angular.js 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134
  1. /**
  2. * @license AngularJS v1.6.2
  3. * (c) 2010-2017 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function() {
  39. var SKIP_INDEXES = 2;
  40. var templateArgs = arguments,
  41. code = templateArgs[0],
  42. message = '[' + (module ? module + ':' : '') + code + '] ',
  43. template = templateArgs[1],
  44. paramPrefix, i;
  45. message += template.replace(/\{\d+\}/g, function(match) {
  46. var index = +match.slice(1, -1),
  47. shiftedIndex = index + SKIP_INDEXES;
  48. if (shiftedIndex < templateArgs.length) {
  49. return toDebugString(templateArgs[shiftedIndex]);
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.6.2/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  57. encodeURIComponent(toDebugString(templateArgs[i]));
  58. }
  59. return new ErrorConstructor(message);
  60. };
  61. }
  62. /* We need to tell ESLint what variables are being exported */
  63. /* exported
  64. angular,
  65. msie,
  66. jqLite,
  67. jQuery,
  68. slice,
  69. splice,
  70. push,
  71. toString,
  72. ngMinErr,
  73. angularModule,
  74. uid,
  75. REGEX_STRING_REGEXP,
  76. VALIDITY_STATE_PROPERTY,
  77. lowercase,
  78. uppercase,
  79. manualLowercase,
  80. manualUppercase,
  81. nodeName_,
  82. isArrayLike,
  83. forEach,
  84. forEachSorted,
  85. reverseParams,
  86. nextUid,
  87. setHashKey,
  88. extend,
  89. toInt,
  90. inherit,
  91. merge,
  92. noop,
  93. identity,
  94. valueFn,
  95. isUndefined,
  96. isDefined,
  97. isObject,
  98. isBlankObject,
  99. isString,
  100. isNumber,
  101. isNumberNaN,
  102. isDate,
  103. isArray,
  104. isFunction,
  105. isRegExp,
  106. isWindow,
  107. isScope,
  108. isFile,
  109. isFormData,
  110. isBlob,
  111. isBoolean,
  112. isPromiseLike,
  113. trim,
  114. escapeForRegexp,
  115. isElement,
  116. makeMap,
  117. includes,
  118. arrayRemove,
  119. copy,
  120. equals,
  121. csp,
  122. jq,
  123. concat,
  124. sliceArgs,
  125. bind,
  126. toJsonReplacer,
  127. toJson,
  128. fromJson,
  129. convertTimezoneToLocal,
  130. timezoneToOffset,
  131. startingTag,
  132. tryDecodeURIComponent,
  133. parseKeyValue,
  134. toKeyValue,
  135. encodeUriSegment,
  136. encodeUriQuery,
  137. angularInit,
  138. bootstrap,
  139. getTestability,
  140. snake_case,
  141. bindJQuery,
  142. assertArg,
  143. assertArgFn,
  144. assertNotHasOwnProperty,
  145. getter,
  146. getBlockNodes,
  147. hasOwnProperty,
  148. createMap,
  149. stringify,
  150. NODE_TYPE_ELEMENT,
  151. NODE_TYPE_ATTRIBUTE,
  152. NODE_TYPE_TEXT,
  153. NODE_TYPE_COMMENT,
  154. NODE_TYPE_DOCUMENT,
  155. NODE_TYPE_DOCUMENT_FRAGMENT
  156. */
  157. ////////////////////////////////////
  158. /**
  159. * @ngdoc module
  160. * @name ng
  161. * @module ng
  162. * @installation
  163. * @description
  164. *
  165. * # ng (core module)
  166. * The ng module is loaded by default when an AngularJS application is started. The module itself
  167. * contains the essential components for an AngularJS application to function. The table below
  168. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  169. * components available within this core module.
  170. *
  171. * <div doc-module-components="ng"></div>
  172. */
  173. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  174. // The name of a form control's ValidityState property.
  175. // This is used so that it's possible for internal tests to create mock ValidityStates.
  176. var VALIDITY_STATE_PROPERTY = 'validity';
  177. var hasOwnProperty = Object.prototype.hasOwnProperty;
  178. /**
  179. * @ngdoc function
  180. * @name angular.lowercase
  181. * @module ng
  182. * @kind function
  183. *
  184. * @deprecated
  185. * sinceVersion="1.5.0"
  186. * removeVersion="1.7.0"
  187. * Use [String.prototype.toLowerCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) instead.
  188. *
  189. * @description Converts the specified string to lowercase.
  190. * @param {string} string String to be converted to lowercase.
  191. * @returns {string} Lowercased string.
  192. */
  193. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  194. /**
  195. * @ngdoc function
  196. * @name angular.uppercase
  197. * @module ng
  198. * @kind function
  199. *
  200. * @deprecated
  201. * sinceVersion="1.5.0"
  202. * removeVersion="1.7.0"
  203. * Use [String.prototype.toUpperCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) instead.
  204. *
  205. * @description Converts the specified string to uppercase.
  206. * @param {string} string String to be converted to uppercase.
  207. * @returns {string} Uppercased string.
  208. */
  209. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  210. var manualLowercase = function(s) {
  211. /* eslint-disable no-bitwise */
  212. return isString(s)
  213. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  214. : s;
  215. /* eslint-enable */
  216. };
  217. var manualUppercase = function(s) {
  218. /* eslint-disable no-bitwise */
  219. return isString(s)
  220. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  221. : s;
  222. /* eslint-enable */
  223. };
  224. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  225. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  226. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  227. if ('i' !== 'I'.toLowerCase()) {
  228. lowercase = manualLowercase;
  229. uppercase = manualUppercase;
  230. }
  231. var
  232. msie, // holds major version number for IE, or NaN if UA is not IE.
  233. jqLite, // delay binding since jQuery could be loaded after us.
  234. jQuery, // delay binding
  235. slice = [].slice,
  236. splice = [].splice,
  237. push = [].push,
  238. toString = Object.prototype.toString,
  239. getPrototypeOf = Object.getPrototypeOf,
  240. ngMinErr = minErr('ng'),
  241. /** @name angular */
  242. angular = window.angular || (window.angular = {}),
  243. angularModule,
  244. uid = 0;
  245. // Support: IE 9-11 only
  246. /**
  247. * documentMode is an IE-only property
  248. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  249. */
  250. msie = window.document.documentMode;
  251. /**
  252. * @private
  253. * @param {*} obj
  254. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  255. * String ...)
  256. */
  257. function isArrayLike(obj) {
  258. // `null`, `undefined` and `window` are not array-like
  259. if (obj == null || isWindow(obj)) return false;
  260. // arrays, strings and jQuery/jqLite objects are array like
  261. // * jqLite is either the jQuery or jqLite constructor function
  262. // * we have to check the existence of jqLite first as this method is called
  263. // via the forEach method when constructing the jqLite object in the first place
  264. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  265. // Support: iOS 8.2 (not reproducible in simulator)
  266. // "length" in obj used to prevent JIT error (gh-11508)
  267. var length = 'length' in Object(obj) && obj.length;
  268. // NodeList objects (with `item` method) and
  269. // other objects with suitable length characteristics are array-like
  270. return isNumber(length) &&
  271. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');
  272. }
  273. /**
  274. * @ngdoc function
  275. * @name angular.forEach
  276. * @module ng
  277. * @kind function
  278. *
  279. * @description
  280. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  281. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  282. * is the value of an object property or an array element, `key` is the object property key or
  283. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  284. *
  285. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  286. * using the `hasOwnProperty` method.
  287. *
  288. * Unlike ES262's
  289. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  290. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  291. * return the value provided.
  292. *
  293. ```js
  294. var values = {name: 'misko', gender: 'male'};
  295. var log = [];
  296. angular.forEach(values, function(value, key) {
  297. this.push(key + ': ' + value);
  298. }, log);
  299. expect(log).toEqual(['name: misko', 'gender: male']);
  300. ```
  301. *
  302. * @param {Object|Array} obj Object to iterate over.
  303. * @param {Function} iterator Iterator function.
  304. * @param {Object=} context Object to become context (`this`) for the iterator function.
  305. * @returns {Object|Array} Reference to `obj`.
  306. */
  307. function forEach(obj, iterator, context) {
  308. var key, length;
  309. if (obj) {
  310. if (isFunction(obj)) {
  311. for (key in obj) {
  312. if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
  313. iterator.call(context, obj[key], key, obj);
  314. }
  315. }
  316. } else if (isArray(obj) || isArrayLike(obj)) {
  317. var isPrimitive = typeof obj !== 'object';
  318. for (key = 0, length = obj.length; key < length; key++) {
  319. if (isPrimitive || key in obj) {
  320. iterator.call(context, obj[key], key, obj);
  321. }
  322. }
  323. } else if (obj.forEach && obj.forEach !== forEach) {
  324. obj.forEach(iterator, context, obj);
  325. } else if (isBlankObject(obj)) {
  326. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  327. for (key in obj) {
  328. iterator.call(context, obj[key], key, obj);
  329. }
  330. } else if (typeof obj.hasOwnProperty === 'function') {
  331. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  332. for (key in obj) {
  333. if (obj.hasOwnProperty(key)) {
  334. iterator.call(context, obj[key], key, obj);
  335. }
  336. }
  337. } else {
  338. // Slow path for objects which do not have a method `hasOwnProperty`
  339. for (key in obj) {
  340. if (hasOwnProperty.call(obj, key)) {
  341. iterator.call(context, obj[key], key, obj);
  342. }
  343. }
  344. }
  345. }
  346. return obj;
  347. }
  348. function forEachSorted(obj, iterator, context) {
  349. var keys = Object.keys(obj).sort();
  350. for (var i = 0; i < keys.length; i++) {
  351. iterator.call(context, obj[keys[i]], keys[i]);
  352. }
  353. return keys;
  354. }
  355. /**
  356. * when using forEach the params are value, key, but it is often useful to have key, value.
  357. * @param {function(string, *)} iteratorFn
  358. * @returns {function(*, string)}
  359. */
  360. function reverseParams(iteratorFn) {
  361. return function(value, key) {iteratorFn(key, value);};
  362. }
  363. /**
  364. * A consistent way of creating unique IDs in angular.
  365. *
  366. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  367. * we hit number precision issues in JavaScript.
  368. *
  369. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  370. *
  371. * @returns {number} an unique alpha-numeric string
  372. */
  373. function nextUid() {
  374. return ++uid;
  375. }
  376. /**
  377. * Set or clear the hashkey for an object.
  378. * @param obj object
  379. * @param h the hashkey (!truthy to delete the hashkey)
  380. */
  381. function setHashKey(obj, h) {
  382. if (h) {
  383. obj.$$hashKey = h;
  384. } else {
  385. delete obj.$$hashKey;
  386. }
  387. }
  388. function baseExtend(dst, objs, deep) {
  389. var h = dst.$$hashKey;
  390. for (var i = 0, ii = objs.length; i < ii; ++i) {
  391. var obj = objs[i];
  392. if (!isObject(obj) && !isFunction(obj)) continue;
  393. var keys = Object.keys(obj);
  394. for (var j = 0, jj = keys.length; j < jj; j++) {
  395. var key = keys[j];
  396. var src = obj[key];
  397. if (deep && isObject(src)) {
  398. if (isDate(src)) {
  399. dst[key] = new Date(src.valueOf());
  400. } else if (isRegExp(src)) {
  401. dst[key] = new RegExp(src);
  402. } else if (src.nodeName) {
  403. dst[key] = src.cloneNode(true);
  404. } else if (isElement(src)) {
  405. dst[key] = src.clone();
  406. } else {
  407. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  408. baseExtend(dst[key], [src], true);
  409. }
  410. } else {
  411. dst[key] = src;
  412. }
  413. }
  414. }
  415. setHashKey(dst, h);
  416. return dst;
  417. }
  418. /**
  419. * @ngdoc function
  420. * @name angular.extend
  421. * @module ng
  422. * @kind function
  423. *
  424. * @description
  425. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  426. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  427. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  428. *
  429. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  430. * {@link angular.merge} for this.
  431. *
  432. * @param {Object} dst Destination object.
  433. * @param {...Object} src Source object(s).
  434. * @returns {Object} Reference to `dst`.
  435. */
  436. function extend(dst) {
  437. return baseExtend(dst, slice.call(arguments, 1), false);
  438. }
  439. /**
  440. * @ngdoc function
  441. * @name angular.merge
  442. * @module ng
  443. * @kind function
  444. *
  445. * @description
  446. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  447. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  448. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  449. *
  450. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  451. * objects, performing a deep copy.
  452. *
  453. * @param {Object} dst Destination object.
  454. * @param {...Object} src Source object(s).
  455. * @returns {Object} Reference to `dst`.
  456. */
  457. function merge(dst) {
  458. return baseExtend(dst, slice.call(arguments, 1), true);
  459. }
  460. function toInt(str) {
  461. return parseInt(str, 10);
  462. }
  463. var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
  464. // eslint-disable-next-line no-self-compare
  465. return num !== num;
  466. };
  467. function inherit(parent, extra) {
  468. return extend(Object.create(parent), extra);
  469. }
  470. /**
  471. * @ngdoc function
  472. * @name angular.noop
  473. * @module ng
  474. * @kind function
  475. *
  476. * @description
  477. * A function that performs no operations. This function can be useful when writing code in the
  478. * functional style.
  479. ```js
  480. function foo(callback) {
  481. var result = calculateResult();
  482. (callback || angular.noop)(result);
  483. }
  484. ```
  485. */
  486. function noop() {}
  487. noop.$inject = [];
  488. /**
  489. * @ngdoc function
  490. * @name angular.identity
  491. * @module ng
  492. * @kind function
  493. *
  494. * @description
  495. * A function that returns its first argument. This function is useful when writing code in the
  496. * functional style.
  497. *
  498. ```js
  499. function transformer(transformationFn, value) {
  500. return (transformationFn || angular.identity)(value);
  501. };
  502. // E.g.
  503. function getResult(fn, input) {
  504. return (fn || angular.identity)(input);
  505. };
  506. getResult(function(n) { return n * 2; }, 21); // returns 42
  507. getResult(null, 21); // returns 21
  508. getResult(undefined, 21); // returns 21
  509. ```
  510. *
  511. * @param {*} value to be returned.
  512. * @returns {*} the value passed in.
  513. */
  514. function identity($) {return $;}
  515. identity.$inject = [];
  516. function valueFn(value) {return function valueRef() {return value;};}
  517. function hasCustomToString(obj) {
  518. return isFunction(obj.toString) && obj.toString !== toString;
  519. }
  520. /**
  521. * @ngdoc function
  522. * @name angular.isUndefined
  523. * @module ng
  524. * @kind function
  525. *
  526. * @description
  527. * Determines if a reference is undefined.
  528. *
  529. * @param {*} value Reference to check.
  530. * @returns {boolean} True if `value` is undefined.
  531. */
  532. function isUndefined(value) {return typeof value === 'undefined';}
  533. /**
  534. * @ngdoc function
  535. * @name angular.isDefined
  536. * @module ng
  537. * @kind function
  538. *
  539. * @description
  540. * Determines if a reference is defined.
  541. *
  542. * @param {*} value Reference to check.
  543. * @returns {boolean} True if `value` is defined.
  544. */
  545. function isDefined(value) {return typeof value !== 'undefined';}
  546. /**
  547. * @ngdoc function
  548. * @name angular.isObject
  549. * @module ng
  550. * @kind function
  551. *
  552. * @description
  553. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  554. * considered to be objects. Note that JavaScript arrays are objects.
  555. *
  556. * @param {*} value Reference to check.
  557. * @returns {boolean} True if `value` is an `Object` but not `null`.
  558. */
  559. function isObject(value) {
  560. // http://jsperf.com/isobject4
  561. return value !== null && typeof value === 'object';
  562. }
  563. /**
  564. * Determine if a value is an object with a null prototype
  565. *
  566. * @returns {boolean} True if `value` is an `Object` with a null prototype
  567. */
  568. function isBlankObject(value) {
  569. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  570. }
  571. /**
  572. * @ngdoc function
  573. * @name angular.isString
  574. * @module ng
  575. * @kind function
  576. *
  577. * @description
  578. * Determines if a reference is a `String`.
  579. *
  580. * @param {*} value Reference to check.
  581. * @returns {boolean} True if `value` is a `String`.
  582. */
  583. function isString(value) {return typeof value === 'string';}
  584. /**
  585. * @ngdoc function
  586. * @name angular.isNumber
  587. * @module ng
  588. * @kind function
  589. *
  590. * @description
  591. * Determines if a reference is a `Number`.
  592. *
  593. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  594. *
  595. * If you wish to exclude these then you can use the native
  596. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  597. * method.
  598. *
  599. * @param {*} value Reference to check.
  600. * @returns {boolean} True if `value` is a `Number`.
  601. */
  602. function isNumber(value) {return typeof value === 'number';}
  603. /**
  604. * @ngdoc function
  605. * @name angular.isDate
  606. * @module ng
  607. * @kind function
  608. *
  609. * @description
  610. * Determines if a value is a date.
  611. *
  612. * @param {*} value Reference to check.
  613. * @returns {boolean} True if `value` is a `Date`.
  614. */
  615. function isDate(value) {
  616. return toString.call(value) === '[object Date]';
  617. }
  618. /**
  619. * @ngdoc function
  620. * @name angular.isArray
  621. * @module ng
  622. * @kind function
  623. *
  624. * @description
  625. * Determines if a reference is an `Array`. Alias of Array.isArray.
  626. *
  627. * @param {*} value Reference to check.
  628. * @returns {boolean} True if `value` is an `Array`.
  629. */
  630. var isArray = Array.isArray;
  631. /**
  632. * @ngdoc function
  633. * @name angular.isFunction
  634. * @module ng
  635. * @kind function
  636. *
  637. * @description
  638. * Determines if a reference is a `Function`.
  639. *
  640. * @param {*} value Reference to check.
  641. * @returns {boolean} True if `value` is a `Function`.
  642. */
  643. function isFunction(value) {return typeof value === 'function';}
  644. /**
  645. * Determines if a value is a regular expression object.
  646. *
  647. * @private
  648. * @param {*} value Reference to check.
  649. * @returns {boolean} True if `value` is a `RegExp`.
  650. */
  651. function isRegExp(value) {
  652. return toString.call(value) === '[object RegExp]';
  653. }
  654. /**
  655. * Checks if `obj` is a window object.
  656. *
  657. * @private
  658. * @param {*} obj Object to check
  659. * @returns {boolean} True if `obj` is a window obj.
  660. */
  661. function isWindow(obj) {
  662. return obj && obj.window === obj;
  663. }
  664. function isScope(obj) {
  665. return obj && obj.$evalAsync && obj.$watch;
  666. }
  667. function isFile(obj) {
  668. return toString.call(obj) === '[object File]';
  669. }
  670. function isFormData(obj) {
  671. return toString.call(obj) === '[object FormData]';
  672. }
  673. function isBlob(obj) {
  674. return toString.call(obj) === '[object Blob]';
  675. }
  676. function isBoolean(value) {
  677. return typeof value === 'boolean';
  678. }
  679. function isPromiseLike(obj) {
  680. return obj && isFunction(obj.then);
  681. }
  682. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
  683. function isTypedArray(value) {
  684. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  685. }
  686. function isArrayBuffer(obj) {
  687. return toString.call(obj) === '[object ArrayBuffer]';
  688. }
  689. var trim = function(value) {
  690. return isString(value) ? value.trim() : value;
  691. };
  692. // Copied from:
  693. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  694. // Prereq: s is a string.
  695. var escapeForRegexp = function(s) {
  696. return s
  697. .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
  698. // eslint-disable-next-line no-control-regex
  699. .replace(/\x08/g, '\\x08');
  700. };
  701. /**
  702. * @ngdoc function
  703. * @name angular.isElement
  704. * @module ng
  705. * @kind function
  706. *
  707. * @description
  708. * Determines if a reference is a DOM element (or wrapped jQuery element).
  709. *
  710. * @param {*} value Reference to check.
  711. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  712. */
  713. function isElement(node) {
  714. return !!(node &&
  715. (node.nodeName // We are a direct element.
  716. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  717. }
  718. /**
  719. * @param str 'key1,key2,...'
  720. * @returns {object} in the form of {key1:true, key2:true, ...}
  721. */
  722. function makeMap(str) {
  723. var obj = {}, items = str.split(','), i;
  724. for (i = 0; i < items.length; i++) {
  725. obj[items[i]] = true;
  726. }
  727. return obj;
  728. }
  729. function nodeName_(element) {
  730. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  731. }
  732. function includes(array, obj) {
  733. return Array.prototype.indexOf.call(array, obj) !== -1;
  734. }
  735. function arrayRemove(array, value) {
  736. var index = array.indexOf(value);
  737. if (index >= 0) {
  738. array.splice(index, 1);
  739. }
  740. return index;
  741. }
  742. /**
  743. * @ngdoc function
  744. * @name angular.copy
  745. * @module ng
  746. * @kind function
  747. *
  748. * @description
  749. * Creates a deep copy of `source`, which should be an object or an array.
  750. *
  751. * * If no destination is supplied, a copy of the object or array is created.
  752. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  753. * are deleted and then all elements/properties from the source are copied to it.
  754. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  755. * * If `source` is identical to `destination` an exception will be thrown.
  756. *
  757. * <br />
  758. * <div class="alert alert-warning">
  759. * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
  760. * and on `destination`) will be ignored.
  761. * </div>
  762. *
  763. * @param {*} source The source that will be used to make a copy.
  764. * Can be any type, including primitives, `null`, and `undefined`.
  765. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  766. * provided, must be of the same type as `source`.
  767. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  768. *
  769. * @example
  770. <example module="copyExample" name="angular-copy">
  771. <file name="index.html">
  772. <div ng-controller="ExampleController">
  773. <form novalidate class="simple-form">
  774. <label>Name: <input type="text" ng-model="user.name" /></label><br />
  775. <label>Age: <input type="number" ng-model="user.age" /></label><br />
  776. Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
  777. <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
  778. <button ng-click="reset()">RESET</button>
  779. <button ng-click="update(user)">SAVE</button>
  780. </form>
  781. <pre>form = {{user | json}}</pre>
  782. <pre>master = {{master | json}}</pre>
  783. </div>
  784. </file>
  785. <file name="script.js">
  786. // Module: copyExample
  787. angular.
  788. module('copyExample', []).
  789. controller('ExampleController', ['$scope', function($scope) {
  790. $scope.master = {};
  791. $scope.reset = function() {
  792. // Example with 1 argument
  793. $scope.user = angular.copy($scope.master);
  794. };
  795. $scope.update = function(user) {
  796. // Example with 2 arguments
  797. angular.copy(user, $scope.master);
  798. };
  799. $scope.reset();
  800. }]);
  801. </file>
  802. </example>
  803. */
  804. function copy(source, destination) {
  805. var stackSource = [];
  806. var stackDest = [];
  807. if (destination) {
  808. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  809. throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
  810. }
  811. if (source === destination) {
  812. throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
  813. }
  814. // Empty the destination object
  815. if (isArray(destination)) {
  816. destination.length = 0;
  817. } else {
  818. forEach(destination, function(value, key) {
  819. if (key !== '$$hashKey') {
  820. delete destination[key];
  821. }
  822. });
  823. }
  824. stackSource.push(source);
  825. stackDest.push(destination);
  826. return copyRecurse(source, destination);
  827. }
  828. return copyElement(source);
  829. function copyRecurse(source, destination) {
  830. var h = destination.$$hashKey;
  831. var key;
  832. if (isArray(source)) {
  833. for (var i = 0, ii = source.length; i < ii; i++) {
  834. destination.push(copyElement(source[i]));
  835. }
  836. } else if (isBlankObject(source)) {
  837. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  838. for (key in source) {
  839. destination[key] = copyElement(source[key]);
  840. }
  841. } else if (source && typeof source.hasOwnProperty === 'function') {
  842. // Slow path, which must rely on hasOwnProperty
  843. for (key in source) {
  844. if (source.hasOwnProperty(key)) {
  845. destination[key] = copyElement(source[key]);
  846. }
  847. }
  848. } else {
  849. // Slowest path --- hasOwnProperty can't be called as a method
  850. for (key in source) {
  851. if (hasOwnProperty.call(source, key)) {
  852. destination[key] = copyElement(source[key]);
  853. }
  854. }
  855. }
  856. setHashKey(destination, h);
  857. return destination;
  858. }
  859. function copyElement(source) {
  860. // Simple values
  861. if (!isObject(source)) {
  862. return source;
  863. }
  864. // Already copied values
  865. var index = stackSource.indexOf(source);
  866. if (index !== -1) {
  867. return stackDest[index];
  868. }
  869. if (isWindow(source) || isScope(source)) {
  870. throw ngMinErr('cpws',
  871. 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
  872. }
  873. var needsRecurse = false;
  874. var destination = copyType(source);
  875. if (destination === undefined) {
  876. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  877. needsRecurse = true;
  878. }
  879. stackSource.push(source);
  880. stackDest.push(destination);
  881. return needsRecurse
  882. ? copyRecurse(source, destination)
  883. : destination;
  884. }
  885. function copyType(source) {
  886. switch (toString.call(source)) {
  887. case '[object Int8Array]':
  888. case '[object Int16Array]':
  889. case '[object Int32Array]':
  890. case '[object Float32Array]':
  891. case '[object Float64Array]':
  892. case '[object Uint8Array]':
  893. case '[object Uint8ClampedArray]':
  894. case '[object Uint16Array]':
  895. case '[object Uint32Array]':
  896. return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
  897. case '[object ArrayBuffer]':
  898. // Support: IE10
  899. if (!source.slice) {
  900. // If we're in this case we know the environment supports ArrayBuffer
  901. /* eslint-disable no-undef */
  902. var copied = new ArrayBuffer(source.byteLength);
  903. new Uint8Array(copied).set(new Uint8Array(source));
  904. /* eslint-enable */
  905. return copied;
  906. }
  907. return source.slice(0);
  908. case '[object Boolean]':
  909. case '[object Number]':
  910. case '[object String]':
  911. case '[object Date]':
  912. return new source.constructor(source.valueOf());
  913. case '[object RegExp]':
  914. var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
  915. re.lastIndex = source.lastIndex;
  916. return re;
  917. case '[object Blob]':
  918. return new source.constructor([source], {type: source.type});
  919. }
  920. if (isFunction(source.cloneNode)) {
  921. return source.cloneNode(true);
  922. }
  923. }
  924. }
  925. /**
  926. * @ngdoc function
  927. * @name angular.equals
  928. * @module ng
  929. * @kind function
  930. *
  931. * @description
  932. * Determines if two objects or two values are equivalent. Supports value types, regular
  933. * expressions, arrays and objects.
  934. *
  935. * Two objects or values are considered equivalent if at least one of the following is true:
  936. *
  937. * * Both objects or values pass `===` comparison.
  938. * * Both objects or values are of the same type and all of their properties are equal by
  939. * comparing them with `angular.equals`.
  940. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  941. * * Both values represent the same regular expression (In JavaScript,
  942. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  943. * representation matches).
  944. *
  945. * During a property comparison, properties of `function` type and properties with names
  946. * that begin with `$` are ignored.
  947. *
  948. * Scope and DOMWindow objects are being compared only by identify (`===`).
  949. *
  950. * @param {*} o1 Object or value to compare.
  951. * @param {*} o2 Object or value to compare.
  952. * @returns {boolean} True if arguments are equal.
  953. *
  954. * @example
  955. <example module="equalsExample" name="equalsExample">
  956. <file name="index.html">
  957. <div ng-controller="ExampleController">
  958. <form novalidate>
  959. <h3>User 1</h3>
  960. Name: <input type="text" ng-model="user1.name">
  961. Age: <input type="number" ng-model="user1.age">
  962. <h3>User 2</h3>
  963. Name: <input type="text" ng-model="user2.name">
  964. Age: <input type="number" ng-model="user2.age">
  965. <div>
  966. <br/>
  967. <input type="button" value="Compare" ng-click="compare()">
  968. </div>
  969. User 1: <pre>{{user1 | json}}</pre>
  970. User 2: <pre>{{user2 | json}}</pre>
  971. Equal: <pre>{{result}}</pre>
  972. </form>
  973. </div>
  974. </file>
  975. <file name="script.js">
  976. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  977. $scope.user1 = {};
  978. $scope.user2 = {};
  979. $scope.compare = function() {
  980. $scope.result = angular.equals($scope.user1, $scope.user2);
  981. };
  982. }]);
  983. </file>
  984. </example>
  985. */
  986. function equals(o1, o2) {
  987. if (o1 === o2) return true;
  988. if (o1 === null || o2 === null) return false;
  989. // eslint-disable-next-line no-self-compare
  990. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  991. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  992. if (t1 === t2 && t1 === 'object') {
  993. if (isArray(o1)) {
  994. if (!isArray(o2)) return false;
  995. if ((length = o1.length) === o2.length) {
  996. for (key = 0; key < length; key++) {
  997. if (!equals(o1[key], o2[key])) return false;
  998. }
  999. return true;
  1000. }
  1001. } else if (isDate(o1)) {
  1002. if (!isDate(o2)) return false;
  1003. return equals(o1.getTime(), o2.getTime());
  1004. } else if (isRegExp(o1)) {
  1005. if (!isRegExp(o2)) return false;
  1006. return o1.toString() === o2.toString();
  1007. } else {
  1008. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  1009. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  1010. keySet = createMap();
  1011. for (key in o1) {
  1012. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  1013. if (!equals(o1[key], o2[key])) return false;
  1014. keySet[key] = true;
  1015. }
  1016. for (key in o2) {
  1017. if (!(key in keySet) &&
  1018. key.charAt(0) !== '$' &&
  1019. isDefined(o2[key]) &&
  1020. !isFunction(o2[key])) return false;
  1021. }
  1022. return true;
  1023. }
  1024. }
  1025. return false;
  1026. }
  1027. var csp = function() {
  1028. if (!isDefined(csp.rules)) {
  1029. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  1030. window.document.querySelector('[data-ng-csp]'));
  1031. if (ngCspElement) {
  1032. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  1033. ngCspElement.getAttribute('data-ng-csp');
  1034. csp.rules = {
  1035. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  1036. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  1037. };
  1038. } else {
  1039. csp.rules = {
  1040. noUnsafeEval: noUnsafeEval(),
  1041. noInlineStyle: false
  1042. };
  1043. }
  1044. }
  1045. return csp.rules;
  1046. function noUnsafeEval() {
  1047. try {
  1048. // eslint-disable-next-line no-new, no-new-func
  1049. new Function('');
  1050. return false;
  1051. } catch (e) {
  1052. return true;
  1053. }
  1054. }
  1055. };
  1056. /**
  1057. * @ngdoc directive
  1058. * @module ng
  1059. * @name ngJq
  1060. *
  1061. * @element ANY
  1062. * @param {string=} ngJq the name of the library available under `window`
  1063. * to be used for angular.element
  1064. * @description
  1065. * Use this directive to force the angular.element library. This should be
  1066. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1067. * the jquery variable under window (eg. jQuery).
  1068. *
  1069. * Since angular looks for this directive when it is loaded (doesn't wait for the
  1070. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1071. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1072. * others ignored.
  1073. *
  1074. * @example
  1075. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1076. ```html
  1077. <!doctype html>
  1078. <html ng-app ng-jq>
  1079. ...
  1080. ...
  1081. </html>
  1082. ```
  1083. * @example
  1084. * This example shows how to use a jQuery based library of a different name.
  1085. * The library name must be available at the top most 'window'.
  1086. ```html
  1087. <!doctype html>
  1088. <html ng-app ng-jq="jQueryLib">
  1089. ...
  1090. ...
  1091. </html>
  1092. ```
  1093. */
  1094. var jq = function() {
  1095. if (isDefined(jq.name_)) return jq.name_;
  1096. var el;
  1097. var i, ii = ngAttrPrefixes.length, prefix, name;
  1098. for (i = 0; i < ii; ++i) {
  1099. prefix = ngAttrPrefixes[i];
  1100. el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
  1101. if (el) {
  1102. name = el.getAttribute(prefix + 'jq');
  1103. break;
  1104. }
  1105. }
  1106. return (jq.name_ = name);
  1107. };
  1108. function concat(array1, array2, index) {
  1109. return array1.concat(slice.call(array2, index));
  1110. }
  1111. function sliceArgs(args, startIndex) {
  1112. return slice.call(args, startIndex || 0);
  1113. }
  1114. /**
  1115. * @ngdoc function
  1116. * @name angular.bind
  1117. * @module ng
  1118. * @kind function
  1119. *
  1120. * @description
  1121. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1122. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1123. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1124. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1125. *
  1126. * @param {Object} self Context which `fn` should be evaluated in.
  1127. * @param {function()} fn Function to be bound.
  1128. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1129. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1130. */
  1131. function bind(self, fn) {
  1132. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1133. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1134. return curryArgs.length
  1135. ? function() {
  1136. return arguments.length
  1137. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1138. : fn.apply(self, curryArgs);
  1139. }
  1140. : function() {
  1141. return arguments.length
  1142. ? fn.apply(self, arguments)
  1143. : fn.call(self);
  1144. };
  1145. } else {
  1146. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1147. return fn;
  1148. }
  1149. }
  1150. function toJsonReplacer(key, value) {
  1151. var val = value;
  1152. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1153. val = undefined;
  1154. } else if (isWindow(value)) {
  1155. val = '$WINDOW';
  1156. } else if (value && window.document === value) {
  1157. val = '$DOCUMENT';
  1158. } else if (isScope(value)) {
  1159. val = '$SCOPE';
  1160. }
  1161. return val;
  1162. }
  1163. /**
  1164. * @ngdoc function
  1165. * @name angular.toJson
  1166. * @module ng
  1167. * @kind function
  1168. *
  1169. * @description
  1170. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1171. * stripped since angular uses this notation internally.
  1172. *
  1173. * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
  1174. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1175. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1176. * @returns {string|undefined} JSON-ified string representing `obj`.
  1177. * @knownIssue
  1178. *
  1179. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1180. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1181. * `Date.prototype.toJSON` method as follows:
  1182. *
  1183. * ```
  1184. * var _DatetoJSON = Date.prototype.toJSON;
  1185. * Date.prototype.toJSON = function() {
  1186. * try {
  1187. * return _DatetoJSON.call(this);
  1188. * } catch(e) {
  1189. * if (e instanceof RangeError) {
  1190. * return null;
  1191. * }
  1192. * throw e;
  1193. * }
  1194. * };
  1195. * ```
  1196. *
  1197. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1198. */
  1199. function toJson(obj, pretty) {
  1200. if (isUndefined(obj)) return undefined;
  1201. if (!isNumber(pretty)) {
  1202. pretty = pretty ? 2 : null;
  1203. }
  1204. return JSON.stringify(obj, toJsonReplacer, pretty);
  1205. }
  1206. /**
  1207. * @ngdoc function
  1208. * @name angular.fromJson
  1209. * @module ng
  1210. * @kind function
  1211. *
  1212. * @description
  1213. * Deserializes a JSON string.
  1214. *
  1215. * @param {string} json JSON string to deserialize.
  1216. * @returns {Object|Array|string|number} Deserialized JSON string.
  1217. */
  1218. function fromJson(json) {
  1219. return isString(json)
  1220. ? JSON.parse(json)
  1221. : json;
  1222. }
  1223. var ALL_COLONS = /:/g;
  1224. function timezoneToOffset(timezone, fallback) {
  1225. // Support: IE 9-11 only, Edge 13-14+
  1226. // IE/Edge do not "understand" colon (`:`) in timezone
  1227. timezone = timezone.replace(ALL_COLONS, '');
  1228. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1229. return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1230. }
  1231. function addDateMinutes(date, minutes) {
  1232. date = new Date(date.getTime());
  1233. date.setMinutes(date.getMinutes() + minutes);
  1234. return date;
  1235. }
  1236. function convertTimezoneToLocal(date, timezone, reverse) {
  1237. reverse = reverse ? -1 : 1;
  1238. var dateTimezoneOffset = date.getTimezoneOffset();
  1239. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1240. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1241. }
  1242. /**
  1243. * @returns {string} Returns the string representation of the element.
  1244. */
  1245. function startingTag(element) {
  1246. element = jqLite(element).clone();
  1247. try {
  1248. // turns out IE does not let you set .html() on elements which
  1249. // are not allowed to have children. So we just ignore it.
  1250. element.empty();
  1251. } catch (e) { /* empty */ }
  1252. var elemHtml = jqLite('<div>').append(element).html();
  1253. try {
  1254. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1255. elemHtml.
  1256. match(/^(<[^>]+>)/)[1].
  1257. replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1258. } catch (e) {
  1259. return lowercase(elemHtml);
  1260. }
  1261. }
  1262. /////////////////////////////////////////////////
  1263. /**
  1264. * Tries to decode the URI component without throwing an exception.
  1265. *
  1266. * @private
  1267. * @param str value potential URI component to check.
  1268. * @returns {boolean} True if `value` can be decoded
  1269. * with the decodeURIComponent function.
  1270. */
  1271. function tryDecodeURIComponent(value) {
  1272. try {
  1273. return decodeURIComponent(value);
  1274. } catch (e) {
  1275. // Ignore any invalid uri component.
  1276. }
  1277. }
  1278. /**
  1279. * Parses an escaped url query string into key-value pairs.
  1280. * @returns {Object.<string,boolean|Array>}
  1281. */
  1282. function parseKeyValue(/**string*/keyValue) {
  1283. var obj = {};
  1284. forEach((keyValue || '').split('&'), function(keyValue) {
  1285. var splitPoint, key, val;
  1286. if (keyValue) {
  1287. key = keyValue = keyValue.replace(/\+/g,'%20');
  1288. splitPoint = keyValue.indexOf('=');
  1289. if (splitPoint !== -1) {
  1290. key = keyValue.substring(0, splitPoint);
  1291. val = keyValue.substring(splitPoint + 1);
  1292. }
  1293. key = tryDecodeURIComponent(key);
  1294. if (isDefined(key)) {
  1295. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1296. if (!hasOwnProperty.call(obj, key)) {
  1297. obj[key] = val;
  1298. } else if (isArray(obj[key])) {
  1299. obj[key].push(val);
  1300. } else {
  1301. obj[key] = [obj[key],val];
  1302. }
  1303. }
  1304. }
  1305. });
  1306. return obj;
  1307. }
  1308. function toKeyValue(obj) {
  1309. var parts = [];
  1310. forEach(obj, function(value, key) {
  1311. if (isArray(value)) {
  1312. forEach(value, function(arrayValue) {
  1313. parts.push(encodeUriQuery(key, true) +
  1314. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1315. });
  1316. } else {
  1317. parts.push(encodeUriQuery(key, true) +
  1318. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1319. }
  1320. });
  1321. return parts.length ? parts.join('&') : '';
  1322. }
  1323. /**
  1324. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1325. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1326. * segments:
  1327. * segment = *pchar
  1328. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1329. * pct-encoded = "%" HEXDIG HEXDIG
  1330. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1331. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1332. * / "*" / "+" / "," / ";" / "="
  1333. */
  1334. function encodeUriSegment(val) {
  1335. return encodeUriQuery(val, true).
  1336. replace(/%26/gi, '&').
  1337. replace(/%3D/gi, '=').
  1338. replace(/%2B/gi, '+');
  1339. }
  1340. /**
  1341. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1342. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1343. * encoded per http://tools.ietf.org/html/rfc3986:
  1344. * query = *( pchar / "/" / "?" )
  1345. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1346. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1347. * pct-encoded = "%" HEXDIG HEXDIG
  1348. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1349. * / "*" / "+" / "," / ";" / "="
  1350. */
  1351. function encodeUriQuery(val, pctEncodeSpaces) {
  1352. return encodeURIComponent(val).
  1353. replace(/%40/gi, '@').
  1354. replace(/%3A/gi, ':').
  1355. replace(/%24/g, '$').
  1356. replace(/%2C/gi, ',').
  1357. replace(/%3B/gi, ';').
  1358. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1359. }
  1360. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1361. function getNgAttribute(element, ngAttr) {
  1362. var attr, i, ii = ngAttrPrefixes.length;
  1363. for (i = 0; i < ii; ++i) {
  1364. attr = ngAttrPrefixes[i] + ngAttr;
  1365. if (isString(attr = element.getAttribute(attr))) {
  1366. return attr;
  1367. }
  1368. }
  1369. return null;
  1370. }
  1371. function allowAutoBootstrap(document) {
  1372. var script = document.currentScript;
  1373. var src = script && script.getAttribute('src');
  1374. if (!src) {
  1375. return true;
  1376. }
  1377. var link = document.createElement('a');
  1378. link.href = src;
  1379. if (document.location.origin === link.origin) {
  1380. // Same-origin resources are always allowed, even for non-whitelisted schemes.
  1381. return true;
  1382. }
  1383. // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
  1384. // This is to prevent angular.js bundled with browser extensions from being used to bypass the
  1385. // content security policy in web pages and other browser extensions.
  1386. switch (link.protocol) {
  1387. case 'http:':
  1388. case 'https:':
  1389. case 'ftp:':
  1390. case 'blob:':
  1391. case 'file:':
  1392. case 'data:':
  1393. return true;
  1394. default:
  1395. return false;
  1396. }
  1397. }
  1398. // Cached as it has to run during loading so that document.currentScript is available.
  1399. var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
  1400. /**
  1401. * @ngdoc directive
  1402. * @name ngApp
  1403. * @module ng
  1404. *
  1405. * @element ANY
  1406. * @param {angular.Module} ngApp an optional application
  1407. * {@link angular.module module} name to load.
  1408. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1409. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1410. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1411. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1412. * tracking down the root of these bugs.
  1413. *
  1414. * @description
  1415. *
  1416. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1417. * designates the **root element** of the application and is typically placed near the root element
  1418. * of the page - e.g. on the `<body>` or `<html>` tags.
  1419. *
  1420. * There are a few things to keep in mind when using `ngApp`:
  1421. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1422. * found in the document will be used to define the root element to auto-bootstrap as an
  1423. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1424. * {@link angular.bootstrap} instead.
  1425. * - AngularJS applications cannot be nested within each other.
  1426. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1427. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1428. * {@link ngRoute.ngView `ngView`}.
  1429. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1430. * causing animations to stop working and making the injector inaccessible from outside the app.
  1431. *
  1432. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1433. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1434. * should contain the application code needed or have dependencies on other modules that will
  1435. * contain the code. See {@link angular.module} for more information.
  1436. *
  1437. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1438. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1439. * would not be resolved to `3`.
  1440. *
  1441. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1442. *
  1443. <example module="ngAppDemo" name="ng-app">
  1444. <file name="index.html">
  1445. <div ng-controller="ngAppDemoController">
  1446. I can add: {{a}} + {{b}} = {{ a+b }}
  1447. </div>
  1448. </file>
  1449. <file name="script.js">
  1450. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1451. $scope.a = 1;
  1452. $scope.b = 2;
  1453. });
  1454. </file>
  1455. </example>
  1456. *
  1457. * Using `ngStrictDi`, you would see something like this:
  1458. *
  1459. <example ng-app-included="true" name="strict-di">
  1460. <file name="index.html">
  1461. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1462. <div ng-controller="GoodController1">
  1463. I can add: {{a}} + {{b}} = {{ a+b }}
  1464. <p>This renders because the controller does not fail to
  1465. instantiate, by using explicit annotation style (see
  1466. script.js for details)
  1467. </p>
  1468. </div>
  1469. <div ng-controller="GoodController2">
  1470. Name: <input ng-model="name"><br />
  1471. Hello, {{name}}!
  1472. <p>This renders because the controller does not fail to
  1473. instantiate, by using explicit annotation style
  1474. (see script.js for details)
  1475. </p>
  1476. </div>
  1477. <div ng-controller="BadController">
  1478. I can add: {{a}} + {{b}} = {{ a+b }}
  1479. <p>The controller could not be instantiated, due to relying
  1480. on automatic function annotations (which are disabled in
  1481. strict mode). As such, the content of this section is not
  1482. interpolated, and there should be an error in your web console.
  1483. </p>
  1484. </div>
  1485. </div>
  1486. </file>
  1487. <file name="script.js">
  1488. angular.module('ngAppStrictDemo', [])
  1489. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1490. // rather than an explicit annotation
  1491. .controller('BadController', function($scope) {
  1492. $scope.a = 1;
  1493. $scope.b = 2;
  1494. })
  1495. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1496. // due to using explicit annotations using the array style and $inject property, respectively.
  1497. .controller('GoodController1', ['$scope', function($scope) {
  1498. $scope.a = 1;
  1499. $scope.b = 2;
  1500. }])
  1501. .controller('GoodController2', GoodController2);
  1502. function GoodController2($scope) {
  1503. $scope.name = 'World';
  1504. }
  1505. GoodController2.$inject = ['$scope'];
  1506. </file>
  1507. <file name="style.css">
  1508. div[ng-controller] {
  1509. margin-bottom: 1em;
  1510. -webkit-border-radius: 4px;
  1511. border-radius: 4px;
  1512. border: 1px solid;
  1513. padding: .5em;
  1514. }
  1515. div[ng-controller^=Good] {
  1516. border-color: #d6e9c6;
  1517. background-color: #dff0d8;
  1518. color: #3c763d;
  1519. }
  1520. div[ng-controller^=Bad] {
  1521. border-color: #ebccd1;
  1522. background-color: #f2dede;
  1523. color: #a94442;
  1524. margin-bottom: 0;
  1525. }
  1526. </file>
  1527. </example>
  1528. */
  1529. function angularInit(element, bootstrap) {
  1530. var appElement,
  1531. module,
  1532. config = {};
  1533. // The element `element` has priority over any other element.
  1534. forEach(ngAttrPrefixes, function(prefix) {
  1535. var name = prefix + 'app';
  1536. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1537. appElement = element;
  1538. module = element.getAttribute(name);
  1539. }
  1540. });
  1541. forEach(ngAttrPrefixes, function(prefix) {
  1542. var name = prefix + 'app';
  1543. var candidate;
  1544. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1545. appElement = candidate;
  1546. module = candidate.getAttribute(name);
  1547. }
  1548. });
  1549. if (appElement) {
  1550. if (!isAutoBootstrapAllowed) {
  1551. window.console.error('Angular: disabling automatic bootstrap. <script> protocol indicates ' +
  1552. 'an extension, document.location.href does not match.');
  1553. return;
  1554. }
  1555. config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
  1556. bootstrap(appElement, module ? [module] : [], config);
  1557. }
  1558. }
  1559. /**
  1560. * @ngdoc function
  1561. * @name angular.bootstrap
  1562. * @module ng
  1563. * @description
  1564. * Use this function to manually start up angular application.
  1565. *
  1566. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1567. *
  1568. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1569. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1570. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1571. * multiple instances of Angular try to work on the DOM.
  1572. *
  1573. * <div class="alert alert-warning">
  1574. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1575. * They must use {@link ng.directive:ngApp ngApp}.
  1576. * </div>
  1577. *
  1578. * <div class="alert alert-warning">
  1579. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1580. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1581. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1582. * causing animations to stop working and making the injector inaccessible from outside the app.
  1583. * </div>
  1584. *
  1585. * ```html
  1586. * <!doctype html>
  1587. * <html>
  1588. * <body>
  1589. * <div ng-controller="WelcomeController">
  1590. * {{greeting}}
  1591. * </div>
  1592. *
  1593. * <script src="angular.js"></script>
  1594. * <script>
  1595. * var app = angular.module('demo', [])
  1596. * .controller('WelcomeController', function($scope) {
  1597. * $scope.greeting = 'Welcome!';
  1598. * });
  1599. * angular.bootstrap(document, ['demo']);
  1600. * </script>
  1601. * </body>
  1602. * </html>
  1603. * ```
  1604. *
  1605. * @param {DOMElement} element DOM element which is the root of angular application.
  1606. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1607. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1608. * function that will be invoked by the injector as a `config` block.
  1609. * See: {@link angular.module modules}
  1610. * @param {Object=} config an object for defining configuration options for the application. The
  1611. * following keys are supported:
  1612. *
  1613. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1614. * assist in finding bugs which break minified code. Defaults to `false`.
  1615. *
  1616. * @returns {auto.$injector} Returns the newly created injector for this app.
  1617. */
  1618. function bootstrap(element, modules, config) {
  1619. if (!isObject(config)) config = {};
  1620. var defaultConfig = {
  1621. strictDi: false
  1622. };
  1623. config = extend(defaultConfig, config);
  1624. var doBootstrap = function() {
  1625. element = jqLite(element);
  1626. if (element.injector()) {
  1627. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1628. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1629. throw ngMinErr(
  1630. 'btstrpd',
  1631. 'App already bootstrapped with this element \'{0}\'',
  1632. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1633. }
  1634. modules = modules || [];
  1635. modules.unshift(['$provide', function($provide) {
  1636. $provide.value('$rootElement', element);
  1637. }]);
  1638. if (config.debugInfoEnabled) {
  1639. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1640. modules.push(['$compileProvider', function($compileProvider) {
  1641. $compileProvider.debugInfoEnabled(true);
  1642. }]);
  1643. }
  1644. modules.unshift('ng');
  1645. var injector = createInjector(modules, config.strictDi);
  1646. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1647. function bootstrapApply(scope, element, compile, injector) {
  1648. scope.$apply(function() {
  1649. element.data('$injector', injector);
  1650. compile(element)(scope);
  1651. });
  1652. }]
  1653. );
  1654. return injector;
  1655. };
  1656. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1657. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1658. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1659. config.debugInfoEnabled = true;
  1660. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1661. }
  1662. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1663. return doBootstrap();
  1664. }
  1665. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1666. angular.resumeBootstrap = function(extraModules) {
  1667. forEach(extraModules, function(module) {
  1668. modules.push(module);
  1669. });
  1670. return doBootstrap();
  1671. };
  1672. if (isFunction(angular.resumeDeferredBootstrap)) {
  1673. angular.resumeDeferredBootstrap();
  1674. }
  1675. }
  1676. /**
  1677. * @ngdoc function
  1678. * @name angular.reloadWithDebugInfo
  1679. * @module ng
  1680. * @description
  1681. * Use this function to reload the current application with debug information turned on.
  1682. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1683. *
  1684. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1685. */
  1686. function reloadWithDebugInfo() {
  1687. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1688. window.location.reload();
  1689. }
  1690. /**
  1691. * @name angular.getTestability
  1692. * @module ng
  1693. * @description
  1694. * Get the testability service for the instance of Angular on the given
  1695. * element.
  1696. * @param {DOMElement} element DOM element which is the root of angular application.
  1697. */
  1698. function getTestability(rootElement) {
  1699. var injector = angular.element(rootElement).injector();
  1700. if (!injector) {
  1701. throw ngMinErr('test',
  1702. 'no injector found for element argument to getTestability');
  1703. }
  1704. return injector.get('$$testability');
  1705. }
  1706. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1707. function snake_case(name, separator) {
  1708. separator = separator || '_';
  1709. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1710. return (pos ? separator : '') + letter.toLowerCase();
  1711. });
  1712. }
  1713. var bindJQueryFired = false;
  1714. function bindJQuery() {
  1715. var originalCleanData;
  1716. if (bindJQueryFired) {
  1717. return;
  1718. }
  1719. // bind to jQuery if present;
  1720. var jqName = jq();
  1721. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1722. !jqName ? undefined : // use jqLite
  1723. window[jqName]; // use jQuery specified by `ngJq`
  1724. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1725. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1726. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1727. // versions. It will not work for sure with jQuery <1.7, though.
  1728. if (jQuery && jQuery.fn.on) {
  1729. jqLite = jQuery;
  1730. extend(jQuery.fn, {
  1731. scope: JQLitePrototype.scope,
  1732. isolateScope: JQLitePrototype.isolateScope,
  1733. controller: /** @type {?} */ (JQLitePrototype).controller,
  1734. injector: JQLitePrototype.injector,
  1735. inheritedData: JQLitePrototype.inheritedData
  1736. });
  1737. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1738. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1739. // the $destroy event on all removed nodes.
  1740. originalCleanData = jQuery.cleanData;
  1741. jQuery.cleanData = function(elems) {
  1742. var events;
  1743. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1744. events = jQuery._data(elem, 'events');
  1745. if (events && events.$destroy) {
  1746. jQuery(elem).triggerHandler('$destroy');
  1747. }
  1748. }
  1749. originalCleanData(elems);
  1750. };
  1751. } else {
  1752. jqLite = JQLite;
  1753. }
  1754. angular.element = jqLite;
  1755. // Prevent double-proxying.
  1756. bindJQueryFired = true;
  1757. }
  1758. /**
  1759. * throw error if the argument is falsy.
  1760. */
  1761. function assertArg(arg, name, reason) {
  1762. if (!arg) {
  1763. throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
  1764. }
  1765. return arg;
  1766. }
  1767. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1768. if (acceptArrayAnnotation && isArray(arg)) {
  1769. arg = arg[arg.length - 1];
  1770. }
  1771. assertArg(isFunction(arg), name, 'not a function, got ' +
  1772. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1773. return arg;
  1774. }
  1775. /**
  1776. * throw error if the name given is hasOwnProperty
  1777. * @param {String} name the name to test
  1778. * @param {String} context the context in which the name is used, such as module or directive
  1779. */
  1780. function assertNotHasOwnProperty(name, context) {
  1781. if (name === 'hasOwnProperty') {
  1782. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1783. }
  1784. }
  1785. /**
  1786. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1787. * @param {Object} obj starting object
  1788. * @param {String} path path to traverse
  1789. * @param {boolean} [bindFnToScope=true]
  1790. * @returns {Object} value as accessible by path
  1791. */
  1792. //TODO(misko): this function needs to be removed
  1793. function getter(obj, path, bindFnToScope) {
  1794. if (!path) return obj;
  1795. var keys = path.split('.');
  1796. var key;
  1797. var lastInstance = obj;
  1798. var len = keys.length;
  1799. for (var i = 0; i < len; i++) {
  1800. key = keys[i];
  1801. if (obj) {
  1802. obj = (lastInstance = obj)[key];
  1803. }
  1804. }
  1805. if (!bindFnToScope && isFunction(obj)) {
  1806. return bind(lastInstance, obj);
  1807. }
  1808. return obj;
  1809. }
  1810. /**
  1811. * Return the DOM siblings between the first and last node in the given array.
  1812. * @param {Array} array like object
  1813. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1814. */
  1815. function getBlockNodes(nodes) {
  1816. // TODO(perf): update `nodes` instead of creating a new object?
  1817. var node = nodes[0];
  1818. var endNode = nodes[nodes.length - 1];
  1819. var blockNodes;
  1820. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1821. if (blockNodes || nodes[i] !== node) {
  1822. if (!blockNodes) {
  1823. blockNodes = jqLite(slice.call(nodes, 0, i));
  1824. }
  1825. blockNodes.push(node);
  1826. }
  1827. }
  1828. return blockNodes || nodes;
  1829. }
  1830. /**
  1831. * Creates a new object without a prototype. This object is useful for lookup without having to
  1832. * guard against prototypically inherited properties via hasOwnProperty.
  1833. *
  1834. * Related micro-benchmarks:
  1835. * - http://jsperf.com/object-create2
  1836. * - http://jsperf.com/proto-map-lookup/2
  1837. * - http://jsperf.com/for-in-vs-object-keys2
  1838. *
  1839. * @returns {Object}
  1840. */
  1841. function createMap() {
  1842. return Object.create(null);
  1843. }
  1844. function stringify(value) {
  1845. if (value == null) { // null || undefined
  1846. return '';
  1847. }
  1848. switch (typeof value) {
  1849. case 'string':
  1850. break;
  1851. case 'number':
  1852. value = '' + value;
  1853. break;
  1854. default:
  1855. if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
  1856. value = value.toString();
  1857. } else {
  1858. value = toJson(value);
  1859. }
  1860. }
  1861. return value;
  1862. }
  1863. var NODE_TYPE_ELEMENT = 1;
  1864. var NODE_TYPE_ATTRIBUTE = 2;
  1865. var NODE_TYPE_TEXT = 3;
  1866. var NODE_TYPE_COMMENT = 8;
  1867. var NODE_TYPE_DOCUMENT = 9;
  1868. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1869. /**
  1870. * @ngdoc type
  1871. * @name angular.Module
  1872. * @module ng
  1873. * @description
  1874. *
  1875. * Interface for configuring angular {@link angular.module modules}.
  1876. */
  1877. function setupModuleLoader(window) {
  1878. var $injectorMinErr = minErr('$injector');
  1879. var ngMinErr = minErr('ng');
  1880. function ensure(obj, name, factory) {
  1881. return obj[name] || (obj[name] = factory());
  1882. }
  1883. var angular = ensure(window, 'angular', Object);
  1884. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1885. angular.$$minErr = angular.$$minErr || minErr;
  1886. return ensure(angular, 'module', function() {
  1887. /** @type {Object.<string, angular.Module>} */
  1888. var modules = {};
  1889. /**
  1890. * @ngdoc function
  1891. * @name angular.module
  1892. * @module ng
  1893. * @description
  1894. *
  1895. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1896. * modules.
  1897. * All modules (angular core or 3rd party) that should be available to an application must be
  1898. * registered using this mechanism.
  1899. *
  1900. * Passing one argument retrieves an existing {@link angular.Module},
  1901. * whereas passing more than one argument creates a new {@link angular.Module}
  1902. *
  1903. *
  1904. * # Module
  1905. *
  1906. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1907. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1908. *
  1909. * ```js
  1910. * // Create a new module
  1911. * var myModule = angular.module('myModule', []);
  1912. *
  1913. * // register a new service
  1914. * myModule.value('appName', 'MyCoolApp');
  1915. *
  1916. * // configure existing services inside initialization blocks.
  1917. * myModule.config(['$locationProvider', function($locationProvider) {
  1918. * // Configure existing providers
  1919. * $locationProvider.hashPrefix('!');
  1920. * }]);
  1921. * ```
  1922. *
  1923. * Then you can create an injector and load your modules like this:
  1924. *
  1925. * ```js
  1926. * var injector = angular.injector(['ng', 'myModule'])
  1927. * ```
  1928. *
  1929. * However it's more likely that you'll just use
  1930. * {@link ng.directive:ngApp ngApp} or
  1931. * {@link angular.bootstrap} to simplify this process for you.
  1932. *
  1933. * @param {!string} name The name of the module to create or retrieve.
  1934. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1935. * unspecified then the module is being retrieved for further configuration.
  1936. * @param {Function=} configFn Optional configuration function for the module. Same as
  1937. * {@link angular.Module#config Module#config()}.
  1938. * @returns {angular.Module} new module with the {@link angular.Module} api.
  1939. */
  1940. return function module(name, requires, configFn) {
  1941. var assertNotHasOwnProperty = function(name, context) {
  1942. if (name === 'hasOwnProperty') {
  1943. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1944. }
  1945. };
  1946. assertNotHasOwnProperty(name, 'module');
  1947. if (requires && modules.hasOwnProperty(name)) {
  1948. modules[name] = null;
  1949. }
  1950. return ensure(modules, name, function() {
  1951. if (!requires) {
  1952. throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
  1953. 'the module name or forgot to load it. If registering a module ensure that you ' +
  1954. 'specify the dependencies as the second argument.', name);
  1955. }
  1956. /** @type {!Array.<Array.<*>>} */
  1957. var invokeQueue = [];
  1958. /** @type {!Array.<Function>} */
  1959. var configBlocks = [];
  1960. /** @type {!Array.<Function>} */
  1961. var runBlocks = [];
  1962. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1963. /** @type {angular.Module} */
  1964. var moduleInstance = {
  1965. // Private state
  1966. _invokeQueue: invokeQueue,
  1967. _configBlocks: configBlocks,
  1968. _runBlocks: runBlocks,
  1969. /**
  1970. * @ngdoc property
  1971. * @name angular.Module#requires
  1972. * @module ng
  1973. *
  1974. * @description
  1975. * Holds the list of modules which the injector will load before the current module is
  1976. * loaded.
  1977. */
  1978. requires: requires,
  1979. /**
  1980. * @ngdoc property
  1981. * @name angular.Module#name
  1982. * @module ng
  1983. *
  1984. * @description
  1985. * Name of the module.
  1986. */
  1987. name: name,
  1988. /**
  1989. * @ngdoc method
  1990. * @name angular.Module#provider
  1991. * @module ng
  1992. * @param {string} name service name
  1993. * @param {Function} providerType Construction function for creating new instance of the
  1994. * service.
  1995. * @description
  1996. * See {@link auto.$provide#provider $provide.provider()}.
  1997. */
  1998. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1999. /**
  2000. * @ngdoc method
  2001. * @name angular.Module#factory
  2002. * @module ng
  2003. * @param {string} name service name
  2004. * @param {Function} providerFunction Function for creating new instance of the service.
  2005. * @description
  2006. * See {@link auto.$provide#factory $provide.factory()}.
  2007. */
  2008. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  2009. /**
  2010. * @ngdoc method
  2011. * @name angular.Module#service
  2012. * @module ng
  2013. * @param {string} name service name
  2014. * @param {Function} constructor A constructor function that will be instantiated.
  2015. * @description
  2016. * See {@link auto.$provide#service $provide.service()}.
  2017. */
  2018. service: invokeLaterAndSetModuleName('$provide', 'service'),
  2019. /**
  2020. * @ngdoc method
  2021. * @name angular.Module#value
  2022. * @module ng
  2023. * @param {string} name service name
  2024. * @param {*} object Service instance object.
  2025. * @description
  2026. * See {@link auto.$provide#value $provide.value()}.
  2027. */
  2028. value: invokeLater('$provide', 'value'),
  2029. /**
  2030. * @ngdoc method
  2031. * @name angular.Module#constant
  2032. * @module ng
  2033. * @param {string} name constant name
  2034. * @param {*} object Constant value.
  2035. * @description
  2036. * Because the constants are fixed, they get applied before other provide methods.
  2037. * See {@link auto.$provide#constant $provide.constant()}.
  2038. */
  2039. constant: invokeLater('$provide', 'constant', 'unshift'),
  2040. /**
  2041. * @ngdoc method
  2042. * @name angular.Module#decorator
  2043. * @module ng
  2044. * @param {string} name The name of the service to decorate.
  2045. * @param {Function} decorFn This function will be invoked when the service needs to be
  2046. * instantiated and should return the decorated service instance.
  2047. * @description
  2048. * See {@link auto.$provide#decorator $provide.decorator()}.
  2049. */
  2050. decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
  2051. /**
  2052. * @ngdoc method
  2053. * @name angular.Module#animation
  2054. * @module ng
  2055. * @param {string} name animation name
  2056. * @param {Function} animationFactory Factory function for creating new instance of an
  2057. * animation.
  2058. * @description
  2059. *
  2060. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  2061. *
  2062. *
  2063. * Defines an animation hook that can be later used with
  2064. * {@link $animate $animate} service and directives that use this service.
  2065. *
  2066. * ```js
  2067. * module.animation('.animation-name', function($inject1, $inject2) {
  2068. * return {
  2069. * eventName : function(element, done) {
  2070. * //code to run the animation
  2071. * //once complete, then run done()
  2072. * return function cancellationFunction(element) {
  2073. * //code to cancel the animation
  2074. * }
  2075. * }
  2076. * }
  2077. * })
  2078. * ```
  2079. *
  2080. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  2081. * {@link ngAnimate ngAnimate module} for more information.
  2082. */
  2083. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  2084. /**
  2085. * @ngdoc method
  2086. * @name angular.Module#filter
  2087. * @module ng
  2088. * @param {string} name Filter name - this must be a valid angular expression identifier
  2089. * @param {Function} filterFactory Factory function for creating new instance of filter.
  2090. * @description
  2091. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  2092. *
  2093. * <div class="alert alert-warning">
  2094. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  2095. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  2096. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  2097. * (`myapp_subsection_filterx`).
  2098. * </div>
  2099. */
  2100. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  2101. /**
  2102. * @ngdoc method
  2103. * @name angular.Module#controller
  2104. * @module ng
  2105. * @param {string|Object} name Controller name, or an object map of controllers where the
  2106. * keys are the names and the values are the constructors.
  2107. * @param {Function} constructor Controller constructor function.
  2108. * @description
  2109. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2110. */
  2111. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2112. /**
  2113. * @ngdoc method
  2114. * @name angular.Module#directive
  2115. * @module ng
  2116. * @param {string|Object} name Directive name, or an object map of directives where the
  2117. * keys are the names and the values are the factories.
  2118. * @param {Function} directiveFactory Factory function for creating new instance of
  2119. * directives.
  2120. * @description
  2121. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2122. */
  2123. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2124. /**
  2125. * @ngdoc method
  2126. * @name angular.Module#component
  2127. * @module ng
  2128. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  2129. * @param {Object} options Component definition object (a simplified
  2130. * {@link ng.$compile#directive-definition-object directive definition object})
  2131. *
  2132. * @description
  2133. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2134. */
  2135. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2136. /**
  2137. * @ngdoc method
  2138. * @name angular.Module#config
  2139. * @module ng
  2140. * @param {Function} configFn Execute this function on module load. Useful for service
  2141. * configuration.
  2142. * @description
  2143. * Use this method to register work which needs to be performed on module loading.
  2144. * For more about how to configure services, see
  2145. * {@link providers#provider-recipe Provider Recipe}.
  2146. */
  2147. config: config,
  2148. /**
  2149. * @ngdoc method
  2150. * @name angular.Module#run
  2151. * @module ng
  2152. * @param {Function} initializationFn Execute this function after injector creation.
  2153. * Useful for application initialization.
  2154. * @description
  2155. * Use this method to register work which should be performed when the injector is done
  2156. * loading all modules.
  2157. */
  2158. run: function(block) {
  2159. runBlocks.push(block);
  2160. return this;
  2161. }
  2162. };
  2163. if (configFn) {
  2164. config(configFn);
  2165. }
  2166. return moduleInstance;
  2167. /**
  2168. * @param {string} provider
  2169. * @param {string} method
  2170. * @param {String=} insertMethod
  2171. * @returns {angular.Module}
  2172. */
  2173. function invokeLater(provider, method, insertMethod, queue) {
  2174. if (!queue) queue = invokeQueue;
  2175. return function() {
  2176. queue[insertMethod || 'push']([provider, method, arguments]);
  2177. return moduleInstance;
  2178. };
  2179. }
  2180. /**
  2181. * @param {string} provider
  2182. * @param {string} method
  2183. * @returns {angular.Module}
  2184. */
  2185. function invokeLaterAndSetModuleName(provider, method, queue) {
  2186. if (!queue) queue = invokeQueue;
  2187. return function(recipeName, factoryFunction) {
  2188. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2189. queue.push([provider, method, arguments]);
  2190. return moduleInstance;
  2191. };
  2192. }
  2193. });
  2194. };
  2195. });
  2196. }
  2197. /* global shallowCopy: true */
  2198. /**
  2199. * Creates a shallow copy of an object, an array or a primitive.
  2200. *
  2201. * Assumes that there are no proto properties for objects.
  2202. */
  2203. function shallowCopy(src, dst) {
  2204. if (isArray(src)) {
  2205. dst = dst || [];
  2206. for (var i = 0, ii = src.length; i < ii; i++) {
  2207. dst[i] = src[i];
  2208. }
  2209. } else if (isObject(src)) {
  2210. dst = dst || {};
  2211. for (var key in src) {
  2212. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2213. dst[key] = src[key];
  2214. }
  2215. }
  2216. }
  2217. return dst || src;
  2218. }
  2219. /* global toDebugString: true */
  2220. function serializeObject(obj) {
  2221. var seen = [];
  2222. return JSON.stringify(obj, function(key, val) {
  2223. val = toJsonReplacer(key, val);
  2224. if (isObject(val)) {
  2225. if (seen.indexOf(val) >= 0) return '...';
  2226. seen.push(val);
  2227. }
  2228. return val;
  2229. });
  2230. }
  2231. function toDebugString(obj) {
  2232. if (typeof obj === 'function') {
  2233. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2234. } else if (isUndefined(obj)) {
  2235. return 'undefined';
  2236. } else if (typeof obj !== 'string') {
  2237. return serializeObject(obj);
  2238. }
  2239. return obj;
  2240. }
  2241. /* global angularModule: true,
  2242. version: true,
  2243. $CompileProvider,
  2244. htmlAnchorDirective,
  2245. inputDirective,
  2246. inputDirective,
  2247. formDirective,
  2248. scriptDirective,
  2249. selectDirective,
  2250. optionDirective,
  2251. ngBindDirective,
  2252. ngBindHtmlDirective,
  2253. ngBindTemplateDirective,
  2254. ngClassDirective,
  2255. ngClassEvenDirective,
  2256. ngClassOddDirective,
  2257. ngCloakDirective,
  2258. ngControllerDirective,
  2259. ngFormDirective,
  2260. ngHideDirective,
  2261. ngIfDirective,
  2262. ngIncludeDirective,
  2263. ngIncludeFillContentDirective,
  2264. ngInitDirective,
  2265. ngNonBindableDirective,
  2266. ngPluralizeDirective,
  2267. ngRepeatDirective,
  2268. ngShowDirective,
  2269. ngStyleDirective,
  2270. ngSwitchDirective,
  2271. ngSwitchWhenDirective,
  2272. ngSwitchDefaultDirective,
  2273. ngOptionsDirective,
  2274. ngTranscludeDirective,
  2275. ngModelDirective,
  2276. ngListDirective,
  2277. ngChangeDirective,
  2278. patternDirective,
  2279. patternDirective,
  2280. requiredDirective,
  2281. requiredDirective,
  2282. minlengthDirective,
  2283. minlengthDirective,
  2284. maxlengthDirective,
  2285. maxlengthDirective,
  2286. ngValueDirective,
  2287. ngModelOptionsDirective,
  2288. ngAttributeAliasDirectives,
  2289. ngEventDirectives,
  2290. $AnchorScrollProvider,
  2291. $AnimateProvider,
  2292. $CoreAnimateCssProvider,
  2293. $$CoreAnimateJsProvider,
  2294. $$CoreAnimateQueueProvider,
  2295. $$AnimateRunnerFactoryProvider,
  2296. $$AnimateAsyncRunFactoryProvider,
  2297. $BrowserProvider,
  2298. $CacheFactoryProvider,
  2299. $ControllerProvider,
  2300. $DateProvider,
  2301. $DocumentProvider,
  2302. $$IsDocumentHiddenProvider,
  2303. $ExceptionHandlerProvider,
  2304. $FilterProvider,
  2305. $$ForceReflowProvider,
  2306. $InterpolateProvider,
  2307. $IntervalProvider,
  2308. $HttpProvider,
  2309. $HttpParamSerializerProvider,
  2310. $HttpParamSerializerJQLikeProvider,
  2311. $HttpBackendProvider,
  2312. $xhrFactoryProvider,
  2313. $jsonpCallbacksProvider,
  2314. $LocationProvider,
  2315. $LogProvider,
  2316. $$MapProvider,
  2317. $ParseProvider,
  2318. $RootScopeProvider,
  2319. $QProvider,
  2320. $$QProvider,
  2321. $$SanitizeUriProvider,
  2322. $SceProvider,
  2323. $SceDelegateProvider,
  2324. $SnifferProvider,
  2325. $TemplateCacheProvider,
  2326. $TemplateRequestProvider,
  2327. $$TestabilityProvider,
  2328. $TimeoutProvider,
  2329. $$RAFProvider,
  2330. $WindowProvider,
  2331. $$jqLiteProvider,
  2332. $$CookieReaderProvider
  2333. */
  2334. /**
  2335. * @ngdoc object
  2336. * @name angular.version
  2337. * @module ng
  2338. * @description
  2339. * An object that contains information about the current AngularJS version.
  2340. *
  2341. * This object has the following properties:
  2342. *
  2343. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2344. * - `major` – `{number}` – Major version number, such as "0".
  2345. * - `minor` – `{number}` – Minor version number, such as "9".
  2346. * - `dot` – `{number}` – Dot version number, such as "18".
  2347. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2348. */
  2349. var version = {
  2350. // These placeholder strings will be replaced by grunt's `build` task.
  2351. // They need to be double- or single-quoted.
  2352. full: '1.6.2',
  2353. major: 1,
  2354. minor: 6,
  2355. dot: 2,
  2356. codeName: 'llamacorn-lovehug'
  2357. };
  2358. function publishExternalAPI(angular) {
  2359. extend(angular, {
  2360. 'bootstrap': bootstrap,
  2361. 'copy': copy,
  2362. 'extend': extend,
  2363. 'merge': merge,
  2364. 'equals': equals,
  2365. 'element': jqLite,
  2366. 'forEach': forEach,
  2367. 'injector': createInjector,
  2368. 'noop': noop,
  2369. 'bind': bind,
  2370. 'toJson': toJson,
  2371. 'fromJson': fromJson,
  2372. 'identity': identity,
  2373. 'isUndefined': isUndefined,
  2374. 'isDefined': isDefined,
  2375. 'isString': isString,
  2376. 'isFunction': isFunction,
  2377. 'isObject': isObject,
  2378. 'isNumber': isNumber,
  2379. 'isElement': isElement,
  2380. 'isArray': isArray,
  2381. 'version': version,
  2382. 'isDate': isDate,
  2383. 'lowercase': lowercase,
  2384. 'uppercase': uppercase,
  2385. 'callbacks': {$$counter: 0},
  2386. 'getTestability': getTestability,
  2387. 'reloadWithDebugInfo': reloadWithDebugInfo,
  2388. '$$minErr': minErr,
  2389. '$$csp': csp,
  2390. '$$encodeUriSegment': encodeUriSegment,
  2391. '$$encodeUriQuery': encodeUriQuery,
  2392. '$$stringify': stringify
  2393. });
  2394. angularModule = setupModuleLoader(window);
  2395. angularModule('ng', ['ngLocale'], ['$provide',
  2396. function ngModule($provide) {
  2397. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2398. $provide.provider({
  2399. $$sanitizeUri: $$SanitizeUriProvider
  2400. });
  2401. $provide.provider('$compile', $CompileProvider).
  2402. directive({
  2403. a: htmlAnchorDirective,
  2404. input: inputDirective,
  2405. textarea: inputDirective,
  2406. form: formDirective,
  2407. script: scriptDirective,
  2408. select: selectDirective,
  2409. option: optionDirective,
  2410. ngBind: ngBindDirective,
  2411. ngBindHtml: ngBindHtmlDirective,
  2412. ngBindTemplate: ngBindTemplateDirective,
  2413. ngClass: ngClassDirective,
  2414. ngClassEven: ngClassEvenDirective,
  2415. ngClassOdd: ngClassOddDirective,
  2416. ngCloak: ngCloakDirective,
  2417. ngController: ngControllerDirective,
  2418. ngForm: ngFormDirective,
  2419. ngHide: ngHideDirective,
  2420. ngIf: ngIfDirective,
  2421. ngInclude: ngIncludeDirective,
  2422. ngInit: ngInitDirective,
  2423. ngNonBindable: ngNonBindableDirective,
  2424. ngPluralize: ngPluralizeDirective,
  2425. ngRepeat: ngRepeatDirective,
  2426. ngShow: ngShowDirective,
  2427. ngStyle: ngStyleDirective,
  2428. ngSwitch: ngSwitchDirective,
  2429. ngSwitchWhen: ngSwitchWhenDirective,
  2430. ngSwitchDefault: ngSwitchDefaultDirective,
  2431. ngOptions: ngOptionsDirective,
  2432. ngTransclude: ngTranscludeDirective,
  2433. ngModel: ngModelDirective,
  2434. ngList: ngListDirective,
  2435. ngChange: ngChangeDirective,
  2436. pattern: patternDirective,
  2437. ngPattern: patternDirective,
  2438. required: requiredDirective,
  2439. ngRequired: requiredDirective,
  2440. minlength: minlengthDirective,
  2441. ngMinlength: minlengthDirective,
  2442. maxlength: maxlengthDirective,
  2443. ngMaxlength: maxlengthDirective,
  2444. ngValue: ngValueDirective,
  2445. ngModelOptions: ngModelOptionsDirective
  2446. }).
  2447. directive({
  2448. ngInclude: ngIncludeFillContentDirective
  2449. }).
  2450. directive(ngAttributeAliasDirectives).
  2451. directive(ngEventDirectives);
  2452. $provide.provider({
  2453. $anchorScroll: $AnchorScrollProvider,
  2454. $animate: $AnimateProvider,
  2455. $animateCss: $CoreAnimateCssProvider,
  2456. $$animateJs: $$CoreAnimateJsProvider,
  2457. $$animateQueue: $$CoreAnimateQueueProvider,
  2458. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2459. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2460. $browser: $BrowserProvider,
  2461. $cacheFactory: $CacheFactoryProvider,
  2462. $controller: $ControllerProvider,
  2463. $document: $DocumentProvider,
  2464. $$isDocumentHidden: $$IsDocumentHiddenProvider,
  2465. $exceptionHandler: $ExceptionHandlerProvider,
  2466. $filter: $FilterProvider,
  2467. $$forceReflow: $$ForceReflowProvider,
  2468. $interpolate: $InterpolateProvider,
  2469. $interval: $IntervalProvider,
  2470. $http: $HttpProvider,
  2471. $httpParamSerializer: $HttpParamSerializerProvider,
  2472. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2473. $httpBackend: $HttpBackendProvider,
  2474. $xhrFactory: $xhrFactoryProvider,
  2475. $jsonpCallbacks: $jsonpCallbacksProvider,
  2476. $location: $LocationProvider,
  2477. $log: $LogProvider,
  2478. $parse: $ParseProvider,
  2479. $rootScope: $RootScopeProvider,
  2480. $q: $QProvider,
  2481. $$q: $$QProvider,
  2482. $sce: $SceProvider,
  2483. $sceDelegate: $SceDelegateProvider,
  2484. $sniffer: $SnifferProvider,
  2485. $templateCache: $TemplateCacheProvider,
  2486. $templateRequest: $TemplateRequestProvider,
  2487. $$testability: $$TestabilityProvider,
  2488. $timeout: $TimeoutProvider,
  2489. $window: $WindowProvider,
  2490. $$rAF: $$RAFProvider,
  2491. $$jqLite: $$jqLiteProvider,
  2492. $$Map: $$MapProvider,
  2493. $$cookieReader: $$CookieReaderProvider
  2494. });
  2495. }
  2496. ]);
  2497. }
  2498. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2499. * Any commits to this file should be reviewed with security in mind. *
  2500. * Changes to this file can potentially create security vulnerabilities. *
  2501. * An approval from 2 Core members with history of modifying *
  2502. * this file is required. *
  2503. * *
  2504. * Does the change somehow allow for arbitrary javascript to be executed? *
  2505. * Or allows for someone to change the prototype of built-in objects? *
  2506. * Or gives undesired access to variables likes document or window? *
  2507. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2508. /* global
  2509. JQLitePrototype: true,
  2510. BOOLEAN_ATTR: true,
  2511. ALIASED_ATTR: true
  2512. */
  2513. //////////////////////////////////
  2514. //JQLite
  2515. //////////////////////////////////
  2516. /**
  2517. * @ngdoc function
  2518. * @name angular.element
  2519. * @module ng
  2520. * @kind function
  2521. *
  2522. * @description
  2523. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2524. *
  2525. * If jQuery is available, `angular.element` is an alias for the
  2526. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2527. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2528. *
  2529. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2530. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2531. * commonly needed functionality with the goal of having a very small footprint.
  2532. *
  2533. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2534. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2535. * specific version of jQuery if multiple versions exist on the page.
  2536. *
  2537. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2538. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2539. *
  2540. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2541. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2542. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2543. *
  2544. * ## Angular's jqLite
  2545. * jqLite provides only the following jQuery methods:
  2546. *
  2547. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2548. * - [`after()`](http://api.jquery.com/after/)
  2549. * - [`append()`](http://api.jquery.com/append/)
  2550. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2551. * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
  2552. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2553. * - [`clone()`](http://api.jquery.com/clone/)
  2554. * - [`contents()`](http://api.jquery.com/contents/)
  2555. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2556. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2557. * - [`data()`](http://api.jquery.com/data/)
  2558. * - [`detach()`](http://api.jquery.com/detach/)
  2559. * - [`empty()`](http://api.jquery.com/empty/)
  2560. * - [`eq()`](http://api.jquery.com/eq/)
  2561. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2562. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2563. * - [`html()`](http://api.jquery.com/html/)
  2564. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2565. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2566. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2567. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2568. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2569. * - [`prepend()`](http://api.jquery.com/prepend/)
  2570. * - [`prop()`](http://api.jquery.com/prop/)
  2571. * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
  2572. * - [`remove()`](http://api.jquery.com/remove/)
  2573. * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
  2574. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2575. * - [`removeData()`](http://api.jquery.com/removeData/)
  2576. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2577. * - [`text()`](http://api.jquery.com/text/)
  2578. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2579. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2580. * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
  2581. * - [`val()`](http://api.jquery.com/val/)
  2582. * - [`wrap()`](http://api.jquery.com/wrap/)
  2583. *
  2584. * ## jQuery/jqLite Extras
  2585. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2586. *
  2587. * ### Events
  2588. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2589. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2590. * element before it is removed.
  2591. *
  2592. * ### Methods
  2593. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2594. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2595. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2596. * `'ngModel'`).
  2597. * - `injector()` - retrieves the injector of the current element or its parent.
  2598. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2599. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2600. * be enabled.
  2601. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2602. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2603. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2604. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2605. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2606. * parent element is reached.
  2607. *
  2608. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2609. * https://github.com/angular/angular.js/issues/14251 for more information.
  2610. *
  2611. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2612. * @returns {Object} jQuery object.
  2613. */
  2614. JQLite.expando = 'ng339';
  2615. var jqCache = JQLite.cache = {},
  2616. jqId = 1;
  2617. /*
  2618. * !!! This is an undocumented "private" function !!!
  2619. */
  2620. JQLite._data = function(node) {
  2621. //jQuery always returns an object on cache miss
  2622. return this.cache[node[this.expando]] || {};
  2623. };
  2624. function jqNextId() { return ++jqId; }
  2625. var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
  2626. var MS_HACK_REGEXP = /^-ms-/;
  2627. var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
  2628. var jqLiteMinErr = minErr('jqLite');
  2629. /**
  2630. * Converts kebab-case to camelCase.
  2631. * There is also a special case for the ms prefix starting with a lowercase letter.
  2632. * @param name Name to normalize
  2633. */
  2634. function cssKebabToCamel(name) {
  2635. return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
  2636. }
  2637. function fnCamelCaseReplace(all, letter) {
  2638. return letter.toUpperCase();
  2639. }
  2640. /**
  2641. * Converts kebab-case to camelCase.
  2642. * @param name Name to normalize
  2643. */
  2644. function kebabToCamel(name) {
  2645. return name
  2646. .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
  2647. }
  2648. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2649. var HTML_REGEXP = /<|&#?\w+;/;
  2650. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2651. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2652. var wrapMap = {
  2653. 'option': [1, '<select multiple="multiple">', '</select>'],
  2654. 'thead': [1, '<table>', '</table>'],
  2655. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2656. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2657. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2658. '_default': [0, '', '']
  2659. };
  2660. wrapMap.optgroup = wrapMap.option;
  2661. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2662. wrapMap.th = wrapMap.td;
  2663. function jqLiteIsTextNode(html) {
  2664. return !HTML_REGEXP.test(html);
  2665. }
  2666. function jqLiteAcceptsData(node) {
  2667. // The window object can accept data but has no nodeType
  2668. // Otherwise we are only interested in elements (1) and documents (9)
  2669. var nodeType = node.nodeType;
  2670. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2671. }
  2672. function jqLiteHasData(node) {
  2673. for (var key in jqCache[node.ng339]) {
  2674. return true;
  2675. }
  2676. return false;
  2677. }
  2678. function jqLiteCleanData(nodes) {
  2679. for (var i = 0, ii = nodes.length; i < ii; i++) {
  2680. jqLiteRemoveData(nodes[i]);
  2681. }
  2682. }
  2683. function jqLiteBuildFragment(html, context) {
  2684. var tmp, tag, wrap,
  2685. fragment = context.createDocumentFragment(),
  2686. nodes = [], i;
  2687. if (jqLiteIsTextNode(html)) {
  2688. // Convert non-html into a text node
  2689. nodes.push(context.createTextNode(html));
  2690. } else {
  2691. // Convert html into DOM nodes
  2692. tmp = fragment.appendChild(context.createElement('div'));
  2693. tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
  2694. wrap = wrapMap[tag] || wrapMap._default;
  2695. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
  2696. // Descend through wrappers to the right content
  2697. i = wrap[0];
  2698. while (i--) {
  2699. tmp = tmp.lastChild;
  2700. }
  2701. nodes = concat(nodes, tmp.childNodes);
  2702. tmp = fragment.firstChild;
  2703. tmp.textContent = '';
  2704. }
  2705. // Remove wrapper from fragment
  2706. fragment.textContent = '';
  2707. fragment.innerHTML = ''; // Clear inner HTML
  2708. forEach(nodes, function(node) {
  2709. fragment.appendChild(node);
  2710. });
  2711. return fragment;
  2712. }
  2713. function jqLiteParseHTML(html, context) {
  2714. context = context || window.document;
  2715. var parsed;
  2716. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2717. return [context.createElement(parsed[1])];
  2718. }
  2719. if ((parsed = jqLiteBuildFragment(html, context))) {
  2720. return parsed.childNodes;
  2721. }
  2722. return [];
  2723. }
  2724. function jqLiteWrapNode(node, wrapper) {
  2725. var parent = node.parentNode;
  2726. if (parent) {
  2727. parent.replaceChild(wrapper, node);
  2728. }
  2729. wrapper.appendChild(node);
  2730. }
  2731. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2732. var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
  2733. // eslint-disable-next-line no-bitwise
  2734. return !!(this.compareDocumentPosition(arg) & 16);
  2735. };
  2736. /////////////////////////////////////////////
  2737. function JQLite(element) {
  2738. if (element instanceof JQLite) {
  2739. return element;
  2740. }
  2741. var argIsString;
  2742. if (isString(element)) {
  2743. element = trim(element);
  2744. argIsString = true;
  2745. }
  2746. if (!(this instanceof JQLite)) {
  2747. if (argIsString && element.charAt(0) !== '<') {
  2748. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2749. }
  2750. return new JQLite(element);
  2751. }
  2752. if (argIsString) {
  2753. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2754. } else if (isFunction(element)) {
  2755. jqLiteReady(element);
  2756. } else {
  2757. jqLiteAddNodes(this, element);
  2758. }
  2759. }
  2760. function jqLiteClone(element) {
  2761. return element.cloneNode(true);
  2762. }
  2763. function jqLiteDealoc(element, onlyDescendants) {
  2764. if (!onlyDescendants) jqLiteRemoveData(element);
  2765. if (element.querySelectorAll) {
  2766. var descendants = element.querySelectorAll('*');
  2767. for (var i = 0, l = descendants.length; i < l; i++) {
  2768. jqLiteRemoveData(descendants[i]);
  2769. }
  2770. }
  2771. }
  2772. function jqLiteOff(element, type, fn, unsupported) {
  2773. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2774. var expandoStore = jqLiteExpandoStore(element);
  2775. var events = expandoStore && expandoStore.events;
  2776. var handle = expandoStore && expandoStore.handle;
  2777. if (!handle) return; //no listeners registered
  2778. if (!type) {
  2779. for (type in events) {
  2780. if (type !== '$destroy') {
  2781. element.removeEventListener(type, handle);
  2782. }
  2783. delete events[type];
  2784. }
  2785. } else {
  2786. var removeHandler = function(type) {
  2787. var listenerFns = events[type];
  2788. if (isDefined(fn)) {
  2789. arrayRemove(listenerFns || [], fn);
  2790. }
  2791. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2792. element.removeEventListener(type, handle);
  2793. delete events[type];
  2794. }
  2795. };
  2796. forEach(type.split(' '), function(type) {
  2797. removeHandler(type);
  2798. if (MOUSE_EVENT_MAP[type]) {
  2799. removeHandler(MOUSE_EVENT_MAP[type]);
  2800. }
  2801. });
  2802. }
  2803. }
  2804. function jqLiteRemoveData(element, name) {
  2805. var expandoId = element.ng339;
  2806. var expandoStore = expandoId && jqCache[expandoId];
  2807. if (expandoStore) {
  2808. if (name) {
  2809. delete expandoStore.data[name];
  2810. return;
  2811. }
  2812. if (expandoStore.handle) {
  2813. if (expandoStore.events.$destroy) {
  2814. expandoStore.handle({}, '$destroy');
  2815. }
  2816. jqLiteOff(element);
  2817. }
  2818. delete jqCache[expandoId];
  2819. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2820. }
  2821. }
  2822. function jqLiteExpandoStore(element, createIfNecessary) {
  2823. var expandoId = element.ng339,
  2824. expandoStore = expandoId && jqCache[expandoId];
  2825. if (createIfNecessary && !expandoStore) {
  2826. element.ng339 = expandoId = jqNextId();
  2827. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2828. }
  2829. return expandoStore;
  2830. }
  2831. function jqLiteData(element, key, value) {
  2832. if (jqLiteAcceptsData(element)) {
  2833. var prop;
  2834. var isSimpleSetter = isDefined(value);
  2835. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2836. var massGetter = !key;
  2837. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2838. var data = expandoStore && expandoStore.data;
  2839. if (isSimpleSetter) { // data('key', value)
  2840. data[kebabToCamel(key)] = value;
  2841. } else {
  2842. if (massGetter) { // data()
  2843. return data;
  2844. } else {
  2845. if (isSimpleGetter) { // data('key')
  2846. // don't force creation of expandoStore if it doesn't exist yet
  2847. return data && data[kebabToCamel(key)];
  2848. } else { // mass-setter: data({key1: val1, key2: val2})
  2849. for (prop in key) {
  2850. data[kebabToCamel(prop)] = key[prop];
  2851. }
  2852. }
  2853. }
  2854. }
  2855. }
  2856. }
  2857. function jqLiteHasClass(element, selector) {
  2858. if (!element.getAttribute) return false;
  2859. return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
  2860. indexOf(' ' + selector + ' ') > -1);
  2861. }
  2862. function jqLiteRemoveClass(element, cssClasses) {
  2863. if (cssClasses && element.setAttribute) {
  2864. forEach(cssClasses.split(' '), function(cssClass) {
  2865. element.setAttribute('class', trim(
  2866. (' ' + (element.getAttribute('class') || '') + ' ')
  2867. .replace(/[\n\t]/g, ' ')
  2868. .replace(' ' + trim(cssClass) + ' ', ' '))
  2869. );
  2870. });
  2871. }
  2872. }
  2873. function jqLiteAddClass(element, cssClasses) {
  2874. if (cssClasses && element.setAttribute) {
  2875. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2876. .replace(/[\n\t]/g, ' ');
  2877. forEach(cssClasses.split(' '), function(cssClass) {
  2878. cssClass = trim(cssClass);
  2879. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2880. existingClasses += cssClass + ' ';
  2881. }
  2882. });
  2883. element.setAttribute('class', trim(existingClasses));
  2884. }
  2885. }
  2886. function jqLiteAddNodes(root, elements) {
  2887. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2888. if (elements) {
  2889. // if a Node (the most common case)
  2890. if (elements.nodeType) {
  2891. root[root.length++] = elements;
  2892. } else {
  2893. var length = elements.length;
  2894. // if an Array or NodeList and not a Window
  2895. if (typeof length === 'number' && elements.window !== elements) {
  2896. if (length) {
  2897. for (var i = 0; i < length; i++) {
  2898. root[root.length++] = elements[i];
  2899. }
  2900. }
  2901. } else {
  2902. root[root.length++] = elements;
  2903. }
  2904. }
  2905. }
  2906. }
  2907. function jqLiteController(element, name) {
  2908. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2909. }
  2910. function jqLiteInheritedData(element, name, value) {
  2911. // if element is the document object work with the html element instead
  2912. // this makes $(document).scope() possible
  2913. if (element.nodeType === NODE_TYPE_DOCUMENT) {
  2914. element = element.documentElement;
  2915. }
  2916. var names = isArray(name) ? name : [name];
  2917. while (element) {
  2918. for (var i = 0, ii = names.length; i < ii; i++) {
  2919. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  2920. }
  2921. // If dealing with a document fragment node with a host element, and no parent, use the host
  2922. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2923. // to lookup parent controllers.
  2924. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2925. }
  2926. }
  2927. function jqLiteEmpty(element) {
  2928. jqLiteDealoc(element, true);
  2929. while (element.firstChild) {
  2930. element.removeChild(element.firstChild);
  2931. }
  2932. }
  2933. function jqLiteRemove(element, keepData) {
  2934. if (!keepData) jqLiteDealoc(element);
  2935. var parent = element.parentNode;
  2936. if (parent) parent.removeChild(element);
  2937. }
  2938. function jqLiteDocumentLoaded(action, win) {
  2939. win = win || window;
  2940. if (win.document.readyState === 'complete') {
  2941. // Force the action to be run async for consistent behavior
  2942. // from the action's point of view
  2943. // i.e. it will definitely not be in a $apply
  2944. win.setTimeout(action);
  2945. } else {
  2946. // No need to unbind this handler as load is only ever called once
  2947. jqLite(win).on('load', action);
  2948. }
  2949. }
  2950. function jqLiteReady(fn) {
  2951. function trigger() {
  2952. window.document.removeEventListener('DOMContentLoaded', trigger);
  2953. window.removeEventListener('load', trigger);
  2954. fn();
  2955. }
  2956. // check if document is already loaded
  2957. if (window.document.readyState === 'complete') {
  2958. window.setTimeout(fn);
  2959. } else {
  2960. // We can not use jqLite since we are not done loading and jQuery could be loaded later.
  2961. // Works for modern browsers and IE9
  2962. window.document.addEventListener('DOMContentLoaded', trigger);
  2963. // Fallback to window.onload for others
  2964. window.addEventListener('load', trigger);
  2965. }
  2966. }
  2967. //////////////////////////////////////////
  2968. // Functions which are declared directly.
  2969. //////////////////////////////////////////
  2970. var JQLitePrototype = JQLite.prototype = {
  2971. ready: jqLiteReady,
  2972. toString: function() {
  2973. var value = [];
  2974. forEach(this, function(e) { value.push('' + e);});
  2975. return '[' + value.join(', ') + ']';
  2976. },
  2977. eq: function(index) {
  2978. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2979. },
  2980. length: 0,
  2981. push: push,
  2982. sort: [].sort,
  2983. splice: [].splice
  2984. };
  2985. //////////////////////////////////////////
  2986. // Functions iterating getter/setters.
  2987. // these functions return self on setter and
  2988. // value on get.
  2989. //////////////////////////////////////////
  2990. var BOOLEAN_ATTR = {};
  2991. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2992. BOOLEAN_ATTR[lowercase(value)] = value;
  2993. });
  2994. var BOOLEAN_ELEMENTS = {};
  2995. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2996. BOOLEAN_ELEMENTS[value] = true;
  2997. });
  2998. var ALIASED_ATTR = {
  2999. 'ngMinlength': 'minlength',
  3000. 'ngMaxlength': 'maxlength',
  3001. 'ngMin': 'min',
  3002. 'ngMax': 'max',
  3003. 'ngPattern': 'pattern',
  3004. 'ngStep': 'step'
  3005. };
  3006. function getBooleanAttrName(element, name) {
  3007. // check dom last since we will most likely fail on name
  3008. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  3009. // booleanAttr is here twice to minimize DOM access
  3010. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  3011. }
  3012. function getAliasedAttrName(name) {
  3013. return ALIASED_ATTR[name];
  3014. }
  3015. forEach({
  3016. data: jqLiteData,
  3017. removeData: jqLiteRemoveData,
  3018. hasData: jqLiteHasData,
  3019. cleanData: jqLiteCleanData
  3020. }, function(fn, name) {
  3021. JQLite[name] = fn;
  3022. });
  3023. forEach({
  3024. data: jqLiteData,
  3025. inheritedData: jqLiteInheritedData,
  3026. scope: function(element) {
  3027. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3028. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  3029. },
  3030. isolateScope: function(element) {
  3031. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3032. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  3033. },
  3034. controller: jqLiteController,
  3035. injector: function(element) {
  3036. return jqLiteInheritedData(element, '$injector');
  3037. },
  3038. removeAttr: function(element, name) {
  3039. element.removeAttribute(name);
  3040. },
  3041. hasClass: jqLiteHasClass,
  3042. css: function(element, name, value) {
  3043. name = cssKebabToCamel(name);
  3044. if (isDefined(value)) {
  3045. element.style[name] = value;
  3046. } else {
  3047. return element.style[name];
  3048. }
  3049. },
  3050. attr: function(element, name, value) {
  3051. var ret;
  3052. var nodeType = element.nodeType;
  3053. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
  3054. !element.getAttribute) {
  3055. return;
  3056. }
  3057. var lowercasedName = lowercase(name);
  3058. var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
  3059. if (isDefined(value)) {
  3060. // setter
  3061. if (value === null || (value === false && isBooleanAttr)) {
  3062. element.removeAttribute(name);
  3063. } else {
  3064. element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
  3065. }
  3066. } else {
  3067. // getter
  3068. ret = element.getAttribute(name);
  3069. if (isBooleanAttr && ret !== null) {
  3070. ret = lowercasedName;
  3071. }
  3072. // Normalize non-existing attributes to undefined (as jQuery).
  3073. return ret === null ? undefined : ret;
  3074. }
  3075. },
  3076. prop: function(element, name, value) {
  3077. if (isDefined(value)) {
  3078. element[name] = value;
  3079. } else {
  3080. return element[name];
  3081. }
  3082. },
  3083. text: (function() {
  3084. getText.$dv = '';
  3085. return getText;
  3086. function getText(element, value) {
  3087. if (isUndefined(value)) {
  3088. var nodeType = element.nodeType;
  3089. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  3090. }
  3091. element.textContent = value;
  3092. }
  3093. })(),
  3094. val: function(element, value) {
  3095. if (isUndefined(value)) {
  3096. if (element.multiple && nodeName_(element) === 'select') {
  3097. var result = [];
  3098. forEach(element.options, function(option) {
  3099. if (option.selected) {
  3100. result.push(option.value || option.text);
  3101. }
  3102. });
  3103. return result;
  3104. }
  3105. return element.value;
  3106. }
  3107. element.value = value;
  3108. },
  3109. html: function(element, value) {
  3110. if (isUndefined(value)) {
  3111. return element.innerHTML;
  3112. }
  3113. jqLiteDealoc(element, true);
  3114. element.innerHTML = value;
  3115. },
  3116. empty: jqLiteEmpty
  3117. }, function(fn, name) {
  3118. /**
  3119. * Properties: writes return selection, reads return first value
  3120. */
  3121. JQLite.prototype[name] = function(arg1, arg2) {
  3122. var i, key;
  3123. var nodeCount = this.length;
  3124. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3125. // in a way that survives minification.
  3126. // jqLiteEmpty takes no arguments but is a setter.
  3127. if (fn !== jqLiteEmpty &&
  3128. (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3129. if (isObject(arg1)) {
  3130. // we are a write, but the object properties are the key/values
  3131. for (i = 0; i < nodeCount; i++) {
  3132. if (fn === jqLiteData) {
  3133. // data() takes the whole object in jQuery
  3134. fn(this[i], arg1);
  3135. } else {
  3136. for (key in arg1) {
  3137. fn(this[i], key, arg1[key]);
  3138. }
  3139. }
  3140. }
  3141. // return self for chaining
  3142. return this;
  3143. } else {
  3144. // we are a read, so read the first child.
  3145. // TODO: do we still need this?
  3146. var value = fn.$dv;
  3147. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3148. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3149. for (var j = 0; j < jj; j++) {
  3150. var nodeValue = fn(this[j], arg1, arg2);
  3151. value = value ? value + nodeValue : nodeValue;
  3152. }
  3153. return value;
  3154. }
  3155. } else {
  3156. // we are a write, so apply to all children
  3157. for (i = 0; i < nodeCount; i++) {
  3158. fn(this[i], arg1, arg2);
  3159. }
  3160. // return self for chaining
  3161. return this;
  3162. }
  3163. };
  3164. });
  3165. function createEventHandler(element, events) {
  3166. var eventHandler = function(event, type) {
  3167. // jQuery specific api
  3168. event.isDefaultPrevented = function() {
  3169. return event.defaultPrevented;
  3170. };
  3171. var eventFns = events[type || event.type];
  3172. var eventFnsLength = eventFns ? eventFns.length : 0;
  3173. if (!eventFnsLength) return;
  3174. if (isUndefined(event.immediatePropagationStopped)) {
  3175. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3176. event.stopImmediatePropagation = function() {
  3177. event.immediatePropagationStopped = true;
  3178. if (event.stopPropagation) {
  3179. event.stopPropagation();
  3180. }
  3181. if (originalStopImmediatePropagation) {
  3182. originalStopImmediatePropagation.call(event);
  3183. }
  3184. };
  3185. }
  3186. event.isImmediatePropagationStopped = function() {
  3187. return event.immediatePropagationStopped === true;
  3188. };
  3189. // Some events have special handlers that wrap the real handler
  3190. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3191. // Copy event handlers in case event handlers array is modified during execution.
  3192. if ((eventFnsLength > 1)) {
  3193. eventFns = shallowCopy(eventFns);
  3194. }
  3195. for (var i = 0; i < eventFnsLength; i++) {
  3196. if (!event.isImmediatePropagationStopped()) {
  3197. handlerWrapper(element, event, eventFns[i]);
  3198. }
  3199. }
  3200. };
  3201. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3202. // events on `element`
  3203. eventHandler.elem = element;
  3204. return eventHandler;
  3205. }
  3206. function defaultHandlerWrapper(element, event, handler) {
  3207. handler.call(element, event);
  3208. }
  3209. function specialMouseHandlerWrapper(target, event, handler) {
  3210. // Refer to jQuery's implementation of mouseenter & mouseleave
  3211. // Read about mouseenter and mouseleave:
  3212. // http://www.quirksmode.org/js/events_mouse.html#link8
  3213. var related = event.relatedTarget;
  3214. // For mousenter/leave call the handler if related is outside the target.
  3215. // NB: No relatedTarget if the mouse left/entered the browser window
  3216. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3217. handler.call(target, event);
  3218. }
  3219. }
  3220. //////////////////////////////////////////
  3221. // Functions iterating traversal.
  3222. // These functions chain results into a single
  3223. // selector.
  3224. //////////////////////////////////////////
  3225. forEach({
  3226. removeData: jqLiteRemoveData,
  3227. on: function jqLiteOn(element, type, fn, unsupported) {
  3228. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3229. // Do not add event handlers to non-elements because they will not be cleaned up.
  3230. if (!jqLiteAcceptsData(element)) {
  3231. return;
  3232. }
  3233. var expandoStore = jqLiteExpandoStore(element, true);
  3234. var events = expandoStore.events;
  3235. var handle = expandoStore.handle;
  3236. if (!handle) {
  3237. handle = expandoStore.handle = createEventHandler(element, events);
  3238. }
  3239. // http://jsperf.com/string-indexof-vs-split
  3240. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3241. var i = types.length;
  3242. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3243. var eventFns = events[type];
  3244. if (!eventFns) {
  3245. eventFns = events[type] = [];
  3246. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3247. if (type !== '$destroy' && !noEventListener) {
  3248. element.addEventListener(type, handle);
  3249. }
  3250. }
  3251. eventFns.push(fn);
  3252. };
  3253. while (i--) {
  3254. type = types[i];
  3255. if (MOUSE_EVENT_MAP[type]) {
  3256. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3257. addHandler(type, undefined, true);
  3258. } else {
  3259. addHandler(type);
  3260. }
  3261. }
  3262. },
  3263. off: jqLiteOff,
  3264. one: function(element, type, fn) {
  3265. element = jqLite(element);
  3266. //add the listener twice so that when it is called
  3267. //you can remove the original function and still be
  3268. //able to call element.off(ev, fn) normally
  3269. element.on(type, function onFn() {
  3270. element.off(type, fn);
  3271. element.off(type, onFn);
  3272. });
  3273. element.on(type, fn);
  3274. },
  3275. replaceWith: function(element, replaceNode) {
  3276. var index, parent = element.parentNode;
  3277. jqLiteDealoc(element);
  3278. forEach(new JQLite(replaceNode), function(node) {
  3279. if (index) {
  3280. parent.insertBefore(node, index.nextSibling);
  3281. } else {
  3282. parent.replaceChild(node, element);
  3283. }
  3284. index = node;
  3285. });
  3286. },
  3287. children: function(element) {
  3288. var children = [];
  3289. forEach(element.childNodes, function(element) {
  3290. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3291. children.push(element);
  3292. }
  3293. });
  3294. return children;
  3295. },
  3296. contents: function(element) {
  3297. return element.contentDocument || element.childNodes || [];
  3298. },
  3299. append: function(element, node) {
  3300. var nodeType = element.nodeType;
  3301. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3302. node = new JQLite(node);
  3303. for (var i = 0, ii = node.length; i < ii; i++) {
  3304. var child = node[i];
  3305. element.appendChild(child);
  3306. }
  3307. },
  3308. prepend: function(element, node) {
  3309. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3310. var index = element.firstChild;
  3311. forEach(new JQLite(node), function(child) {
  3312. element.insertBefore(child, index);
  3313. });
  3314. }
  3315. },
  3316. wrap: function(element, wrapNode) {
  3317. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3318. },
  3319. remove: jqLiteRemove,
  3320. detach: function(element) {
  3321. jqLiteRemove(element, true);
  3322. },
  3323. after: function(element, newElement) {
  3324. var index = element, parent = element.parentNode;
  3325. if (parent) {
  3326. newElement = new JQLite(newElement);
  3327. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3328. var node = newElement[i];
  3329. parent.insertBefore(node, index.nextSibling);
  3330. index = node;
  3331. }
  3332. }
  3333. },
  3334. addClass: jqLiteAddClass,
  3335. removeClass: jqLiteRemoveClass,
  3336. toggleClass: function(element, selector, condition) {
  3337. if (selector) {
  3338. forEach(selector.split(' '), function(className) {
  3339. var classCondition = condition;
  3340. if (isUndefined(classCondition)) {
  3341. classCondition = !jqLiteHasClass(element, className);
  3342. }
  3343. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3344. });
  3345. }
  3346. },
  3347. parent: function(element) {
  3348. var parent = element.parentNode;
  3349. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3350. },
  3351. next: function(element) {
  3352. return element.nextElementSibling;
  3353. },
  3354. find: function(element, selector) {
  3355. if (element.getElementsByTagName) {
  3356. return element.getElementsByTagName(selector);
  3357. } else {
  3358. return [];
  3359. }
  3360. },
  3361. clone: jqLiteClone,
  3362. triggerHandler: function(element, event, extraParameters) {
  3363. var dummyEvent, eventFnsCopy, handlerArgs;
  3364. var eventName = event.type || event;
  3365. var expandoStore = jqLiteExpandoStore(element);
  3366. var events = expandoStore && expandoStore.events;
  3367. var eventFns = events && events[eventName];
  3368. if (eventFns) {
  3369. // Create a dummy event to pass to the handlers
  3370. dummyEvent = {
  3371. preventDefault: function() { this.defaultPrevented = true; },
  3372. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3373. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3374. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3375. stopPropagation: noop,
  3376. type: eventName,
  3377. target: element
  3378. };
  3379. // If a custom event was provided then extend our dummy event with it
  3380. if (event.type) {
  3381. dummyEvent = extend(dummyEvent, event);
  3382. }
  3383. // Copy event handlers in case event handlers array is modified during execution.
  3384. eventFnsCopy = shallowCopy(eventFns);
  3385. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3386. forEach(eventFnsCopy, function(fn) {
  3387. if (!dummyEvent.isImmediatePropagationStopped()) {
  3388. fn.apply(element, handlerArgs);
  3389. }
  3390. });
  3391. }
  3392. }
  3393. }, function(fn, name) {
  3394. /**
  3395. * chaining functions
  3396. */
  3397. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3398. var value;
  3399. for (var i = 0, ii = this.length; i < ii; i++) {
  3400. if (isUndefined(value)) {
  3401. value = fn(this[i], arg1, arg2, arg3);
  3402. if (isDefined(value)) {
  3403. // any function which returns a value needs to be wrapped
  3404. value = jqLite(value);
  3405. }
  3406. } else {
  3407. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3408. }
  3409. }
  3410. return isDefined(value) ? value : this;
  3411. };
  3412. });
  3413. // bind legacy bind/unbind to on/off
  3414. JQLite.prototype.bind = JQLite.prototype.on;
  3415. JQLite.prototype.unbind = JQLite.prototype.off;
  3416. // Provider for private $$jqLite service
  3417. /** @this */
  3418. function $$jqLiteProvider() {
  3419. this.$get = function $$jqLite() {
  3420. return extend(JQLite, {
  3421. hasClass: function(node, classes) {
  3422. if (node.attr) node = node[0];
  3423. return jqLiteHasClass(node, classes);
  3424. },
  3425. addClass: function(node, classes) {
  3426. if (node.attr) node = node[0];
  3427. return jqLiteAddClass(node, classes);
  3428. },
  3429. removeClass: function(node, classes) {
  3430. if (node.attr) node = node[0];
  3431. return jqLiteRemoveClass(node, classes);
  3432. }
  3433. });
  3434. };
  3435. }
  3436. /**
  3437. * Computes a hash of an 'obj'.
  3438. * Hash of a:
  3439. * string is string
  3440. * number is number as string
  3441. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3442. * that is also assigned to the $$hashKey property of the object.
  3443. *
  3444. * @param obj
  3445. * @returns {string} hash string such that the same input will have the same hash string.
  3446. * The resulting string key is in 'type:hashKey' format.
  3447. */
  3448. function hashKey(obj, nextUidFn) {
  3449. var key = obj && obj.$$hashKey;
  3450. if (key) {
  3451. if (typeof key === 'function') {
  3452. key = obj.$$hashKey();
  3453. }
  3454. return key;
  3455. }
  3456. var objType = typeof obj;
  3457. if (objType === 'function' || (objType === 'object' && obj !== null)) {
  3458. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3459. } else {
  3460. key = objType + ':' + obj;
  3461. }
  3462. return key;
  3463. }
  3464. // A minimal ES2015 Map implementation.
  3465. // Should be bug/feature equivalent to the native implementations of supported browsers
  3466. // (for the features required in Angular).
  3467. // See https://kangax.github.io/compat-table/es6/#test-Map
  3468. var nanKey = Object.create(null);
  3469. function NgMapShim() {
  3470. this._keys = [];
  3471. this._values = [];
  3472. this._lastKey = NaN;
  3473. this._lastIndex = -1;
  3474. }
  3475. NgMapShim.prototype = {
  3476. _idx: function(key) {
  3477. if (key === this._lastKey) {
  3478. return this._lastIndex;
  3479. }
  3480. this._lastKey = key;
  3481. this._lastIndex = this._keys.indexOf(key);
  3482. return this._lastIndex;
  3483. },
  3484. _transformKey: function(key) {
  3485. return isNumberNaN(key) ? nanKey : key;
  3486. },
  3487. get: function(key) {
  3488. key = this._transformKey(key);
  3489. var idx = this._idx(key);
  3490. if (idx !== -1) {
  3491. return this._values[idx];
  3492. }
  3493. },
  3494. set: function(key, value) {
  3495. key = this._transformKey(key);
  3496. var idx = this._idx(key);
  3497. if (idx === -1) {
  3498. idx = this._lastIndex = this._keys.length;
  3499. }
  3500. this._keys[idx] = key;
  3501. this._values[idx] = value;
  3502. // Support: IE11
  3503. // Do not `return this` to simulate the partial IE11 implementation
  3504. },
  3505. delete: function(key) {
  3506. key = this._transformKey(key);
  3507. var idx = this._idx(key);
  3508. if (idx === -1) {
  3509. return false;
  3510. }
  3511. this._keys.splice(idx, 1);
  3512. this._values.splice(idx, 1);
  3513. this._lastKey = NaN;
  3514. this._lastIndex = -1;
  3515. return true;
  3516. }
  3517. };
  3518. // For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations
  3519. // are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map`
  3520. // implementations get more stable, we can reconsider switching to `window.Map` (when available).
  3521. var NgMap = NgMapShim;
  3522. var $$MapProvider = [/** @this */function() {
  3523. this.$get = [function() {
  3524. return NgMap;
  3525. }];
  3526. }];
  3527. /**
  3528. * @ngdoc function
  3529. * @module ng
  3530. * @name angular.injector
  3531. * @kind function
  3532. *
  3533. * @description
  3534. * Creates an injector object that can be used for retrieving services as well as for
  3535. * dependency injection (see {@link guide/di dependency injection}).
  3536. *
  3537. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3538. * {@link angular.module}. The `ng` module must be explicitly added.
  3539. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3540. * disallows argument name annotation inference.
  3541. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3542. *
  3543. * @example
  3544. * Typical usage
  3545. * ```js
  3546. * // create an injector
  3547. * var $injector = angular.injector(['ng']);
  3548. *
  3549. * // use the injector to kick off your application
  3550. * // use the type inference to auto inject arguments, or use implicit injection
  3551. * $injector.invoke(function($rootScope, $compile, $document) {
  3552. * $compile($document)($rootScope);
  3553. * $rootScope.$digest();
  3554. * });
  3555. * ```
  3556. *
  3557. * Sometimes you want to get access to the injector of a currently running Angular app
  3558. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3559. * application has been bootstrapped. You can do this using the extra `injector()` added
  3560. * to JQuery/jqLite elements. See {@link angular.element}.
  3561. *
  3562. * *This is fairly rare but could be the case if a third party library is injecting the
  3563. * markup.*
  3564. *
  3565. * In the following example a new block of HTML containing a `ng-controller`
  3566. * directive is added to the end of the document body by JQuery. We then compile and link
  3567. * it into the current AngularJS scope.
  3568. *
  3569. * ```js
  3570. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3571. * $(document.body).append($div);
  3572. *
  3573. * angular.element(document).injector().invoke(function($compile) {
  3574. * var scope = angular.element($div).scope();
  3575. * $compile($div)(scope);
  3576. * });
  3577. * ```
  3578. */
  3579. /**
  3580. * @ngdoc module
  3581. * @name auto
  3582. * @installation
  3583. * @description
  3584. *
  3585. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3586. */
  3587. var ARROW_ARG = /^([^(]+?)=>/;
  3588. var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
  3589. var FN_ARG_SPLIT = /,/;
  3590. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3591. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3592. var $injectorMinErr = minErr('$injector');
  3593. function stringifyFn(fn) {
  3594. return Function.prototype.toString.call(fn);
  3595. }
  3596. function extractArgs(fn) {
  3597. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3598. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3599. return args;
  3600. }
  3601. function anonFn(fn) {
  3602. // For anonymous functions, showing at the very least the function signature can help in
  3603. // debugging.
  3604. var args = extractArgs(fn);
  3605. if (args) {
  3606. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3607. }
  3608. return 'fn';
  3609. }
  3610. function annotate(fn, strictDi, name) {
  3611. var $inject,
  3612. argDecl,
  3613. last;
  3614. if (typeof fn === 'function') {
  3615. if (!($inject = fn.$inject)) {
  3616. $inject = [];
  3617. if (fn.length) {
  3618. if (strictDi) {
  3619. if (!isString(name) || !name) {
  3620. name = fn.name || anonFn(fn);
  3621. }
  3622. throw $injectorMinErr('strictdi',
  3623. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3624. }
  3625. argDecl = extractArgs(fn);
  3626. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3627. arg.replace(FN_ARG, function(all, underscore, name) {
  3628. $inject.push(name);
  3629. });
  3630. });
  3631. }
  3632. fn.$inject = $inject;
  3633. }
  3634. } else if (isArray(fn)) {
  3635. last = fn.length - 1;
  3636. assertArgFn(fn[last], 'fn');
  3637. $inject = fn.slice(0, last);
  3638. } else {
  3639. assertArgFn(fn, 'fn', true);
  3640. }
  3641. return $inject;
  3642. }
  3643. ///////////////////////////////////////
  3644. /**
  3645. * @ngdoc service
  3646. * @name $injector
  3647. *
  3648. * @description
  3649. *
  3650. * `$injector` is used to retrieve object instances as defined by
  3651. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3652. * and load modules.
  3653. *
  3654. * The following always holds true:
  3655. *
  3656. * ```js
  3657. * var $injector = angular.injector();
  3658. * expect($injector.get('$injector')).toBe($injector);
  3659. * expect($injector.invoke(function($injector) {
  3660. * return $injector;
  3661. * })).toBe($injector);
  3662. * ```
  3663. *
  3664. * # Injection Function Annotation
  3665. *
  3666. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3667. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3668. *
  3669. * ```js
  3670. * // inferred (only works if code not minified/obfuscated)
  3671. * $injector.invoke(function(serviceA){});
  3672. *
  3673. * // annotated
  3674. * function explicit(serviceA) {};
  3675. * explicit.$inject = ['serviceA'];
  3676. * $injector.invoke(explicit);
  3677. *
  3678. * // inline
  3679. * $injector.invoke(['serviceA', function(serviceA){}]);
  3680. * ```
  3681. *
  3682. * ## Inference
  3683. *
  3684. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3685. * can then be parsed and the function arguments can be extracted. This method of discovering
  3686. * annotations is disallowed when the injector is in strict mode.
  3687. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3688. * argument names.
  3689. *
  3690. * ## `$inject` Annotation
  3691. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3692. *
  3693. * ## Inline
  3694. * As an array of injection names, where the last item in the array is the function to call.
  3695. */
  3696. /**
  3697. * @ngdoc method
  3698. * @name $injector#get
  3699. *
  3700. * @description
  3701. * Return an instance of the service.
  3702. *
  3703. * @param {string} name The name of the instance to retrieve.
  3704. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3705. * @return {*} The instance.
  3706. */
  3707. /**
  3708. * @ngdoc method
  3709. * @name $injector#invoke
  3710. *
  3711. * @description
  3712. * Invoke the method and supply the method arguments from the `$injector`.
  3713. *
  3714. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3715. * injected according to the {@link guide/di $inject Annotation} rules.
  3716. * @param {Object=} self The `this` for the invoked method.
  3717. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3718. * object first, before the `$injector` is consulted.
  3719. * @returns {*} the value returned by the invoked `fn` function.
  3720. */
  3721. /**
  3722. * @ngdoc method
  3723. * @name $injector#has
  3724. *
  3725. * @description
  3726. * Allows the user to query if the particular service exists.
  3727. *
  3728. * @param {string} name Name of the service to query.
  3729. * @returns {boolean} `true` if injector has given service.
  3730. */
  3731. /**
  3732. * @ngdoc method
  3733. * @name $injector#instantiate
  3734. * @description
  3735. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3736. * operator, and supplies all of the arguments to the constructor function as specified by the
  3737. * constructor annotation.
  3738. *
  3739. * @param {Function} Type Annotated constructor function.
  3740. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3741. * object first, before the `$injector` is consulted.
  3742. * @returns {Object} new instance of `Type`.
  3743. */
  3744. /**
  3745. * @ngdoc method
  3746. * @name $injector#annotate
  3747. *
  3748. * @description
  3749. * Returns an array of service names which the function is requesting for injection. This API is
  3750. * used by the injector to determine which services need to be injected into the function when the
  3751. * function is invoked. There are three ways in which the function can be annotated with the needed
  3752. * dependencies.
  3753. *
  3754. * # Argument names
  3755. *
  3756. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3757. * by converting the function into a string using `toString()` method and extracting the argument
  3758. * names.
  3759. * ```js
  3760. * // Given
  3761. * function MyController($scope, $route) {
  3762. * // ...
  3763. * }
  3764. *
  3765. * // Then
  3766. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3767. * ```
  3768. *
  3769. * You can disallow this method by using strict injection mode.
  3770. *
  3771. * This method does not work with code minification / obfuscation. For this reason the following
  3772. * annotation strategies are supported.
  3773. *
  3774. * # The `$inject` property
  3775. *
  3776. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3777. * represent names of services to be injected into the function.
  3778. * ```js
  3779. * // Given
  3780. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3781. * // ...
  3782. * }
  3783. * // Define function dependencies
  3784. * MyController['$inject'] = ['$scope', '$route'];
  3785. *
  3786. * // Then
  3787. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3788. * ```
  3789. *
  3790. * # The array notation
  3791. *
  3792. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3793. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3794. * a way that survives minification is a better choice:
  3795. *
  3796. * ```js
  3797. * // We wish to write this (not minification / obfuscation safe)
  3798. * injector.invoke(function($compile, $rootScope) {
  3799. * // ...
  3800. * });
  3801. *
  3802. * // We are forced to write break inlining
  3803. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3804. * // ...
  3805. * };
  3806. * tmpFn.$inject = ['$compile', '$rootScope'];
  3807. * injector.invoke(tmpFn);
  3808. *
  3809. * // To better support inline function the inline annotation is supported
  3810. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3811. * // ...
  3812. * }]);
  3813. *
  3814. * // Therefore
  3815. * expect(injector.annotate(
  3816. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3817. * ).toEqual(['$compile', '$rootScope']);
  3818. * ```
  3819. *
  3820. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3821. * be retrieved as described above.
  3822. *
  3823. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3824. *
  3825. * @returns {Array.<string>} The names of the services which the function requires.
  3826. */
  3827. /**
  3828. * @ngdoc service
  3829. * @name $provide
  3830. *
  3831. * @description
  3832. *
  3833. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3834. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3835. * {@link angular.Module}.
  3836. *
  3837. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3838. * factories** are functions which, in turn, are created by a **service provider**.
  3839. * The **service providers** are constructor functions. When instantiated they must contain a
  3840. * property called `$get`, which holds the **service factory** function.
  3841. *
  3842. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3843. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3844. * function to get the instance of the **service**.
  3845. *
  3846. * Often services have no configuration options and there is no need to add methods to the service
  3847. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3848. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3849. * services without specifying a provider.
  3850. *
  3851. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  3852. * {@link auto.$injector $injector}
  3853. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  3854. * providers and services.
  3855. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  3856. * services, not providers.
  3857. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  3858. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3859. * given factory function.
  3860. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  3861. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3862. * a new object using the given constructor function.
  3863. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  3864. * will be able to modify or replace the implementation of another service.
  3865. *
  3866. * See the individual methods for more information and examples.
  3867. */
  3868. /**
  3869. * @ngdoc method
  3870. * @name $provide#provider
  3871. * @description
  3872. *
  3873. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3874. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3875. * service.
  3876. *
  3877. * Service provider names start with the name of the service they provide followed by `Provider`.
  3878. * For example, the {@link ng.$log $log} service has a provider called
  3879. * {@link ng.$logProvider $logProvider}.
  3880. *
  3881. * Service provider objects can have additional methods which allow configuration of the provider
  3882. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3883. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3884. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3885. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3886. * console or not.
  3887. *
  3888. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3889. 'Provider'` key.
  3890. * @param {(Object|function())} provider If the provider is:
  3891. *
  3892. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3893. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3894. * - `Constructor`: a new instance of the provider will be created using
  3895. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3896. *
  3897. * @returns {Object} registered provider instance
  3898. * @example
  3899. *
  3900. * The following example shows how to create a simple event tracking service and register it using
  3901. * {@link auto.$provide#provider $provide.provider()}.
  3902. *
  3903. * ```js
  3904. * // Define the eventTracker provider
  3905. * function EventTrackerProvider() {
  3906. * var trackingUrl = '/track';
  3907. *
  3908. * // A provider method for configuring where the tracked events should been saved
  3909. * this.setTrackingUrl = function(url) {
  3910. * trackingUrl = url;
  3911. * };
  3912. *
  3913. * // The service factory function
  3914. * this.$get = ['$http', function($http) {
  3915. * var trackedEvents = {};
  3916. * return {
  3917. * // Call this to track an event
  3918. * event: function(event) {
  3919. * var count = trackedEvents[event] || 0;
  3920. * count += 1;
  3921. * trackedEvents[event] = count;
  3922. * return count;
  3923. * },
  3924. * // Call this to save the tracked events to the trackingUrl
  3925. * save: function() {
  3926. * $http.post(trackingUrl, trackedEvents);
  3927. * }
  3928. * };
  3929. * }];
  3930. * }
  3931. *
  3932. * describe('eventTracker', function() {
  3933. * var postSpy;
  3934. *
  3935. * beforeEach(module(function($provide) {
  3936. * // Register the eventTracker provider
  3937. * $provide.provider('eventTracker', EventTrackerProvider);
  3938. * }));
  3939. *
  3940. * beforeEach(module(function(eventTrackerProvider) {
  3941. * // Configure eventTracker provider
  3942. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3943. * }));
  3944. *
  3945. * it('tracks events', inject(function(eventTracker) {
  3946. * expect(eventTracker.event('login')).toEqual(1);
  3947. * expect(eventTracker.event('login')).toEqual(2);
  3948. * }));
  3949. *
  3950. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3951. * postSpy = spyOn($http, 'post');
  3952. * eventTracker.event('login');
  3953. * eventTracker.save();
  3954. * expect(postSpy).toHaveBeenCalled();
  3955. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3956. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3957. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3958. * }));
  3959. * });
  3960. * ```
  3961. */
  3962. /**
  3963. * @ngdoc method
  3964. * @name $provide#factory
  3965. * @description
  3966. *
  3967. * Register a **service factory**, which will be called to return the service instance.
  3968. * This is short for registering a service where its provider consists of only a `$get` property,
  3969. * which is the given service factory function.
  3970. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3971. * configure your service in a provider.
  3972. *
  3973. * @param {string} name The name of the instance.
  3974. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3975. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3976. * @returns {Object} registered provider instance
  3977. *
  3978. * @example
  3979. * Here is an example of registering a service
  3980. * ```js
  3981. * $provide.factory('ping', ['$http', function($http) {
  3982. * return function ping() {
  3983. * return $http.send('/ping');
  3984. * };
  3985. * }]);
  3986. * ```
  3987. * You would then inject and use this service like this:
  3988. * ```js
  3989. * someModule.controller('Ctrl', ['ping', function(ping) {
  3990. * ping();
  3991. * }]);
  3992. * ```
  3993. */
  3994. /**
  3995. * @ngdoc method
  3996. * @name $provide#service
  3997. * @description
  3998. *
  3999. * Register a **service constructor**, which will be invoked with `new` to create the service
  4000. * instance.
  4001. * This is short for registering a service where its provider's `$get` property is a factory
  4002. * function that returns an instance instantiated by the injector from the service constructor
  4003. * function.
  4004. *
  4005. * Internally it looks a bit like this:
  4006. *
  4007. * ```
  4008. * {
  4009. * $get: function() {
  4010. * return $injector.instantiate(constructor);
  4011. * }
  4012. * }
  4013. * ```
  4014. *
  4015. *
  4016. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  4017. * as a type/class.
  4018. *
  4019. * @param {string} name The name of the instance.
  4020. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  4021. * that will be instantiated.
  4022. * @returns {Object} registered provider instance
  4023. *
  4024. * @example
  4025. * Here is an example of registering a service using
  4026. * {@link auto.$provide#service $provide.service(class)}.
  4027. * ```js
  4028. * var Ping = function($http) {
  4029. * this.$http = $http;
  4030. * };
  4031. *
  4032. * Ping.$inject = ['$http'];
  4033. *
  4034. * Ping.prototype.send = function() {
  4035. * return this.$http.get('/ping');
  4036. * };
  4037. * $provide.service('ping', Ping);
  4038. * ```
  4039. * You would then inject and use this service like this:
  4040. * ```js
  4041. * someModule.controller('Ctrl', ['ping', function(ping) {
  4042. * ping.send();
  4043. * }]);
  4044. * ```
  4045. */
  4046. /**
  4047. * @ngdoc method
  4048. * @name $provide#value
  4049. * @description
  4050. *
  4051. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  4052. * number, an array, an object or a function. This is short for registering a service where its
  4053. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  4054. * service**. That also means it is not possible to inject other services into a value service.
  4055. *
  4056. * Value services are similar to constant services, except that they cannot be injected into a
  4057. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  4058. * an Angular {@link auto.$provide#decorator decorator}.
  4059. *
  4060. * @param {string} name The name of the instance.
  4061. * @param {*} value The value.
  4062. * @returns {Object} registered provider instance
  4063. *
  4064. * @example
  4065. * Here are some examples of creating value services.
  4066. * ```js
  4067. * $provide.value('ADMIN_USER', 'admin');
  4068. *
  4069. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  4070. *
  4071. * $provide.value('halfOf', function(value) {
  4072. * return value / 2;
  4073. * });
  4074. * ```
  4075. */
  4076. /**
  4077. * @ngdoc method
  4078. * @name $provide#constant
  4079. * @description
  4080. *
  4081. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  4082. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  4083. * possible to inject other services into a constant.
  4084. *
  4085. * But unlike {@link auto.$provide#value value}, a constant can be
  4086. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  4087. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  4088. *
  4089. * @param {string} name The name of the constant.
  4090. * @param {*} value The constant value.
  4091. * @returns {Object} registered instance
  4092. *
  4093. * @example
  4094. * Here a some examples of creating constants:
  4095. * ```js
  4096. * $provide.constant('SHARD_HEIGHT', 306);
  4097. *
  4098. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  4099. *
  4100. * $provide.constant('double', function(value) {
  4101. * return value * 2;
  4102. * });
  4103. * ```
  4104. */
  4105. /**
  4106. * @ngdoc method
  4107. * @name $provide#decorator
  4108. * @description
  4109. *
  4110. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  4111. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  4112. * service. The return value of the decorator function may be the original service, or a new service
  4113. * that replaces (or wraps and delegates to) the original service.
  4114. *
  4115. * You can find out more about using decorators in the {@link guide/decorators} guide.
  4116. *
  4117. * @param {string} name The name of the service to decorate.
  4118. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  4119. * provided and should return the decorated service instance. The function is called using
  4120. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  4121. * Local injection arguments:
  4122. *
  4123. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  4124. * decorated or delegated to.
  4125. *
  4126. * @example
  4127. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  4128. * calls to {@link ng.$log#error $log.warn()}.
  4129. * ```js
  4130. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4131. * $delegate.warn = $delegate.error;
  4132. * return $delegate;
  4133. * }]);
  4134. * ```
  4135. */
  4136. function createInjector(modulesToLoad, strictDi) {
  4137. strictDi = (strictDi === true);
  4138. var INSTANTIATING = {},
  4139. providerSuffix = 'Provider',
  4140. path = [],
  4141. loadedModules = new NgMap(),
  4142. providerCache = {
  4143. $provide: {
  4144. provider: supportObject(provider),
  4145. factory: supportObject(factory),
  4146. service: supportObject(service),
  4147. value: supportObject(value),
  4148. constant: supportObject(constant),
  4149. decorator: decorator
  4150. }
  4151. },
  4152. providerInjector = (providerCache.$injector =
  4153. createInternalInjector(providerCache, function(serviceName, caller) {
  4154. if (angular.isString(caller)) {
  4155. path.push(caller);
  4156. }
  4157. throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
  4158. })),
  4159. instanceCache = {},
  4160. protoInstanceInjector =
  4161. createInternalInjector(instanceCache, function(serviceName, caller) {
  4162. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4163. return instanceInjector.invoke(
  4164. provider.$get, provider, undefined, serviceName);
  4165. }),
  4166. instanceInjector = protoInstanceInjector;
  4167. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4168. var runBlocks = loadModules(modulesToLoad);
  4169. instanceInjector = protoInstanceInjector.get('$injector');
  4170. instanceInjector.strictDi = strictDi;
  4171. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4172. return instanceInjector;
  4173. ////////////////////////////////////
  4174. // $provider
  4175. ////////////////////////////////////
  4176. function supportObject(delegate) {
  4177. return function(key, value) {
  4178. if (isObject(key)) {
  4179. forEach(key, reverseParams(delegate));
  4180. } else {
  4181. return delegate(key, value);
  4182. }
  4183. };
  4184. }
  4185. function provider(name, provider_) {
  4186. assertNotHasOwnProperty(name, 'service');
  4187. if (isFunction(provider_) || isArray(provider_)) {
  4188. provider_ = providerInjector.instantiate(provider_);
  4189. }
  4190. if (!provider_.$get) {
  4191. throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
  4192. }
  4193. return (providerCache[name + providerSuffix] = provider_);
  4194. }
  4195. function enforceReturnValue(name, factory) {
  4196. return /** @this */ function enforcedReturnValue() {
  4197. var result = instanceInjector.invoke(factory, this);
  4198. if (isUndefined(result)) {
  4199. throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
  4200. }
  4201. return result;
  4202. };
  4203. }
  4204. function factory(name, factoryFn, enforce) {
  4205. return provider(name, {
  4206. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4207. });
  4208. }
  4209. function service(name, constructor) {
  4210. return factory(name, ['$injector', function($injector) {
  4211. return $injector.instantiate(constructor);
  4212. }]);
  4213. }
  4214. function value(name, val) { return factory(name, valueFn(val), false); }
  4215. function constant(name, value) {
  4216. assertNotHasOwnProperty(name, 'constant');
  4217. providerCache[name] = value;
  4218. instanceCache[name] = value;
  4219. }
  4220. function decorator(serviceName, decorFn) {
  4221. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4222. orig$get = origProvider.$get;
  4223. origProvider.$get = function() {
  4224. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4225. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4226. };
  4227. }
  4228. ////////////////////////////////////
  4229. // Module Loading
  4230. ////////////////////////////////////
  4231. function loadModules(modulesToLoad) {
  4232. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4233. var runBlocks = [], moduleFn;
  4234. forEach(modulesToLoad, function(module) {
  4235. if (loadedModules.get(module)) return;
  4236. loadedModules.set(module, true);
  4237. function runInvokeQueue(queue) {
  4238. var i, ii;
  4239. for (i = 0, ii = queue.length; i < ii; i++) {
  4240. var invokeArgs = queue[i],
  4241. provider = providerInjector.get(invokeArgs[0]);
  4242. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4243. }
  4244. }
  4245. try {
  4246. if (isString(module)) {
  4247. moduleFn = angularModule(module);
  4248. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4249. runInvokeQueue(moduleFn._invokeQueue);
  4250. runInvokeQueue(moduleFn._configBlocks);
  4251. } else if (isFunction(module)) {
  4252. runBlocks.push(providerInjector.invoke(module));
  4253. } else if (isArray(module)) {
  4254. runBlocks.push(providerInjector.invoke(module));
  4255. } else {
  4256. assertArgFn(module, 'module');
  4257. }
  4258. } catch (e) {
  4259. if (isArray(module)) {
  4260. module = module[module.length - 1];
  4261. }
  4262. if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
  4263. // Safari & FF's stack traces don't contain error.message content
  4264. // unlike those of Chrome and IE
  4265. // So if stack doesn't contain message, we create a new string that contains both.
  4266. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4267. // eslint-disable-next-line no-ex-assign
  4268. e = e.message + '\n' + e.stack;
  4269. }
  4270. throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
  4271. module, e.stack || e.message || e);
  4272. }
  4273. });
  4274. return runBlocks;
  4275. }
  4276. ////////////////////////////////////
  4277. // internal Injector
  4278. ////////////////////////////////////
  4279. function createInternalInjector(cache, factory) {
  4280. function getService(serviceName, caller) {
  4281. if (cache.hasOwnProperty(serviceName)) {
  4282. if (cache[serviceName] === INSTANTIATING) {
  4283. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4284. serviceName + ' <- ' + path.join(' <- '));
  4285. }
  4286. return cache[serviceName];
  4287. } else {
  4288. try {
  4289. path.unshift(serviceName);
  4290. cache[serviceName] = INSTANTIATING;
  4291. cache[serviceName] = factory(serviceName, caller);
  4292. return cache[serviceName];
  4293. } catch (err) {
  4294. if (cache[serviceName] === INSTANTIATING) {
  4295. delete cache[serviceName];
  4296. }
  4297. throw err;
  4298. } finally {
  4299. path.shift();
  4300. }
  4301. }
  4302. }
  4303. function injectionArgs(fn, locals, serviceName) {
  4304. var args = [],
  4305. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4306. for (var i = 0, length = $inject.length; i < length; i++) {
  4307. var key = $inject[i];
  4308. if (typeof key !== 'string') {
  4309. throw $injectorMinErr('itkn',
  4310. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4311. }
  4312. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4313. getService(key, serviceName));
  4314. }
  4315. return args;
  4316. }
  4317. function isClass(func) {
  4318. // Support: IE 9-11 only
  4319. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4320. if (msie || typeof func !== 'function') {
  4321. return false;
  4322. }
  4323. var result = func.$$ngIsClass;
  4324. if (!isBoolean(result)) {
  4325. // Support: Edge 12-13 only
  4326. // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
  4327. result = func.$$ngIsClass = /^(?:class\b|constructor\()/.test(stringifyFn(func));
  4328. }
  4329. return result;
  4330. }
  4331. function invoke(fn, self, locals, serviceName) {
  4332. if (typeof locals === 'string') {
  4333. serviceName = locals;
  4334. locals = null;
  4335. }
  4336. var args = injectionArgs(fn, locals, serviceName);
  4337. if (isArray(fn)) {
  4338. fn = fn[fn.length - 1];
  4339. }
  4340. if (!isClass(fn)) {
  4341. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4342. // #5388
  4343. return fn.apply(self, args);
  4344. } else {
  4345. args.unshift(null);
  4346. return new (Function.prototype.bind.apply(fn, args))();
  4347. }
  4348. }
  4349. function instantiate(Type, locals, serviceName) {
  4350. // Check if Type is annotated and use just the given function at n-1 as parameter
  4351. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4352. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4353. var args = injectionArgs(Type, locals, serviceName);
  4354. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4355. args.unshift(null);
  4356. return new (Function.prototype.bind.apply(ctor, args))();
  4357. }
  4358. return {
  4359. invoke: invoke,
  4360. instantiate: instantiate,
  4361. get: getService,
  4362. annotate: createInjector.$$annotate,
  4363. has: function(name) {
  4364. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4365. }
  4366. };
  4367. }
  4368. }
  4369. createInjector.$$annotate = annotate;
  4370. /**
  4371. * @ngdoc provider
  4372. * @name $anchorScrollProvider
  4373. * @this
  4374. *
  4375. * @description
  4376. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4377. * {@link ng.$location#hash $location.hash()} changes.
  4378. */
  4379. function $AnchorScrollProvider() {
  4380. var autoScrollingEnabled = true;
  4381. /**
  4382. * @ngdoc method
  4383. * @name $anchorScrollProvider#disableAutoScrolling
  4384. *
  4385. * @description
  4386. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4387. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4388. * Use this method to disable automatic scrolling.
  4389. *
  4390. * If automatic scrolling is disabled, one must explicitly call
  4391. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4392. * current hash.
  4393. */
  4394. this.disableAutoScrolling = function() {
  4395. autoScrollingEnabled = false;
  4396. };
  4397. /**
  4398. * @ngdoc service
  4399. * @name $anchorScroll
  4400. * @kind function
  4401. * @requires $window
  4402. * @requires $location
  4403. * @requires $rootScope
  4404. *
  4405. * @description
  4406. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4407. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4408. * in the
  4409. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4410. *
  4411. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4412. * match any anchor whenever it changes. This can be disabled by calling
  4413. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4414. *
  4415. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4416. * vertical scroll-offset (either fixed or dynamic).
  4417. *
  4418. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4419. * {@link ng.$location#hash $location.hash()} will be used.
  4420. *
  4421. * @property {(number|function|jqLite)} yOffset
  4422. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4423. * positioned elements at the top of the page, such as navbars, headers etc.
  4424. *
  4425. * `yOffset` can be specified in various ways:
  4426. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4427. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4428. * a number representing the offset (in pixels).<br /><br />
  4429. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4430. * the top of the page to the element's bottom will be used as offset.<br />
  4431. * **Note**: The element will be taken into account only as long as its `position` is set to
  4432. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4433. * their height and/or positioning according to the viewport's size.
  4434. *
  4435. * <br />
  4436. * <div class="alert alert-warning">
  4437. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4438. * not some child element.
  4439. * </div>
  4440. *
  4441. * @example
  4442. <example module="anchorScrollExample" name="anchor-scroll">
  4443. <file name="index.html">
  4444. <div id="scrollArea" ng-controller="ScrollController">
  4445. <a ng-click="gotoBottom()">Go to bottom</a>
  4446. <a id="bottom"></a> You're at the bottom!
  4447. </div>
  4448. </file>
  4449. <file name="script.js">
  4450. angular.module('anchorScrollExample', [])
  4451. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4452. function($scope, $location, $anchorScroll) {
  4453. $scope.gotoBottom = function() {
  4454. // set the location.hash to the id of
  4455. // the element you wish to scroll to.
  4456. $location.hash('bottom');
  4457. // call $anchorScroll()
  4458. $anchorScroll();
  4459. };
  4460. }]);
  4461. </file>
  4462. <file name="style.css">
  4463. #scrollArea {
  4464. height: 280px;
  4465. overflow: auto;
  4466. }
  4467. #bottom {
  4468. display: block;
  4469. margin-top: 2000px;
  4470. }
  4471. </file>
  4472. </example>
  4473. *
  4474. * <hr />
  4475. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4476. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4477. *
  4478. * @example
  4479. <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
  4480. <file name="index.html">
  4481. <div class="fixed-header" ng-controller="headerCtrl">
  4482. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4483. Go to anchor {{x}}
  4484. </a>
  4485. </div>
  4486. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4487. Anchor {{x}} of 5
  4488. </div>
  4489. </file>
  4490. <file name="script.js">
  4491. angular.module('anchorScrollOffsetExample', [])
  4492. .run(['$anchorScroll', function($anchorScroll) {
  4493. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4494. }])
  4495. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4496. function($anchorScroll, $location, $scope) {
  4497. $scope.gotoAnchor = function(x) {
  4498. var newHash = 'anchor' + x;
  4499. if ($location.hash() !== newHash) {
  4500. // set the $location.hash to `newHash` and
  4501. // $anchorScroll will automatically scroll to it
  4502. $location.hash('anchor' + x);
  4503. } else {
  4504. // call $anchorScroll() explicitly,
  4505. // since $location.hash hasn't changed
  4506. $anchorScroll();
  4507. }
  4508. };
  4509. }
  4510. ]);
  4511. </file>
  4512. <file name="style.css">
  4513. body {
  4514. padding-top: 50px;
  4515. }
  4516. .anchor {
  4517. border: 2px dashed DarkOrchid;
  4518. padding: 10px 10px 200px 10px;
  4519. }
  4520. .fixed-header {
  4521. background-color: rgba(0, 0, 0, 0.2);
  4522. height: 50px;
  4523. position: fixed;
  4524. top: 0; left: 0; right: 0;
  4525. }
  4526. .fixed-header > a {
  4527. display: inline-block;
  4528. margin: 5px 15px;
  4529. }
  4530. </file>
  4531. </example>
  4532. */
  4533. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4534. var document = $window.document;
  4535. // Helper function to get first anchor from a NodeList
  4536. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4537. // and working in all supported browsers.)
  4538. function getFirstAnchor(list) {
  4539. var result = null;
  4540. Array.prototype.some.call(list, function(element) {
  4541. if (nodeName_(element) === 'a') {
  4542. result = element;
  4543. return true;
  4544. }
  4545. });
  4546. return result;
  4547. }
  4548. function getYOffset() {
  4549. var offset = scroll.yOffset;
  4550. if (isFunction(offset)) {
  4551. offset = offset();
  4552. } else if (isElement(offset)) {
  4553. var elem = offset[0];
  4554. var style = $window.getComputedStyle(elem);
  4555. if (style.position !== 'fixed') {
  4556. offset = 0;
  4557. } else {
  4558. offset = elem.getBoundingClientRect().bottom;
  4559. }
  4560. } else if (!isNumber(offset)) {
  4561. offset = 0;
  4562. }
  4563. return offset;
  4564. }
  4565. function scrollTo(elem) {
  4566. if (elem) {
  4567. elem.scrollIntoView();
  4568. var offset = getYOffset();
  4569. if (offset) {
  4570. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4571. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4572. // top of the viewport.
  4573. //
  4574. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4575. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4576. // way down the page.
  4577. //
  4578. // This is often the case for elements near the bottom of the page.
  4579. //
  4580. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4581. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4582. // desired position.
  4583. var elemTop = elem.getBoundingClientRect().top;
  4584. $window.scrollBy(0, elemTop - offset);
  4585. }
  4586. } else {
  4587. $window.scrollTo(0, 0);
  4588. }
  4589. }
  4590. function scroll(hash) {
  4591. // Allow numeric hashes
  4592. hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
  4593. var elm;
  4594. // empty hash, scroll to the top of the page
  4595. if (!hash) scrollTo(null);
  4596. // element with given id
  4597. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4598. // first anchor with given name :-D
  4599. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4600. // no element and hash === 'top', scroll to the top of the page
  4601. else if (hash === 'top') scrollTo(null);
  4602. }
  4603. // does not scroll when user clicks on anchor link that is currently on
  4604. // (no url change, no $location.hash() change), browser native does scroll
  4605. if (autoScrollingEnabled) {
  4606. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4607. function autoScrollWatchAction(newVal, oldVal) {
  4608. // skip the initial scroll if $location.hash is empty
  4609. if (newVal === oldVal && newVal === '') return;
  4610. jqLiteDocumentLoaded(function() {
  4611. $rootScope.$evalAsync(scroll);
  4612. });
  4613. });
  4614. }
  4615. return scroll;
  4616. }];
  4617. }
  4618. var $animateMinErr = minErr('$animate');
  4619. var ELEMENT_NODE = 1;
  4620. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4621. function mergeClasses(a,b) {
  4622. if (!a && !b) return '';
  4623. if (!a) return b;
  4624. if (!b) return a;
  4625. if (isArray(a)) a = a.join(' ');
  4626. if (isArray(b)) b = b.join(' ');
  4627. return a + ' ' + b;
  4628. }
  4629. function extractElementNode(element) {
  4630. for (var i = 0; i < element.length; i++) {
  4631. var elm = element[i];
  4632. if (elm.nodeType === ELEMENT_NODE) {
  4633. return elm;
  4634. }
  4635. }
  4636. }
  4637. function splitClasses(classes) {
  4638. if (isString(classes)) {
  4639. classes = classes.split(' ');
  4640. }
  4641. // Use createMap() to prevent class assumptions involving property names in
  4642. // Object.prototype
  4643. var obj = createMap();
  4644. forEach(classes, function(klass) {
  4645. // sometimes the split leaves empty string values
  4646. // incase extra spaces were applied to the options
  4647. if (klass.length) {
  4648. obj[klass] = true;
  4649. }
  4650. });
  4651. return obj;
  4652. }
  4653. // if any other type of options value besides an Object value is
  4654. // passed into the $animate.method() animation then this helper code
  4655. // will be run which will ignore it. While this patch is not the
  4656. // greatest solution to this, a lot of existing plugins depend on
  4657. // $animate to either call the callback (< 1.2) or return a promise
  4658. // that can be changed. This helper function ensures that the options
  4659. // are wiped clean incase a callback function is provided.
  4660. function prepareAnimateOptions(options) {
  4661. return isObject(options)
  4662. ? options
  4663. : {};
  4664. }
  4665. var $$CoreAnimateJsProvider = /** @this */ function() {
  4666. this.$get = noop;
  4667. };
  4668. // this is prefixed with Core since it conflicts with
  4669. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4670. var $$CoreAnimateQueueProvider = /** @this */ function() {
  4671. var postDigestQueue = new NgMap();
  4672. var postDigestElements = [];
  4673. this.$get = ['$$AnimateRunner', '$rootScope',
  4674. function($$AnimateRunner, $rootScope) {
  4675. return {
  4676. enabled: noop,
  4677. on: noop,
  4678. off: noop,
  4679. pin: noop,
  4680. push: function(element, event, options, domOperation) {
  4681. if (domOperation) {
  4682. domOperation();
  4683. }
  4684. options = options || {};
  4685. if (options.from) {
  4686. element.css(options.from);
  4687. }
  4688. if (options.to) {
  4689. element.css(options.to);
  4690. }
  4691. if (options.addClass || options.removeClass) {
  4692. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4693. }
  4694. var runner = new $$AnimateRunner();
  4695. // since there are no animations to run the runner needs to be
  4696. // notified that the animation call is complete.
  4697. runner.complete();
  4698. return runner;
  4699. }
  4700. };
  4701. function updateData(data, classes, value) {
  4702. var changed = false;
  4703. if (classes) {
  4704. classes = isString(classes) ? classes.split(' ') :
  4705. isArray(classes) ? classes : [];
  4706. forEach(classes, function(className) {
  4707. if (className) {
  4708. changed = true;
  4709. data[className] = value;
  4710. }
  4711. });
  4712. }
  4713. return changed;
  4714. }
  4715. function handleCSSClassChanges() {
  4716. forEach(postDigestElements, function(element) {
  4717. var data = postDigestQueue.get(element);
  4718. if (data) {
  4719. var existing = splitClasses(element.attr('class'));
  4720. var toAdd = '';
  4721. var toRemove = '';
  4722. forEach(data, function(status, className) {
  4723. var hasClass = !!existing[className];
  4724. if (status !== hasClass) {
  4725. if (status) {
  4726. toAdd += (toAdd.length ? ' ' : '') + className;
  4727. } else {
  4728. toRemove += (toRemove.length ? ' ' : '') + className;
  4729. }
  4730. }
  4731. });
  4732. forEach(element, function(elm) {
  4733. if (toAdd) {
  4734. jqLiteAddClass(elm, toAdd);
  4735. }
  4736. if (toRemove) {
  4737. jqLiteRemoveClass(elm, toRemove);
  4738. }
  4739. });
  4740. postDigestQueue.delete(element);
  4741. }
  4742. });
  4743. postDigestElements.length = 0;
  4744. }
  4745. function addRemoveClassesPostDigest(element, add, remove) {
  4746. var data = postDigestQueue.get(element) || {};
  4747. var classesAdded = updateData(data, add, true);
  4748. var classesRemoved = updateData(data, remove, false);
  4749. if (classesAdded || classesRemoved) {
  4750. postDigestQueue.set(element, data);
  4751. postDigestElements.push(element);
  4752. if (postDigestElements.length === 1) {
  4753. $rootScope.$$postDigest(handleCSSClassChanges);
  4754. }
  4755. }
  4756. }
  4757. }];
  4758. };
  4759. /**
  4760. * @ngdoc provider
  4761. * @name $animateProvider
  4762. *
  4763. * @description
  4764. * Default implementation of $animate that doesn't perform any animations, instead just
  4765. * synchronously performs DOM updates and resolves the returned runner promise.
  4766. *
  4767. * In order to enable animations the `ngAnimate` module has to be loaded.
  4768. *
  4769. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4770. */
  4771. var $AnimateProvider = ['$provide', /** @this */ function($provide) {
  4772. var provider = this;
  4773. this.$$registeredAnimations = Object.create(null);
  4774. /**
  4775. * @ngdoc method
  4776. * @name $animateProvider#register
  4777. *
  4778. * @description
  4779. * Registers a new injectable animation factory function. The factory function produces the
  4780. * animation object which contains callback functions for each event that is expected to be
  4781. * animated.
  4782. *
  4783. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4784. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4785. * on the type of animation additional arguments will be injected into the animation function. The
  4786. * list below explains the function signatures for the different animation methods:
  4787. *
  4788. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4789. * - addClass: function(element, addedClasses, doneFunction, options)
  4790. * - removeClass: function(element, removedClasses, doneFunction, options)
  4791. * - enter, leave, move: function(element, doneFunction, options)
  4792. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4793. *
  4794. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4795. *
  4796. * ```js
  4797. * return {
  4798. * //enter, leave, move signature
  4799. * eventFn : function(element, done, options) {
  4800. * //code to run the animation
  4801. * //once complete, then run done()
  4802. * return function endFunction(wasCancelled) {
  4803. * //code to cancel the animation
  4804. * }
  4805. * }
  4806. * }
  4807. * ```
  4808. *
  4809. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4810. * @param {Function} factory The factory function that will be executed to return the animation
  4811. * object.
  4812. */
  4813. this.register = function(name, factory) {
  4814. if (name && name.charAt(0) !== '.') {
  4815. throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
  4816. }
  4817. var key = name + '-animation';
  4818. provider.$$registeredAnimations[name.substr(1)] = key;
  4819. $provide.factory(key, factory);
  4820. };
  4821. /**
  4822. * @ngdoc method
  4823. * @name $animateProvider#classNameFilter
  4824. *
  4825. * @description
  4826. * Sets and/or returns the CSS class regular expression that is checked when performing
  4827. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4828. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4829. * When setting the `classNameFilter` value, animations will only be performed on elements
  4830. * that successfully match the filter expression. This in turn can boost performance
  4831. * for low-powered devices as well as applications containing a lot of structural operations.
  4832. * @param {RegExp=} expression The className expression which will be checked against all animations
  4833. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4834. */
  4835. this.classNameFilter = function(expression) {
  4836. if (arguments.length === 1) {
  4837. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4838. if (this.$$classNameFilter) {
  4839. var reservedRegex = new RegExp('(\\s+|\\/)' + NG_ANIMATE_CLASSNAME + '(\\s+|\\/)');
  4840. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4841. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4842. }
  4843. }
  4844. }
  4845. return this.$$classNameFilter;
  4846. };
  4847. this.$get = ['$$animateQueue', function($$animateQueue) {
  4848. function domInsert(element, parentElement, afterElement) {
  4849. // if for some reason the previous element was removed
  4850. // from the dom sometime before this code runs then let's
  4851. // just stick to using the parent element as the anchor
  4852. if (afterElement) {
  4853. var afterNode = extractElementNode(afterElement);
  4854. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4855. afterElement = null;
  4856. }
  4857. }
  4858. if (afterElement) {
  4859. afterElement.after(element);
  4860. } else {
  4861. parentElement.prepend(element);
  4862. }
  4863. }
  4864. /**
  4865. * @ngdoc service
  4866. * @name $animate
  4867. * @description The $animate service exposes a series of DOM utility methods that provide support
  4868. * for animation hooks. The default behavior is the application of DOM operations, however,
  4869. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4870. * to ensure that animation runs with the triggered DOM operation.
  4871. *
  4872. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  4873. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4874. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4875. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4876. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4877. *
  4878. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4879. *
  4880. * To learn more about enabling animation support, click here to visit the
  4881. * {@link ngAnimate ngAnimate module page}.
  4882. */
  4883. return {
  4884. // we don't call it directly since non-existant arguments may
  4885. // be interpreted as null within the sub enabled function
  4886. /**
  4887. *
  4888. * @ngdoc method
  4889. * @name $animate#on
  4890. * @kind function
  4891. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4892. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4893. * is fired with the following params:
  4894. *
  4895. * ```js
  4896. * $animate.on('enter', container,
  4897. * function callback(element, phase) {
  4898. * // cool we detected an enter animation within the container
  4899. * }
  4900. * );
  4901. * ```
  4902. *
  4903. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4904. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4905. * as well as among its children
  4906. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4907. *
  4908. * The arguments present in the callback function are:
  4909. * * `element` - The captured DOM element that the animation was fired on.
  4910. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4911. */
  4912. on: $$animateQueue.on,
  4913. /**
  4914. *
  4915. * @ngdoc method
  4916. * @name $animate#off
  4917. * @kind function
  4918. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4919. * can be used in three different ways depending on the arguments:
  4920. *
  4921. * ```js
  4922. * // remove all the animation event listeners listening for `enter`
  4923. * $animate.off('enter');
  4924. *
  4925. * // remove listeners for all animation events from the container element
  4926. * $animate.off(container);
  4927. *
  4928. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4929. * $animate.off('enter', container);
  4930. *
  4931. * // remove the event listener function provided by `callback` that is set
  4932. * // to listen for `enter` on the given `container` as well as its children
  4933. * $animate.off('enter', container, callback);
  4934. * ```
  4935. *
  4936. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  4937. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  4938. * arguments are ignored.
  4939. * @param {DOMElement=} container the container element the event listener was placed on
  4940. * @param {Function=} callback the callback function that was registered as the listener
  4941. */
  4942. off: $$animateQueue.off,
  4943. /**
  4944. * @ngdoc method
  4945. * @name $animate#pin
  4946. * @kind function
  4947. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4948. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4949. * element despite being outside the realm of the application or within another application. Say for example if the application
  4950. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4951. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4952. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4953. *
  4954. * Note that this feature is only active when the `ngAnimate` module is used.
  4955. *
  4956. * @param {DOMElement} element the external element that will be pinned
  4957. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4958. */
  4959. pin: $$animateQueue.pin,
  4960. /**
  4961. *
  4962. * @ngdoc method
  4963. * @name $animate#enabled
  4964. * @kind function
  4965. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4966. * function can be called in four ways:
  4967. *
  4968. * ```js
  4969. * // returns true or false
  4970. * $animate.enabled();
  4971. *
  4972. * // changes the enabled state for all animations
  4973. * $animate.enabled(false);
  4974. * $animate.enabled(true);
  4975. *
  4976. * // returns true or false if animations are enabled for an element
  4977. * $animate.enabled(element);
  4978. *
  4979. * // changes the enabled state for an element and its children
  4980. * $animate.enabled(element, true);
  4981. * $animate.enabled(element, false);
  4982. * ```
  4983. *
  4984. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4985. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4986. *
  4987. * @return {boolean} whether or not animations are enabled
  4988. */
  4989. enabled: $$animateQueue.enabled,
  4990. /**
  4991. * @ngdoc method
  4992. * @name $animate#cancel
  4993. * @kind function
  4994. * @description Cancels the provided animation.
  4995. *
  4996. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4997. */
  4998. cancel: function(runner) {
  4999. if (runner.end) {
  5000. runner.end();
  5001. }
  5002. },
  5003. /**
  5004. *
  5005. * @ngdoc method
  5006. * @name $animate#enter
  5007. * @kind function
  5008. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  5009. * as the first child within the `parent` element and then triggers an animation.
  5010. * A promise is returned that will be resolved during the next digest once the animation
  5011. * has completed.
  5012. *
  5013. * @param {DOMElement} element the element which will be inserted into the DOM
  5014. * @param {DOMElement} parent the parent element which will append the element as
  5015. * a child (so long as the after element is not present)
  5016. * @param {DOMElement=} after the sibling element after which the element will be appended
  5017. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5018. * The object can have the following properties:
  5019. *
  5020. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5021. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5022. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5023. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5024. *
  5025. * @return {Promise} the animation callback promise
  5026. */
  5027. enter: function(element, parent, after, options) {
  5028. parent = parent && jqLite(parent);
  5029. after = after && jqLite(after);
  5030. parent = parent || after.parent();
  5031. domInsert(element, parent, after);
  5032. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  5033. },
  5034. /**
  5035. *
  5036. * @ngdoc method
  5037. * @name $animate#move
  5038. * @kind function
  5039. * @description Inserts (moves) the element into its new position in the DOM either after
  5040. * the `after` element (if provided) or as the first child within the `parent` element
  5041. * and then triggers an animation. A promise is returned that will be resolved
  5042. * during the next digest once the animation has completed.
  5043. *
  5044. * @param {DOMElement} element the element which will be moved into the new DOM position
  5045. * @param {DOMElement} parent the parent element which will append the element as
  5046. * a child (so long as the after element is not present)
  5047. * @param {DOMElement=} after the sibling element after which the element will be appended
  5048. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5049. * The object can have the following properties:
  5050. *
  5051. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5052. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5053. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5054. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5055. *
  5056. * @return {Promise} the animation callback promise
  5057. */
  5058. move: function(element, parent, after, options) {
  5059. parent = parent && jqLite(parent);
  5060. after = after && jqLite(after);
  5061. parent = parent || after.parent();
  5062. domInsert(element, parent, after);
  5063. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  5064. },
  5065. /**
  5066. * @ngdoc method
  5067. * @name $animate#leave
  5068. * @kind function
  5069. * @description Triggers an animation and then removes the element from the DOM.
  5070. * When the function is called a promise is returned that will be resolved during the next
  5071. * digest once the animation has completed.
  5072. *
  5073. * @param {DOMElement} element the element which will be removed from the DOM
  5074. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5075. * The object can have the following properties:
  5076. *
  5077. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5078. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5079. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5080. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5081. *
  5082. * @return {Promise} the animation callback promise
  5083. */
  5084. leave: function(element, options) {
  5085. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  5086. element.remove();
  5087. });
  5088. },
  5089. /**
  5090. * @ngdoc method
  5091. * @name $animate#addClass
  5092. * @kind function
  5093. *
  5094. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  5095. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  5096. * animation if element already contains the CSS class or if the class is removed at a later step.
  5097. * Note that class-based animations are treated differently compared to structural animations
  5098. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5099. * depending if CSS or JavaScript animations are used.
  5100. *
  5101. * @param {DOMElement} element the element which the CSS classes will be applied to
  5102. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  5103. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5104. * The object can have the following properties:
  5105. *
  5106. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5107. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5108. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5109. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5110. *
  5111. * @return {Promise} the animation callback promise
  5112. */
  5113. addClass: function(element, className, options) {
  5114. options = prepareAnimateOptions(options);
  5115. options.addClass = mergeClasses(options.addclass, className);
  5116. return $$animateQueue.push(element, 'addClass', options);
  5117. },
  5118. /**
  5119. * @ngdoc method
  5120. * @name $animate#removeClass
  5121. * @kind function
  5122. *
  5123. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  5124. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  5125. * animation if element does not contain the CSS class or if the class is added at a later step.
  5126. * Note that class-based animations are treated differently compared to structural animations
  5127. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5128. * depending if CSS or JavaScript animations are used.
  5129. *
  5130. * @param {DOMElement} element the element which the CSS classes will be applied to
  5131. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5132. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5133. * The object can have the following properties:
  5134. *
  5135. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5136. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5137. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5138. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5139. *
  5140. * @return {Promise} the animation callback promise
  5141. */
  5142. removeClass: function(element, className, options) {
  5143. options = prepareAnimateOptions(options);
  5144. options.removeClass = mergeClasses(options.removeClass, className);
  5145. return $$animateQueue.push(element, 'removeClass', options);
  5146. },
  5147. /**
  5148. * @ngdoc method
  5149. * @name $animate#setClass
  5150. * @kind function
  5151. *
  5152. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5153. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5154. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5155. * passed. Note that class-based animations are treated differently compared to structural animations
  5156. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5157. * depending if CSS or JavaScript animations are used.
  5158. *
  5159. * @param {DOMElement} element the element which the CSS classes will be applied to
  5160. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5161. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5162. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5163. * The object can have the following properties:
  5164. *
  5165. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5166. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5167. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5168. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5169. *
  5170. * @return {Promise} the animation callback promise
  5171. */
  5172. setClass: function(element, add, remove, options) {
  5173. options = prepareAnimateOptions(options);
  5174. options.addClass = mergeClasses(options.addClass, add);
  5175. options.removeClass = mergeClasses(options.removeClass, remove);
  5176. return $$animateQueue.push(element, 'setClass', options);
  5177. },
  5178. /**
  5179. * @ngdoc method
  5180. * @name $animate#animate
  5181. * @kind function
  5182. *
  5183. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5184. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5185. * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
  5186. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5187. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5188. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5189. * method (or as part of the `options` parameter):
  5190. *
  5191. * ```js
  5192. * ngModule.animation('.my-inline-animation', function() {
  5193. * return {
  5194. * animate : function(element, from, to, done, options) {
  5195. * //animation
  5196. * done();
  5197. * }
  5198. * }
  5199. * });
  5200. * ```
  5201. *
  5202. * @param {DOMElement} element the element which the CSS styles will be applied to
  5203. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5204. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5205. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5206. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5207. * (Note that if no animation is detected then this value will not be applied to the element.)
  5208. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5209. * The object can have the following properties:
  5210. *
  5211. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5212. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5213. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5214. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5215. *
  5216. * @return {Promise} the animation callback promise
  5217. */
  5218. animate: function(element, from, to, className, options) {
  5219. options = prepareAnimateOptions(options);
  5220. options.from = options.from ? extend(options.from, from) : from;
  5221. options.to = options.to ? extend(options.to, to) : to;
  5222. className = className || 'ng-inline-animate';
  5223. options.tempClasses = mergeClasses(options.tempClasses, className);
  5224. return $$animateQueue.push(element, 'animate', options);
  5225. }
  5226. };
  5227. }];
  5228. }];
  5229. var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
  5230. this.$get = ['$$rAF', function($$rAF) {
  5231. var waitQueue = [];
  5232. function waitForTick(fn) {
  5233. waitQueue.push(fn);
  5234. if (waitQueue.length > 1) return;
  5235. $$rAF(function() {
  5236. for (var i = 0; i < waitQueue.length; i++) {
  5237. waitQueue[i]();
  5238. }
  5239. waitQueue = [];
  5240. });
  5241. }
  5242. return function() {
  5243. var passed = false;
  5244. waitForTick(function() {
  5245. passed = true;
  5246. });
  5247. return function(callback) {
  5248. if (passed) {
  5249. callback();
  5250. } else {
  5251. waitForTick(callback);
  5252. }
  5253. };
  5254. };
  5255. }];
  5256. };
  5257. var $$AnimateRunnerFactoryProvider = /** @this */ function() {
  5258. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
  5259. function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
  5260. var INITIAL_STATE = 0;
  5261. var DONE_PENDING_STATE = 1;
  5262. var DONE_COMPLETE_STATE = 2;
  5263. AnimateRunner.chain = function(chain, callback) {
  5264. var index = 0;
  5265. next();
  5266. function next() {
  5267. if (index === chain.length) {
  5268. callback(true);
  5269. return;
  5270. }
  5271. chain[index](function(response) {
  5272. if (response === false) {
  5273. callback(false);
  5274. return;
  5275. }
  5276. index++;
  5277. next();
  5278. });
  5279. }
  5280. };
  5281. AnimateRunner.all = function(runners, callback) {
  5282. var count = 0;
  5283. var status = true;
  5284. forEach(runners, function(runner) {
  5285. runner.done(onProgress);
  5286. });
  5287. function onProgress(response) {
  5288. status = status && response;
  5289. if (++count === runners.length) {
  5290. callback(status);
  5291. }
  5292. }
  5293. };
  5294. function AnimateRunner(host) {
  5295. this.setHost(host);
  5296. var rafTick = $$animateAsyncRun();
  5297. var timeoutTick = function(fn) {
  5298. $timeout(fn, 0, false);
  5299. };
  5300. this._doneCallbacks = [];
  5301. this._tick = function(fn) {
  5302. if ($$isDocumentHidden()) {
  5303. timeoutTick(fn);
  5304. } else {
  5305. rafTick(fn);
  5306. }
  5307. };
  5308. this._state = 0;
  5309. }
  5310. AnimateRunner.prototype = {
  5311. setHost: function(host) {
  5312. this.host = host || {};
  5313. },
  5314. done: function(fn) {
  5315. if (this._state === DONE_COMPLETE_STATE) {
  5316. fn();
  5317. } else {
  5318. this._doneCallbacks.push(fn);
  5319. }
  5320. },
  5321. progress: noop,
  5322. getPromise: function() {
  5323. if (!this.promise) {
  5324. var self = this;
  5325. this.promise = $q(function(resolve, reject) {
  5326. self.done(function(status) {
  5327. if (status === false) {
  5328. reject();
  5329. } else {
  5330. resolve();
  5331. }
  5332. });
  5333. });
  5334. }
  5335. return this.promise;
  5336. },
  5337. then: function(resolveHandler, rejectHandler) {
  5338. return this.getPromise().then(resolveHandler, rejectHandler);
  5339. },
  5340. 'catch': function(handler) {
  5341. return this.getPromise()['catch'](handler);
  5342. },
  5343. 'finally': function(handler) {
  5344. return this.getPromise()['finally'](handler);
  5345. },
  5346. pause: function() {
  5347. if (this.host.pause) {
  5348. this.host.pause();
  5349. }
  5350. },
  5351. resume: function() {
  5352. if (this.host.resume) {
  5353. this.host.resume();
  5354. }
  5355. },
  5356. end: function() {
  5357. if (this.host.end) {
  5358. this.host.end();
  5359. }
  5360. this._resolve(true);
  5361. },
  5362. cancel: function() {
  5363. if (this.host.cancel) {
  5364. this.host.cancel();
  5365. }
  5366. this._resolve(false);
  5367. },
  5368. complete: function(response) {
  5369. var self = this;
  5370. if (self._state === INITIAL_STATE) {
  5371. self._state = DONE_PENDING_STATE;
  5372. self._tick(function() {
  5373. self._resolve(response);
  5374. });
  5375. }
  5376. },
  5377. _resolve: function(response) {
  5378. if (this._state !== DONE_COMPLETE_STATE) {
  5379. forEach(this._doneCallbacks, function(fn) {
  5380. fn(response);
  5381. });
  5382. this._doneCallbacks.length = 0;
  5383. this._state = DONE_COMPLETE_STATE;
  5384. }
  5385. }
  5386. };
  5387. return AnimateRunner;
  5388. }];
  5389. };
  5390. /* exported $CoreAnimateCssProvider */
  5391. /**
  5392. * @ngdoc service
  5393. * @name $animateCss
  5394. * @kind object
  5395. * @this
  5396. *
  5397. * @description
  5398. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5399. * then the `$animateCss` service will actually perform animations.
  5400. *
  5401. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5402. */
  5403. var $CoreAnimateCssProvider = function() {
  5404. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5405. return function(element, initialOptions) {
  5406. // all of the animation functions should create
  5407. // a copy of the options data, however, if a
  5408. // parent service has already created a copy then
  5409. // we should stick to using that
  5410. var options = initialOptions || {};
  5411. if (!options.$$prepared) {
  5412. options = copy(options);
  5413. }
  5414. // there is no point in applying the styles since
  5415. // there is no animation that goes on at all in
  5416. // this version of $animateCss.
  5417. if (options.cleanupStyles) {
  5418. options.from = options.to = null;
  5419. }
  5420. if (options.from) {
  5421. element.css(options.from);
  5422. options.from = null;
  5423. }
  5424. var closed, runner = new $$AnimateRunner();
  5425. return {
  5426. start: run,
  5427. end: run
  5428. };
  5429. function run() {
  5430. $$rAF(function() {
  5431. applyAnimationContents();
  5432. if (!closed) {
  5433. runner.complete();
  5434. }
  5435. closed = true;
  5436. });
  5437. return runner;
  5438. }
  5439. function applyAnimationContents() {
  5440. if (options.addClass) {
  5441. element.addClass(options.addClass);
  5442. options.addClass = null;
  5443. }
  5444. if (options.removeClass) {
  5445. element.removeClass(options.removeClass);
  5446. options.removeClass = null;
  5447. }
  5448. if (options.to) {
  5449. element.css(options.to);
  5450. options.to = null;
  5451. }
  5452. }
  5453. };
  5454. }];
  5455. };
  5456. /* global stripHash: true */
  5457. /**
  5458. * ! This is a private undocumented service !
  5459. *
  5460. * @name $browser
  5461. * @requires $log
  5462. * @description
  5463. * This object has two goals:
  5464. *
  5465. * - hide all the global state in the browser caused by the window object
  5466. * - abstract away all the browser specific features and inconsistencies
  5467. *
  5468. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5469. * service, which can be used for convenient testing of the application without the interaction with
  5470. * the real browser apis.
  5471. */
  5472. /**
  5473. * @param {object} window The global window object.
  5474. * @param {object} document jQuery wrapped document.
  5475. * @param {object} $log window.console or an object with the same interface.
  5476. * @param {object} $sniffer $sniffer service
  5477. */
  5478. function Browser(window, document, $log, $sniffer) {
  5479. var self = this,
  5480. location = window.location,
  5481. history = window.history,
  5482. setTimeout = window.setTimeout,
  5483. clearTimeout = window.clearTimeout,
  5484. pendingDeferIds = {};
  5485. self.isMock = false;
  5486. var outstandingRequestCount = 0;
  5487. var outstandingRequestCallbacks = [];
  5488. // TODO(vojta): remove this temporary api
  5489. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5490. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5491. /**
  5492. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5493. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5494. */
  5495. function completeOutstandingRequest(fn) {
  5496. try {
  5497. fn.apply(null, sliceArgs(arguments, 1));
  5498. } finally {
  5499. outstandingRequestCount--;
  5500. if (outstandingRequestCount === 0) {
  5501. while (outstandingRequestCallbacks.length) {
  5502. try {
  5503. outstandingRequestCallbacks.pop()();
  5504. } catch (e) {
  5505. $log.error(e);
  5506. }
  5507. }
  5508. }
  5509. }
  5510. }
  5511. function getHash(url) {
  5512. var index = url.indexOf('#');
  5513. return index === -1 ? '' : url.substr(index);
  5514. }
  5515. /**
  5516. * @private
  5517. * Note: this method is used only by scenario runner
  5518. * TODO(vojta): prefix this method with $$ ?
  5519. * @param {function()} callback Function that will be called when no outstanding request
  5520. */
  5521. self.notifyWhenNoOutstandingRequests = function(callback) {
  5522. if (outstandingRequestCount === 0) {
  5523. callback();
  5524. } else {
  5525. outstandingRequestCallbacks.push(callback);
  5526. }
  5527. };
  5528. //////////////////////////////////////////////////////////////
  5529. // URL API
  5530. //////////////////////////////////////////////////////////////
  5531. var cachedState, lastHistoryState,
  5532. lastBrowserUrl = location.href,
  5533. baseElement = document.find('base'),
  5534. pendingLocation = null,
  5535. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5536. try {
  5537. return history.state;
  5538. } catch (e) {
  5539. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5540. }
  5541. };
  5542. cacheState();
  5543. /**
  5544. * @name $browser#url
  5545. *
  5546. * @description
  5547. * GETTER:
  5548. * Without any argument, this method just returns current value of location.href.
  5549. *
  5550. * SETTER:
  5551. * With at least one argument, this method sets url to new value.
  5552. * If html5 history api supported, pushState/replaceState is used, otherwise
  5553. * location.href/location.replace is used.
  5554. * Returns its own instance to allow chaining
  5555. *
  5556. * NOTE: this api is intended for use only by the $location service. Please use the
  5557. * {@link ng.$location $location service} to change url.
  5558. *
  5559. * @param {string} url New url (when used as setter)
  5560. * @param {boolean=} replace Should new url replace current history record?
  5561. * @param {object=} state object to use with pushState/replaceState
  5562. */
  5563. self.url = function(url, replace, state) {
  5564. // In modern browsers `history.state` is `null` by default; treating it separately
  5565. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5566. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5567. if (isUndefined(state)) {
  5568. state = null;
  5569. }
  5570. // Android Browser BFCache causes location, history reference to become stale.
  5571. if (location !== window.location) location = window.location;
  5572. if (history !== window.history) history = window.history;
  5573. // setter
  5574. if (url) {
  5575. var sameState = lastHistoryState === state;
  5576. // Don't change anything if previous and current URLs and states match. This also prevents
  5577. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5578. // See https://github.com/angular/angular.js/commit/ffb2701
  5579. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5580. return self;
  5581. }
  5582. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5583. lastBrowserUrl = url;
  5584. lastHistoryState = state;
  5585. // Don't use history API if only the hash changed
  5586. // due to a bug in IE10/IE11 which leads
  5587. // to not firing a `hashchange` nor `popstate` event
  5588. // in some cases (see #9143).
  5589. if ($sniffer.history && (!sameBase || !sameState)) {
  5590. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5591. cacheState();
  5592. } else {
  5593. if (!sameBase) {
  5594. pendingLocation = url;
  5595. }
  5596. if (replace) {
  5597. location.replace(url);
  5598. } else if (!sameBase) {
  5599. location.href = url;
  5600. } else {
  5601. location.hash = getHash(url);
  5602. }
  5603. if (location.href !== url) {
  5604. pendingLocation = url;
  5605. }
  5606. }
  5607. if (pendingLocation) {
  5608. pendingLocation = url;
  5609. }
  5610. return self;
  5611. // getter
  5612. } else {
  5613. // - pendingLocation is needed as browsers don't allow to read out
  5614. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5615. // https://openradar.appspot.com/22186109).
  5616. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5617. return pendingLocation || location.href.replace(/%27/g,'\'');
  5618. }
  5619. };
  5620. /**
  5621. * @name $browser#state
  5622. *
  5623. * @description
  5624. * This method is a getter.
  5625. *
  5626. * Return history.state or null if history.state is undefined.
  5627. *
  5628. * @returns {object} state
  5629. */
  5630. self.state = function() {
  5631. return cachedState;
  5632. };
  5633. var urlChangeListeners = [],
  5634. urlChangeInit = false;
  5635. function cacheStateAndFireUrlChange() {
  5636. pendingLocation = null;
  5637. fireStateOrUrlChange();
  5638. }
  5639. // This variable should be used *only* inside the cacheState function.
  5640. var lastCachedState = null;
  5641. function cacheState() {
  5642. // This should be the only place in $browser where `history.state` is read.
  5643. cachedState = getCurrentState();
  5644. cachedState = isUndefined(cachedState) ? null : cachedState;
  5645. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5646. if (equals(cachedState, lastCachedState)) {
  5647. cachedState = lastCachedState;
  5648. }
  5649. lastCachedState = cachedState;
  5650. lastHistoryState = cachedState;
  5651. }
  5652. function fireStateOrUrlChange() {
  5653. var prevLastHistoryState = lastHistoryState;
  5654. cacheState();
  5655. if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {
  5656. return;
  5657. }
  5658. lastBrowserUrl = self.url();
  5659. lastHistoryState = cachedState;
  5660. forEach(urlChangeListeners, function(listener) {
  5661. listener(self.url(), cachedState);
  5662. });
  5663. }
  5664. /**
  5665. * @name $browser#onUrlChange
  5666. *
  5667. * @description
  5668. * Register callback function that will be called, when url changes.
  5669. *
  5670. * It's only called when the url is changed from outside of angular:
  5671. * - user types different url into address bar
  5672. * - user clicks on history (forward/back) button
  5673. * - user clicks on a link
  5674. *
  5675. * It's not called when url is changed by $browser.url() method
  5676. *
  5677. * The listener gets called with new url as parameter.
  5678. *
  5679. * NOTE: this api is intended for use only by the $location service. Please use the
  5680. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5681. *
  5682. * @param {function(string)} listener Listener function to be called when url changes.
  5683. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5684. */
  5685. self.onUrlChange = function(callback) {
  5686. // TODO(vojta): refactor to use node's syntax for events
  5687. if (!urlChangeInit) {
  5688. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5689. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5690. // changed by push/replaceState
  5691. // html5 history api - popstate event
  5692. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5693. // hashchange event
  5694. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5695. urlChangeInit = true;
  5696. }
  5697. urlChangeListeners.push(callback);
  5698. return callback;
  5699. };
  5700. /**
  5701. * @private
  5702. * Remove popstate and hashchange handler from window.
  5703. *
  5704. * NOTE: this api is intended for use only by $rootScope.
  5705. */
  5706. self.$$applicationDestroyed = function() {
  5707. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5708. };
  5709. /**
  5710. * Checks whether the url has changed outside of Angular.
  5711. * Needs to be exported to be able to check for changes that have been done in sync,
  5712. * as hashchange/popstate events fire in async.
  5713. */
  5714. self.$$checkUrlChange = fireStateOrUrlChange;
  5715. //////////////////////////////////////////////////////////////
  5716. // Misc API
  5717. //////////////////////////////////////////////////////////////
  5718. /**
  5719. * @name $browser#baseHref
  5720. *
  5721. * @description
  5722. * Returns current <base href>
  5723. * (always relative - without domain)
  5724. *
  5725. * @returns {string} The current base href
  5726. */
  5727. self.baseHref = function() {
  5728. var href = baseElement.attr('href');
  5729. return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
  5730. };
  5731. /**
  5732. * @name $browser#defer
  5733. * @param {function()} fn A function, who's execution should be deferred.
  5734. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5735. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5736. *
  5737. * @description
  5738. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5739. *
  5740. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5741. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5742. * via `$browser.defer.flush()`.
  5743. *
  5744. */
  5745. self.defer = function(fn, delay) {
  5746. var timeoutId;
  5747. outstandingRequestCount++;
  5748. timeoutId = setTimeout(function() {
  5749. delete pendingDeferIds[timeoutId];
  5750. completeOutstandingRequest(fn);
  5751. }, delay || 0);
  5752. pendingDeferIds[timeoutId] = true;
  5753. return timeoutId;
  5754. };
  5755. /**
  5756. * @name $browser#defer.cancel
  5757. *
  5758. * @description
  5759. * Cancels a deferred task identified with `deferId`.
  5760. *
  5761. * @param {*} deferId Token returned by the `$browser.defer` function.
  5762. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5763. * canceled.
  5764. */
  5765. self.defer.cancel = function(deferId) {
  5766. if (pendingDeferIds[deferId]) {
  5767. delete pendingDeferIds[deferId];
  5768. clearTimeout(deferId);
  5769. completeOutstandingRequest(noop);
  5770. return true;
  5771. }
  5772. return false;
  5773. };
  5774. }
  5775. /** @this */
  5776. function $BrowserProvider() {
  5777. this.$get = ['$window', '$log', '$sniffer', '$document',
  5778. function($window, $log, $sniffer, $document) {
  5779. return new Browser($window, $document, $log, $sniffer);
  5780. }];
  5781. }
  5782. /**
  5783. * @ngdoc service
  5784. * @name $cacheFactory
  5785. * @this
  5786. *
  5787. * @description
  5788. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5789. * them.
  5790. *
  5791. * ```js
  5792. *
  5793. * var cache = $cacheFactory('cacheId');
  5794. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5795. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5796. *
  5797. * cache.put("key", "value");
  5798. * cache.put("another key", "another value");
  5799. *
  5800. * // We've specified no options on creation
  5801. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5802. *
  5803. * ```
  5804. *
  5805. *
  5806. * @param {string} cacheId Name or id of the newly created cache.
  5807. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5808. *
  5809. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5810. *
  5811. * @returns {object} Newly created cache object with the following set of methods:
  5812. *
  5813. * - `{object}` `info()` — Returns id, size, and options of cache.
  5814. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5815. * it.
  5816. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5817. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5818. * - `{void}` `removeAll()` — Removes all cached values.
  5819. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5820. *
  5821. * @example
  5822. <example module="cacheExampleApp" name="cache-factory">
  5823. <file name="index.html">
  5824. <div ng-controller="CacheController">
  5825. <input ng-model="newCacheKey" placeholder="Key">
  5826. <input ng-model="newCacheValue" placeholder="Value">
  5827. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5828. <p ng-if="keys.length">Cached Values</p>
  5829. <div ng-repeat="key in keys">
  5830. <span ng-bind="key"></span>
  5831. <span>: </span>
  5832. <b ng-bind="cache.get(key)"></b>
  5833. </div>
  5834. <p>Cache Info</p>
  5835. <div ng-repeat="(key, value) in cache.info()">
  5836. <span ng-bind="key"></span>
  5837. <span>: </span>
  5838. <b ng-bind="value"></b>
  5839. </div>
  5840. </div>
  5841. </file>
  5842. <file name="script.js">
  5843. angular.module('cacheExampleApp', []).
  5844. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5845. $scope.keys = [];
  5846. $scope.cache = $cacheFactory('cacheId');
  5847. $scope.put = function(key, value) {
  5848. if (angular.isUndefined($scope.cache.get(key))) {
  5849. $scope.keys.push(key);
  5850. }
  5851. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  5852. };
  5853. }]);
  5854. </file>
  5855. <file name="style.css">
  5856. p {
  5857. margin: 10px 0 3px;
  5858. }
  5859. </file>
  5860. </example>
  5861. */
  5862. function $CacheFactoryProvider() {
  5863. this.$get = function() {
  5864. var caches = {};
  5865. function cacheFactory(cacheId, options) {
  5866. if (cacheId in caches) {
  5867. throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
  5868. }
  5869. var size = 0,
  5870. stats = extend({}, options, {id: cacheId}),
  5871. data = createMap(),
  5872. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5873. lruHash = createMap(),
  5874. freshEnd = null,
  5875. staleEnd = null;
  5876. /**
  5877. * @ngdoc type
  5878. * @name $cacheFactory.Cache
  5879. *
  5880. * @description
  5881. * A cache object used to store and retrieve data, primarily used by
  5882. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5883. * templates and other data.
  5884. *
  5885. * ```js
  5886. * angular.module('superCache')
  5887. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5888. * return $cacheFactory('super-cache');
  5889. * }]);
  5890. * ```
  5891. *
  5892. * Example test:
  5893. *
  5894. * ```js
  5895. * it('should behave like a cache', inject(function(superCache) {
  5896. * superCache.put('key', 'value');
  5897. * superCache.put('another key', 'another value');
  5898. *
  5899. * expect(superCache.info()).toEqual({
  5900. * id: 'super-cache',
  5901. * size: 2
  5902. * });
  5903. *
  5904. * superCache.remove('another key');
  5905. * expect(superCache.get('another key')).toBeUndefined();
  5906. *
  5907. * superCache.removeAll();
  5908. * expect(superCache.info()).toEqual({
  5909. * id: 'super-cache',
  5910. * size: 0
  5911. * });
  5912. * }));
  5913. * ```
  5914. */
  5915. return (caches[cacheId] = {
  5916. /**
  5917. * @ngdoc method
  5918. * @name $cacheFactory.Cache#put
  5919. * @kind function
  5920. *
  5921. * @description
  5922. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5923. * retrieved later, and incrementing the size of the cache if the key was not already
  5924. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5925. * entries from the set.
  5926. *
  5927. * It will not insert undefined values into the cache.
  5928. *
  5929. * @param {string} key the key under which the cached data is stored.
  5930. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5931. * will not be stored.
  5932. * @returns {*} the value stored.
  5933. */
  5934. put: function(key, value) {
  5935. if (isUndefined(value)) return;
  5936. if (capacity < Number.MAX_VALUE) {
  5937. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5938. refresh(lruEntry);
  5939. }
  5940. if (!(key in data)) size++;
  5941. data[key] = value;
  5942. if (size > capacity) {
  5943. this.remove(staleEnd.key);
  5944. }
  5945. return value;
  5946. },
  5947. /**
  5948. * @ngdoc method
  5949. * @name $cacheFactory.Cache#get
  5950. * @kind function
  5951. *
  5952. * @description
  5953. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5954. *
  5955. * @param {string} key the key of the data to be retrieved
  5956. * @returns {*} the value stored.
  5957. */
  5958. get: function(key) {
  5959. if (capacity < Number.MAX_VALUE) {
  5960. var lruEntry = lruHash[key];
  5961. if (!lruEntry) return;
  5962. refresh(lruEntry);
  5963. }
  5964. return data[key];
  5965. },
  5966. /**
  5967. * @ngdoc method
  5968. * @name $cacheFactory.Cache#remove
  5969. * @kind function
  5970. *
  5971. * @description
  5972. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5973. *
  5974. * @param {string} key the key of the entry to be removed
  5975. */
  5976. remove: function(key) {
  5977. if (capacity < Number.MAX_VALUE) {
  5978. var lruEntry = lruHash[key];
  5979. if (!lruEntry) return;
  5980. if (lruEntry === freshEnd) freshEnd = lruEntry.p;
  5981. if (lruEntry === staleEnd) staleEnd = lruEntry.n;
  5982. link(lruEntry.n,lruEntry.p);
  5983. delete lruHash[key];
  5984. }
  5985. if (!(key in data)) return;
  5986. delete data[key];
  5987. size--;
  5988. },
  5989. /**
  5990. * @ngdoc method
  5991. * @name $cacheFactory.Cache#removeAll
  5992. * @kind function
  5993. *
  5994. * @description
  5995. * Clears the cache object of any entries.
  5996. */
  5997. removeAll: function() {
  5998. data = createMap();
  5999. size = 0;
  6000. lruHash = createMap();
  6001. freshEnd = staleEnd = null;
  6002. },
  6003. /**
  6004. * @ngdoc method
  6005. * @name $cacheFactory.Cache#destroy
  6006. * @kind function
  6007. *
  6008. * @description
  6009. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  6010. * removing it from the {@link $cacheFactory $cacheFactory} set.
  6011. */
  6012. destroy: function() {
  6013. data = null;
  6014. stats = null;
  6015. lruHash = null;
  6016. delete caches[cacheId];
  6017. },
  6018. /**
  6019. * @ngdoc method
  6020. * @name $cacheFactory.Cache#info
  6021. * @kind function
  6022. *
  6023. * @description
  6024. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  6025. *
  6026. * @returns {object} an object with the following properties:
  6027. * <ul>
  6028. * <li>**id**: the id of the cache instance</li>
  6029. * <li>**size**: the number of entries kept in the cache instance</li>
  6030. * <li>**...**: any additional properties from the options object when creating the
  6031. * cache.</li>
  6032. * </ul>
  6033. */
  6034. info: function() {
  6035. return extend({}, stats, {size: size});
  6036. }
  6037. });
  6038. /**
  6039. * makes the `entry` the freshEnd of the LRU linked list
  6040. */
  6041. function refresh(entry) {
  6042. if (entry !== freshEnd) {
  6043. if (!staleEnd) {
  6044. staleEnd = entry;
  6045. } else if (staleEnd === entry) {
  6046. staleEnd = entry.n;
  6047. }
  6048. link(entry.n, entry.p);
  6049. link(entry, freshEnd);
  6050. freshEnd = entry;
  6051. freshEnd.n = null;
  6052. }
  6053. }
  6054. /**
  6055. * bidirectionally links two entries of the LRU linked list
  6056. */
  6057. function link(nextEntry, prevEntry) {
  6058. if (nextEntry !== prevEntry) {
  6059. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  6060. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  6061. }
  6062. }
  6063. }
  6064. /**
  6065. * @ngdoc method
  6066. * @name $cacheFactory#info
  6067. *
  6068. * @description
  6069. * Get information about all the caches that have been created
  6070. *
  6071. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  6072. */
  6073. cacheFactory.info = function() {
  6074. var info = {};
  6075. forEach(caches, function(cache, cacheId) {
  6076. info[cacheId] = cache.info();
  6077. });
  6078. return info;
  6079. };
  6080. /**
  6081. * @ngdoc method
  6082. * @name $cacheFactory#get
  6083. *
  6084. * @description
  6085. * Get access to a cache object by the `cacheId` used when it was created.
  6086. *
  6087. * @param {string} cacheId Name or id of a cache to access.
  6088. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  6089. */
  6090. cacheFactory.get = function(cacheId) {
  6091. return caches[cacheId];
  6092. };
  6093. return cacheFactory;
  6094. };
  6095. }
  6096. /**
  6097. * @ngdoc service
  6098. * @name $templateCache
  6099. * @this
  6100. *
  6101. * @description
  6102. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  6103. * can load templates directly into the cache in a `script` tag, or by consuming the
  6104. * `$templateCache` service directly.
  6105. *
  6106. * Adding via the `script` tag:
  6107. *
  6108. * ```html
  6109. * <script type="text/ng-template" id="templateId.html">
  6110. * <p>This is the content of the template</p>
  6111. * </script>
  6112. * ```
  6113. *
  6114. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  6115. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  6116. * element with ng-app attribute), otherwise the template will be ignored.
  6117. *
  6118. * Adding via the `$templateCache` service:
  6119. *
  6120. * ```js
  6121. * var myApp = angular.module('myApp', []);
  6122. * myApp.run(function($templateCache) {
  6123. * $templateCache.put('templateId.html', 'This is the content of the template');
  6124. * });
  6125. * ```
  6126. *
  6127. * To retrieve the template later, simply use it in your component:
  6128. * ```js
  6129. * myApp.component('myComponent', {
  6130. * templateUrl: 'templateId.html'
  6131. * });
  6132. * ```
  6133. *
  6134. * or get it via the `$templateCache` service:
  6135. * ```js
  6136. * $templateCache.get('templateId.html')
  6137. * ```
  6138. *
  6139. * See {@link ng.$cacheFactory $cacheFactory}.
  6140. *
  6141. */
  6142. function $TemplateCacheProvider() {
  6143. this.$get = ['$cacheFactory', function($cacheFactory) {
  6144. return $cacheFactory('templates');
  6145. }];
  6146. }
  6147. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  6148. * Any commits to this file should be reviewed with security in mind. *
  6149. * Changes to this file can potentially create security vulnerabilities. *
  6150. * An approval from 2 Core members with history of modifying *
  6151. * this file is required. *
  6152. * *
  6153. * Does the change somehow allow for arbitrary javascript to be executed? *
  6154. * Or allows for someone to change the prototype of built-in objects? *
  6155. * Or gives undesired access to variables like document or window? *
  6156. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  6157. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  6158. *
  6159. * DOM-related variables:
  6160. *
  6161. * - "node" - DOM Node
  6162. * - "element" - DOM Element or Node
  6163. * - "$node" or "$element" - jqLite-wrapped node or element
  6164. *
  6165. *
  6166. * Compiler related stuff:
  6167. *
  6168. * - "linkFn" - linking fn of a single directive
  6169. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6170. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6171. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6172. */
  6173. /**
  6174. * @ngdoc service
  6175. * @name $compile
  6176. * @kind function
  6177. *
  6178. * @description
  6179. * Compiles an HTML string or DOM into a template and produces a template function, which
  6180. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6181. *
  6182. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6183. * {@link ng.$compileProvider#directive directives}.
  6184. *
  6185. * <div class="alert alert-warning">
  6186. * **Note:** This document is an in-depth reference of all directive options.
  6187. * For a gentle introduction to directives with examples of common use cases,
  6188. * see the {@link guide/directive directive guide}.
  6189. * </div>
  6190. *
  6191. * ## Comprehensive Directive API
  6192. *
  6193. * There are many different options for a directive.
  6194. *
  6195. * The difference resides in the return value of the factory function.
  6196. * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
  6197. * that defines the directive properties, or just the `postLink` function (all other properties will have
  6198. * the default values).
  6199. *
  6200. * <div class="alert alert-success">
  6201. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6202. * </div>
  6203. *
  6204. * Here's an example directive declared with a Directive Definition Object:
  6205. *
  6206. * ```js
  6207. * var myModule = angular.module(...);
  6208. *
  6209. * myModule.directive('directiveName', function factory(injectables) {
  6210. * var directiveDefinitionObject = {
  6211. * {@link $compile#-priority- priority}: 0,
  6212. * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6213. * // or
  6214. * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6215. * {@link $compile#-transclude- transclude}: false,
  6216. * {@link $compile#-restrict- restrict}: 'A',
  6217. * {@link $compile#-templatenamespace- templateNamespace}: 'html',
  6218. * {@link $compile#-scope- scope}: false,
  6219. * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6220. * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
  6221. * {@link $compile#-bindtocontroller- bindToController}: false,
  6222. * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6223. * {@link $compile#-multielement- multiElement}: false,
  6224. * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
  6225. * return {
  6226. * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6227. * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6228. * }
  6229. * // or
  6230. * // return function postLink( ... ) { ... }
  6231. * },
  6232. * // or
  6233. * // {@link $compile#-link- link}: {
  6234. * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6235. * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6236. * // }
  6237. * // or
  6238. * // {@link $compile#-link- link}: function postLink( ... ) { ... }
  6239. * };
  6240. * return directiveDefinitionObject;
  6241. * });
  6242. * ```
  6243. *
  6244. * <div class="alert alert-warning">
  6245. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6246. * </div>
  6247. *
  6248. * Therefore the above can be simplified as:
  6249. *
  6250. * ```js
  6251. * var myModule = angular.module(...);
  6252. *
  6253. * myModule.directive('directiveName', function factory(injectables) {
  6254. * var directiveDefinitionObject = {
  6255. * link: function postLink(scope, iElement, iAttrs) { ... }
  6256. * };
  6257. * return directiveDefinitionObject;
  6258. * // or
  6259. * // return function postLink(scope, iElement, iAttrs) { ... }
  6260. * });
  6261. * ```
  6262. *
  6263. * ### Life-cycle hooks
  6264. * Directive controllers can provide the following methods that are called by Angular at points in the life-cycle of the
  6265. * directive:
  6266. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6267. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6268. * this element). This is a good place to put initialization code for your controller.
  6269. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6270. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6271. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6272. * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will
  6273. * also be called when your bindings are initialized.
  6274. * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
  6275. * changes. Any actions that you wish to take in response to the changes that you detect must be
  6276. * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
  6277. * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
  6278. * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
  6279. * if detecting changes, you must store the previous value(s) for comparison to the current values.
  6280. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6281. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6282. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6283. * components will have their `$onDestroy()` hook called before child components.
  6284. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6285. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6286. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6287. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6288. * suspended until that occurs.
  6289. *
  6290. * #### Comparison with Angular 2 life-cycle hooks
  6291. * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are
  6292. * some differences that you should be aware of, especially when it comes to moving your code from Angular 1 to Angular 2:
  6293. *
  6294. * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`.
  6295. * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor.
  6296. * In Angular 2 you can only define hooks on the prototype of the Component class.
  6297. * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to
  6298. * `ngDoCheck` in Angular 2
  6299. * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
  6300. * propagated throughout the application.
  6301. * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
  6302. * error or do nothing depending upon the state of `enableProdMode()`.
  6303. *
  6304. * #### Life-cycle hook examples
  6305. *
  6306. * This example shows how you can check for mutations to a Date object even though the identity of the object
  6307. * has not changed.
  6308. *
  6309. * <example name="doCheckDateExample" module="do-check-module">
  6310. * <file name="app.js">
  6311. * angular.module('do-check-module', [])
  6312. * .component('app', {
  6313. * template:
  6314. * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
  6315. * 'Date: {{ $ctrl.date }}' +
  6316. * '<test date="$ctrl.date"></test>',
  6317. * controller: function() {
  6318. * this.date = new Date();
  6319. * this.month = this.date.getMonth();
  6320. * this.updateDate = function() {
  6321. * this.date.setMonth(this.month);
  6322. * };
  6323. * }
  6324. * })
  6325. * .component('test', {
  6326. * bindings: { date: '<' },
  6327. * template:
  6328. * '<pre>{{ $ctrl.log | json }}</pre>',
  6329. * controller: function() {
  6330. * var previousValue;
  6331. * this.log = [];
  6332. * this.$doCheck = function() {
  6333. * var currentValue = this.date && this.date.valueOf();
  6334. * if (previousValue !== currentValue) {
  6335. * this.log.push('doCheck: date mutated: ' + this.date);
  6336. * previousValue = currentValue;
  6337. * }
  6338. * };
  6339. * }
  6340. * });
  6341. * </file>
  6342. * <file name="index.html">
  6343. * <app></app>
  6344. * </file>
  6345. * </example>
  6346. *
  6347. * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
  6348. * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
  6349. * arrays or objects can have a negative impact on your application performance)
  6350. *
  6351. * <example name="doCheckArrayExample" module="do-check-module">
  6352. * <file name="index.html">
  6353. * <div ng-init="items = []">
  6354. * <button ng-click="items.push(items.length)">Add Item</button>
  6355. * <button ng-click="items = []">Reset Items</button>
  6356. * <pre>{{ items }}</pre>
  6357. * <test items="items"></test>
  6358. * </div>
  6359. * </file>
  6360. * <file name="app.js">
  6361. * angular.module('do-check-module', [])
  6362. * .component('test', {
  6363. * bindings: { items: '<' },
  6364. * template:
  6365. * '<pre>{{ $ctrl.log | json }}</pre>',
  6366. * controller: function() {
  6367. * this.log = [];
  6368. *
  6369. * this.$doCheck = function() {
  6370. * if (this.items_ref !== this.items) {
  6371. * this.log.push('doCheck: items changed');
  6372. * this.items_ref = this.items;
  6373. * }
  6374. * if (!angular.equals(this.items_clone, this.items)) {
  6375. * this.log.push('doCheck: items mutated');
  6376. * this.items_clone = angular.copy(this.items);
  6377. * }
  6378. * };
  6379. * }
  6380. * });
  6381. * </file>
  6382. * </example>
  6383. *
  6384. *
  6385. * ### Directive Definition Object
  6386. *
  6387. * The directive definition object provides instructions to the {@link ng.$compile
  6388. * compiler}. The attributes are:
  6389. *
  6390. * #### `multiElement`
  6391. * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
  6392. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6393. * together as the directive elements. It is recommended that this feature be used on directives
  6394. * which are not strictly behavioral (such as {@link ngClick}), and which
  6395. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6396. *
  6397. * #### `priority`
  6398. * When there are multiple directives defined on a single DOM element, sometimes it
  6399. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6400. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6401. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6402. * are also run in priority order, but post-link functions are run in reverse order. The order
  6403. * of directives with the same priority is undefined. The default priority is `0`.
  6404. *
  6405. * #### `terminal`
  6406. * If set to true then the current `priority` will be the last set of directives
  6407. * which will execute (any directives at the current priority will still execute
  6408. * as the order of execution on same `priority` is undefined). Note that expressions
  6409. * and other directives used in the directive's template will also be excluded from execution.
  6410. *
  6411. * #### `scope`
  6412. * The scope property can be `false`, `true`, or an object:
  6413. *
  6414. * * **`false` (default):** No scope will be created for the directive. The directive will use its
  6415. * parent's scope.
  6416. *
  6417. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6418. * the directive's element. If multiple directives on the same element request a new scope,
  6419. * only one new scope is created.
  6420. *
  6421. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  6422. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  6423. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  6424. * data in the parent scope.
  6425. *
  6426. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6427. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6428. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6429. * is bound to the parent scope, via matching attributes on the directive's element:
  6430. *
  6431. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6432. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6433. * attribute name is assumed to be the same as the local name. Given `<my-component
  6434. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6435. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6436. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6437. * scope. The `name` is read from the parent scope (not the directive's scope).
  6438. *
  6439. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6440. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6441. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6442. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6443. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6444. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6445. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6446. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6447. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6448. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6449. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6450. * method is used for tracking changes, and the equality check is based on object identity.
  6451. * However, if an object literal or an array literal is passed as the binding expression, the
  6452. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6453. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6454. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6455. *
  6456. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6457. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6458. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6459. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6460. *
  6461. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6462. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6463. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6464. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6465. * two caveats:
  6466. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6467. * sets the same value. That means if your bound value is an object, changes to its properties
  6468. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6469. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6470. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6471. * to the value has changed. In most cases, this should not be of concern, but can be important
  6472. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6473. * If you now change a property of the object in your parent scope, the change will not be
  6474. * propagated to the isolated scope, because the identity of the object on the parent scope
  6475. * has not changed. Instead you must assign a new object.
  6476. *
  6477. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6478. * back to the parent. However, it does not make this completely impossible.
  6479. *
  6480. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6481. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6482. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6483. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6484. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6485. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6486. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6487. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6488. *
  6489. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6490. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6491. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6492. *
  6493. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6494. * * **child scope** + **no scope** => Both directives will share one single child scope
  6495. * * **child scope** + **child scope** => Both directives will share one single child scope
  6496. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6497. * its parent's scope
  6498. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6499. * be applied to the same element.
  6500. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6501. * cannot be applied to the same element.
  6502. *
  6503. *
  6504. * #### `bindToController`
  6505. * This property is used to bind scope properties directly to the controller. It can be either
  6506. * `true` or an object hash with the same format as the `scope` property.
  6507. *
  6508. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6509. * allow a component to have its properties bound to the controller, rather than to scope.
  6510. *
  6511. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6512. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6513. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6514. * initialized.
  6515. *
  6516. * <div class="alert alert-warning">
  6517. * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
  6518. * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
  6519. * code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6520. * </div>
  6521. *
  6522. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6523. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6524. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6525. * scope (useful for component directives).
  6526. *
  6527. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6528. *
  6529. *
  6530. * #### `controller`
  6531. * Controller constructor function. The controller is instantiated before the
  6532. * pre-linking phase and can be accessed by other directives (see
  6533. * `require` attribute). This allows the directives to communicate with each other and augment
  6534. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6535. *
  6536. * * `$scope` - Current scope associated with the element
  6537. * * `$element` - Current element
  6538. * * `$attrs` - Current attributes object for the element
  6539. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6540. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6541. * * `scope`: (optional) override the scope.
  6542. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6543. * * `futureParentElement` (optional):
  6544. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6545. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6546. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6547. * and when the `cloneLinkingFn` is passed,
  6548. * as those elements need to created and cloned in a special way when they are defined outside their
  6549. * usual containers (e.g. like `<svg>`).
  6550. * * See also the `directive.templateNamespace` property.
  6551. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6552. * then the default transclusion is provided.
  6553. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6554. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6555. *
  6556. * #### `require`
  6557. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6558. * `require` property can be a string, an array or an object:
  6559. * * a **string** containing the name of the directive to pass to the linking function
  6560. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6561. * linking function will be an array of controllers in the same order as the names in the `require` property
  6562. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6563. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6564. * controllers.
  6565. *
  6566. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6567. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6568. * have been constructed but before `$onInit` is called.
  6569. * If the name of the required controller is the same as the local name (the key), the name can be
  6570. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  6571. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6572. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6573. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6574. * controller, in which case error checking is skipped). The name can be prefixed with:
  6575. *
  6576. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6577. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6578. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6579. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6580. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6581. * `null` to the `link` fn if not found.
  6582. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6583. * `null` to the `link` fn if not found.
  6584. *
  6585. *
  6586. * #### `controllerAs`
  6587. * Identifier name for a reference to the controller in the directive's scope.
  6588. * This allows the controller to be referenced from the directive template. This is especially
  6589. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6590. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6591. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6592. *
  6593. *
  6594. * #### `restrict`
  6595. * String of subset of `EACM` which restricts the directive to a specific directive
  6596. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6597. *
  6598. * * `E` - Element name (default): `<my-directive></my-directive>`
  6599. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6600. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6601. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6602. *
  6603. *
  6604. * #### `templateNamespace`
  6605. * String representing the document type used by the markup in the template.
  6606. * AngularJS needs this information as those elements need to be created and cloned
  6607. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6608. *
  6609. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6610. * top-level elements such as `<svg>` or `<math>`.
  6611. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6612. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6613. *
  6614. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6615. *
  6616. * #### `template`
  6617. * HTML markup that may:
  6618. * * Replace the contents of the directive's element (default).
  6619. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6620. * * Wrap the contents of the directive's element (if `transclude` is true).
  6621. *
  6622. * Value may be:
  6623. *
  6624. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6625. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6626. * function api below) and returns a string value.
  6627. *
  6628. *
  6629. * #### `templateUrl`
  6630. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6631. *
  6632. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6633. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6634. * sibling and parent elements as though this element had not contained any directives.
  6635. *
  6636. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6637. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6638. * case when only one deeply nested directive has `templateUrl`.
  6639. *
  6640. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6641. *
  6642. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6643. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6644. * a string value representing the url. In either case, the template URL is passed through {@link
  6645. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6646. *
  6647. *
  6648. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  6649. * specify what the template should replace. Defaults to `false`.
  6650. *
  6651. * * `true` - the template will replace the directive's element.
  6652. * * `false` - the template will replace the contents of the directive's element.
  6653. *
  6654. * The replacement process migrates all of the attributes / classes from the old element to the new
  6655. * one. See the {@link guide/directive#template-expanding-directive
  6656. * Directives Guide} for an example.
  6657. *
  6658. * There are very few scenarios where element replacement is required for the application function,
  6659. * the main one being reusable custom components that are used within SVG contexts
  6660. * (because SVG doesn't work with custom elements in the DOM tree).
  6661. *
  6662. * #### `transclude`
  6663. * Extract the contents of the element where the directive appears and make it available to the directive.
  6664. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6665. * {@link $compile#transclusion Transclusion} section below.
  6666. *
  6667. *
  6668. * #### `compile`
  6669. *
  6670. * ```js
  6671. * function compile(tElement, tAttrs, transclude) { ... }
  6672. * ```
  6673. *
  6674. * The compile function deals with transforming the template DOM. Since most directives do not do
  6675. * template transformation, it is not used often. The compile function takes the following arguments:
  6676. *
  6677. * * `tElement` - template element - The element where the directive has been declared. It is
  6678. * safe to do template transformation on the element and child elements only.
  6679. *
  6680. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6681. * between all directive compile functions.
  6682. *
  6683. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6684. *
  6685. * <div class="alert alert-warning">
  6686. * **Note:** The template instance and the link instance may be different objects if the template has
  6687. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6688. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6689. * should be done in a linking function rather than in a compile function.
  6690. * </div>
  6691. * <div class="alert alert-warning">
  6692. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6693. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6694. * stack overflow errors.
  6695. *
  6696. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6697. * a directive's template instead of relying on automatic template compilation via `template` or
  6698. * `templateUrl` declaration or manual compilation inside the compile function.
  6699. * </div>
  6700. *
  6701. * <div class="alert alert-danger">
  6702. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6703. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6704. * to the link function instead.
  6705. * </div>
  6706. * A compile function can have a return value which can be either a function or an object.
  6707. *
  6708. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6709. * `link` property of the config object when the compile function is empty.
  6710. *
  6711. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6712. * control when a linking function should be called during the linking phase. See info about
  6713. * pre-linking and post-linking functions below.
  6714. *
  6715. *
  6716. * #### `link`
  6717. * This property is used only if the `compile` property is not defined.
  6718. *
  6719. * ```js
  6720. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6721. * ```
  6722. *
  6723. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6724. * executed after the template has been cloned. This is where most of the directive logic will be
  6725. * put.
  6726. *
  6727. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6728. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6729. *
  6730. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6731. * manipulate the children of the element only in `postLink` function since the children have
  6732. * already been linked.
  6733. *
  6734. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6735. * between all directive linking functions.
  6736. *
  6737. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6738. * among all directives, which allows the directives to use the controllers as a communication
  6739. * channel. The exact value depends on the directive's `require` property:
  6740. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6741. * * `string`: the controller instance
  6742. * * `array`: array of controller instances
  6743. *
  6744. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6745. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6746. *
  6747. * Note that you can also require the directive's own controller - it will be made available like
  6748. * any other controller.
  6749. *
  6750. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6751. * This is the same as the `$transclude` parameter of directive controllers,
  6752. * see {@link ng.$compile#-controller- the controller section for details}.
  6753. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6754. *
  6755. * #### Pre-linking function
  6756. *
  6757. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6758. * compiler linking function will fail to locate the correct elements for linking.
  6759. *
  6760. * #### Post-linking function
  6761. *
  6762. * Executed after the child elements are linked.
  6763. *
  6764. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6765. * and linked since they are waiting for their template to load asynchronously and their own
  6766. * compilation and linking has been suspended until that occurs.
  6767. *
  6768. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6769. * for their async templates to be resolved.
  6770. *
  6771. *
  6772. * ### Transclusion
  6773. *
  6774. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6775. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6776. * scope from where they were taken.
  6777. *
  6778. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6779. * original contents of a directive's element into a specified place in the template of the directive.
  6780. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6781. * content has access to the properties on the scope from which it was taken, even if the directive
  6782. * has isolated scope.
  6783. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6784. *
  6785. * This makes it possible for the widget to have private state for its template, while the transcluded
  6786. * content has access to its originating scope.
  6787. *
  6788. * <div class="alert alert-warning">
  6789. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6790. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6791. * Testing Transclusion Directives}.
  6792. * </div>
  6793. *
  6794. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  6795. * directive's element, the entire element or multiple parts of the element contents:
  6796. *
  6797. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  6798. * * `'element'` - transclude the whole of the directive's element including any directives on this
  6799. * element that defined at a lower priority than this directive. When used, the `template`
  6800. * property is ignored.
  6801. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  6802. *
  6803. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  6804. *
  6805. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  6806. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  6807. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  6808. *
  6809. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6810. *
  6811. * If the element selector is prefixed with a `?` then that slot is optional.
  6812. *
  6813. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  6814. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  6815. *
  6816. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  6817. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  6818. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  6819. * injectable into the directive's controller.
  6820. *
  6821. *
  6822. * #### Transclusion Functions
  6823. *
  6824. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6825. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6826. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6827. *
  6828. * <div class="alert alert-info">
  6829. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6830. * ngTransclude will deal with it for us.
  6831. * </div>
  6832. *
  6833. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6834. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6835. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6836. *
  6837. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6838. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6839. * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
  6840. *
  6841. * <div class="alert alert-info">
  6842. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  6843. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6844. * </div>
  6845. *
  6846. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6847. * attach function**:
  6848. *
  6849. * ```js
  6850. * var transcludedContent, transclusionScope;
  6851. *
  6852. * $transclude(function(clone, scope) {
  6853. * element.append(clone);
  6854. * transcludedContent = clone;
  6855. * transclusionScope = scope;
  6856. * });
  6857. * ```
  6858. *
  6859. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6860. * associated transclusion scope:
  6861. *
  6862. * ```js
  6863. * transcludedContent.remove();
  6864. * transclusionScope.$destroy();
  6865. * ```
  6866. *
  6867. * <div class="alert alert-info">
  6868. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6869. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6870. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6871. * </div>
  6872. *
  6873. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6874. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  6875. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6876. *
  6877. *
  6878. * #### Transclusion Scopes
  6879. *
  6880. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6881. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6882. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6883. * was taken.
  6884. *
  6885. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6886. * like this:
  6887. *
  6888. * ```html
  6889. * <div ng-app>
  6890. * <div isolate>
  6891. * <div transclusion>
  6892. * </div>
  6893. * </div>
  6894. * </div>
  6895. * ```
  6896. *
  6897. * The `$parent` scope hierarchy will look like this:
  6898. *
  6899. ```
  6900. - $rootScope
  6901. - isolate
  6902. - transclusion
  6903. ```
  6904. *
  6905. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6906. *
  6907. ```
  6908. - $rootScope
  6909. - transclusion
  6910. - isolate
  6911. ```
  6912. *
  6913. *
  6914. * ### Attributes
  6915. *
  6916. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6917. * `link()` or `compile()` functions. It has a variety of uses.
  6918. *
  6919. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  6920. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  6921. * to the attributes.
  6922. *
  6923. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6924. * object which allows the directives to use the attributes object as inter directive
  6925. * communication.
  6926. *
  6927. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6928. * allowing other directives to read the interpolated value.
  6929. *
  6930. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6931. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6932. * the only way to easily get the actual value because during the linking phase the interpolation
  6933. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6934. *
  6935. * ```js
  6936. * function linkingFn(scope, elm, attrs, ctrl) {
  6937. * // get the attribute value
  6938. * console.log(attrs.ngModel);
  6939. *
  6940. * // change the attribute
  6941. * attrs.$set('ngModel', 'new value');
  6942. *
  6943. * // observe changes to interpolated attribute
  6944. * attrs.$observe('ngModel', function(value) {
  6945. * console.log('ngModel has changed value to ' + value);
  6946. * });
  6947. * }
  6948. * ```
  6949. *
  6950. * ## Example
  6951. *
  6952. * <div class="alert alert-warning">
  6953. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6954. * to illustrate how `$compile` works.
  6955. * </div>
  6956. *
  6957. <example module="compileExample" name="compile">
  6958. <file name="index.html">
  6959. <script>
  6960. angular.module('compileExample', [], function($compileProvider) {
  6961. // configure new 'compile' directive by passing a directive
  6962. // factory function. The factory function injects the '$compile'
  6963. $compileProvider.directive('compile', function($compile) {
  6964. // directive factory creates a link function
  6965. return function(scope, element, attrs) {
  6966. scope.$watch(
  6967. function(scope) {
  6968. // watch the 'compile' expression for changes
  6969. return scope.$eval(attrs.compile);
  6970. },
  6971. function(value) {
  6972. // when the 'compile' expression changes
  6973. // assign it into the current DOM
  6974. element.html(value);
  6975. // compile the new DOM and link it to the current
  6976. // scope.
  6977. // NOTE: we only compile .childNodes so that
  6978. // we don't get into infinite loop compiling ourselves
  6979. $compile(element.contents())(scope);
  6980. }
  6981. );
  6982. };
  6983. });
  6984. })
  6985. .controller('GreeterController', ['$scope', function($scope) {
  6986. $scope.name = 'Angular';
  6987. $scope.html = 'Hello {{name}}';
  6988. }]);
  6989. </script>
  6990. <div ng-controller="GreeterController">
  6991. <input ng-model="name"> <br/>
  6992. <textarea ng-model="html"></textarea> <br/>
  6993. <div compile="html"></div>
  6994. </div>
  6995. </file>
  6996. <file name="protractor.js" type="protractor">
  6997. it('should auto compile', function() {
  6998. var textarea = $('textarea');
  6999. var output = $('div[compile]');
  7000. // The initial state reads 'Hello Angular'.
  7001. expect(output.getText()).toBe('Hello Angular');
  7002. textarea.clear();
  7003. textarea.sendKeys('{{name}}!');
  7004. expect(output.getText()).toBe('Angular!');
  7005. });
  7006. </file>
  7007. </example>
  7008. *
  7009. *
  7010. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  7011. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  7012. *
  7013. * <div class="alert alert-danger">
  7014. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  7015. * e.g. will not use the right outer scope. Please pass the transclude function as a
  7016. * `parentBoundTranscludeFn` to the link function instead.
  7017. * </div>
  7018. *
  7019. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  7020. * root element(s), not their children)
  7021. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  7022. * (a DOM element/tree) to a scope. Where:
  7023. *
  7024. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  7025. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  7026. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  7027. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  7028. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  7029. *
  7030. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  7031. * * `scope` - is the current scope with which the linking function is working with.
  7032. *
  7033. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  7034. * keys may be used to control linking behavior:
  7035. *
  7036. * * `parentBoundTranscludeFn` - the transclude function made available to
  7037. * directives; if given, it will be passed through to the link functions of
  7038. * directives found in `element` during compilation.
  7039. * * `transcludeControllers` - an object hash with keys that map controller names
  7040. * to a hash with the key `instance`, which maps to the controller instance;
  7041. * if given, it will make the controllers available to directives on the compileNode:
  7042. * ```
  7043. * {
  7044. * parent: {
  7045. * instance: parentControllerInstance
  7046. * }
  7047. * }
  7048. * ```
  7049. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  7050. * the cloned elements; only needed for transcludes that are allowed to contain non html
  7051. * elements (e.g. SVG elements). See also the directive.controller property.
  7052. *
  7053. * Calling the linking function returns the element of the template. It is either the original
  7054. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  7055. *
  7056. * After linking the view is not updated until after a call to $digest which typically is done by
  7057. * Angular automatically.
  7058. *
  7059. * If you need access to the bound view, there are two ways to do it:
  7060. *
  7061. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  7062. * before you send them to the compiler and keep this reference around.
  7063. * ```js
  7064. * var element = $compile('<p>{{total}}</p>')(scope);
  7065. * ```
  7066. *
  7067. * - if on the other hand, you need the element to be cloned, the view reference from the original
  7068. * example would not point to the clone, but rather to the original template that was cloned. In
  7069. * this case, you can access the clone via the cloneAttachFn:
  7070. * ```js
  7071. * var templateElement = angular.element('<p>{{total}}</p>'),
  7072. * scope = ....;
  7073. *
  7074. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  7075. * //attach the clone to DOM document at the right place
  7076. * });
  7077. *
  7078. * //now we have reference to the cloned DOM via `clonedElement`
  7079. * ```
  7080. *
  7081. *
  7082. * For information on how the compiler works, see the
  7083. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  7084. *
  7085. * @knownIssue
  7086. *
  7087. * ### Double Compilation
  7088. *
  7089. Double compilation occurs when an already compiled part of the DOM gets
  7090. compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,
  7091. and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it
  7092. section on double compilation} for an in-depth explanation and ways to avoid it.
  7093. *
  7094. */
  7095. var $compileMinErr = minErr('$compile');
  7096. function UNINITIALIZED_VALUE() {}
  7097. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  7098. /**
  7099. * @ngdoc provider
  7100. * @name $compileProvider
  7101. *
  7102. * @description
  7103. */
  7104. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  7105. /** @this */
  7106. function $CompileProvider($provide, $$sanitizeUriProvider) {
  7107. var hasDirectives = {},
  7108. Suffix = 'Directive',
  7109. COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/,
  7110. CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,
  7111. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  7112. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  7113. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  7114. // The assumption is that future DOM event attribute names will begin with
  7115. // 'on' and be composed of only English letters.
  7116. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  7117. var bindingCache = createMap();
  7118. function parseIsolateBindings(scope, directiveName, isController) {
  7119. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*([\w$]*)\s*$/;
  7120. var bindings = createMap();
  7121. forEach(scope, function(definition, scopeName) {
  7122. if (definition in bindingCache) {
  7123. bindings[scopeName] = bindingCache[definition];
  7124. return;
  7125. }
  7126. var match = definition.match(LOCAL_REGEXP);
  7127. if (!match) {
  7128. throw $compileMinErr('iscp',
  7129. 'Invalid {3} for directive \'{0}\'.' +
  7130. ' Definition: {... {1}: \'{2}\' ...}',
  7131. directiveName, scopeName, definition,
  7132. (isController ? 'controller bindings definition' :
  7133. 'isolate scope definition'));
  7134. }
  7135. bindings[scopeName] = {
  7136. mode: match[1][0],
  7137. collection: match[2] === '*',
  7138. optional: match[3] === '?',
  7139. attrName: match[4] || scopeName
  7140. };
  7141. if (match[4]) {
  7142. bindingCache[definition] = bindings[scopeName];
  7143. }
  7144. });
  7145. return bindings;
  7146. }
  7147. function parseDirectiveBindings(directive, directiveName) {
  7148. var bindings = {
  7149. isolateScope: null,
  7150. bindToController: null
  7151. };
  7152. if (isObject(directive.scope)) {
  7153. if (directive.bindToController === true) {
  7154. bindings.bindToController = parseIsolateBindings(directive.scope,
  7155. directiveName, true);
  7156. bindings.isolateScope = {};
  7157. } else {
  7158. bindings.isolateScope = parseIsolateBindings(directive.scope,
  7159. directiveName, false);
  7160. }
  7161. }
  7162. if (isObject(directive.bindToController)) {
  7163. bindings.bindToController =
  7164. parseIsolateBindings(directive.bindToController, directiveName, true);
  7165. }
  7166. if (bindings.bindToController && !directive.controller) {
  7167. // There is no controller
  7168. throw $compileMinErr('noctrl',
  7169. 'Cannot bind to controller without directive \'{0}\'s controller.',
  7170. directiveName);
  7171. }
  7172. return bindings;
  7173. }
  7174. function assertValidDirectiveName(name) {
  7175. var letter = name.charAt(0);
  7176. if (!letter || letter !== lowercase(letter)) {
  7177. throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
  7178. }
  7179. if (name !== name.trim()) {
  7180. throw $compileMinErr('baddir',
  7181. 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
  7182. name);
  7183. }
  7184. }
  7185. function getDirectiveRequire(directive) {
  7186. var require = directive.require || (directive.controller && directive.name);
  7187. if (!isArray(require) && isObject(require)) {
  7188. forEach(require, function(value, key) {
  7189. var match = value.match(REQUIRE_PREFIX_REGEXP);
  7190. var name = value.substring(match[0].length);
  7191. if (!name) require[key] = match[0] + key;
  7192. });
  7193. }
  7194. return require;
  7195. }
  7196. function getDirectiveRestrict(restrict, name) {
  7197. if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
  7198. throw $compileMinErr('badrestrict',
  7199. 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
  7200. restrict,
  7201. name);
  7202. }
  7203. return restrict || 'EA';
  7204. }
  7205. /**
  7206. * @ngdoc method
  7207. * @name $compileProvider#directive
  7208. * @kind function
  7209. *
  7210. * @description
  7211. * Register a new directive with the compiler.
  7212. *
  7213. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  7214. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  7215. * names and the values are the factories.
  7216. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  7217. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  7218. * @returns {ng.$compileProvider} Self for chaining.
  7219. */
  7220. this.directive = function registerDirective(name, directiveFactory) {
  7221. assertArg(name, 'name');
  7222. assertNotHasOwnProperty(name, 'directive');
  7223. if (isString(name)) {
  7224. assertValidDirectiveName(name);
  7225. assertArg(directiveFactory, 'directiveFactory');
  7226. if (!hasDirectives.hasOwnProperty(name)) {
  7227. hasDirectives[name] = [];
  7228. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  7229. function($injector, $exceptionHandler) {
  7230. var directives = [];
  7231. forEach(hasDirectives[name], function(directiveFactory, index) {
  7232. try {
  7233. var directive = $injector.invoke(directiveFactory);
  7234. if (isFunction(directive)) {
  7235. directive = { compile: valueFn(directive) };
  7236. } else if (!directive.compile && directive.link) {
  7237. directive.compile = valueFn(directive.link);
  7238. }
  7239. directive.priority = directive.priority || 0;
  7240. directive.index = index;
  7241. directive.name = directive.name || name;
  7242. directive.require = getDirectiveRequire(directive);
  7243. directive.restrict = getDirectiveRestrict(directive.restrict, name);
  7244. directive.$$moduleName = directiveFactory.$$moduleName;
  7245. directives.push(directive);
  7246. } catch (e) {
  7247. $exceptionHandler(e);
  7248. }
  7249. });
  7250. return directives;
  7251. }]);
  7252. }
  7253. hasDirectives[name].push(directiveFactory);
  7254. } else {
  7255. forEach(name, reverseParams(registerDirective));
  7256. }
  7257. return this;
  7258. };
  7259. /**
  7260. * @ngdoc method
  7261. * @name $compileProvider#component
  7262. * @module ng
  7263. * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
  7264. * @param {Object} options Component definition object (a simplified
  7265. * {@link ng.$compile#directive-definition-object directive definition object}),
  7266. * with the following properties (all optional):
  7267. *
  7268. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  7269. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  7270. * registered controller} if passed as a string. An empty `noop` function by default.
  7271. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  7272. * If present, the controller will be published to scope under the `controllerAs` name.
  7273. * If not present, this will default to be `$ctrl`.
  7274. * - `template` – `{string=|function()=}` – html template as a string or a function that
  7275. * returns an html template as a string which should be used as the contents of this component.
  7276. * Empty string by default.
  7277. *
  7278. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  7279. * the following locals:
  7280. *
  7281. * - `$element` - Current element
  7282. * - `$attrs` - Current attributes object for the element
  7283. *
  7284. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  7285. * template that should be used as the contents of this component.
  7286. *
  7287. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  7288. * the following locals:
  7289. *
  7290. * - `$element` - Current element
  7291. * - `$attrs` - Current attributes object for the element
  7292. *
  7293. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  7294. * Component properties are always bound to the component controller and not to the scope.
  7295. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  7296. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  7297. * Disabled by default.
  7298. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  7299. * this component's controller. The object keys specify the property names under which the required
  7300. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  7301. * - `$...` – additional properties to attach to the directive factory function and the controller
  7302. * constructor function. (This is used by the component router to annotate)
  7303. *
  7304. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  7305. * @description
  7306. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  7307. * type of directive, which represents a self-contained UI component in your application. Such components
  7308. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  7309. *
  7310. * Component definitions are very simple and do not require as much configuration as defining general
  7311. * directives. Component definitions usually consist only of a template and a controller backing it.
  7312. *
  7313. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  7314. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  7315. *
  7316. * Here are a few examples of how you would usually define components:
  7317. *
  7318. * ```js
  7319. * var myMod = angular.module(...);
  7320. * myMod.component('myComp', {
  7321. * template: '<div>My name is {{$ctrl.name}}</div>',
  7322. * controller: function() {
  7323. * this.name = 'shahar';
  7324. * }
  7325. * });
  7326. *
  7327. * myMod.component('myComp', {
  7328. * template: '<div>My name is {{$ctrl.name}}</div>',
  7329. * bindings: {name: '@'}
  7330. * });
  7331. *
  7332. * myMod.component('myComp', {
  7333. * templateUrl: 'views/my-comp.html',
  7334. * controller: 'MyCtrl',
  7335. * controllerAs: 'ctrl',
  7336. * bindings: {name: '@'}
  7337. * });
  7338. *
  7339. * ```
  7340. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  7341. *
  7342. * <br />
  7343. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  7344. */
  7345. this.component = function registerComponent(name, options) {
  7346. var controller = options.controller || function() {};
  7347. function factory($injector) {
  7348. function makeInjectable(fn) {
  7349. if (isFunction(fn) || isArray(fn)) {
  7350. return /** @this */ function(tElement, tAttrs) {
  7351. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  7352. };
  7353. } else {
  7354. return fn;
  7355. }
  7356. }
  7357. var template = (!options.template && !options.templateUrl ? '' : options.template);
  7358. var ddo = {
  7359. controller: controller,
  7360. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  7361. template: makeInjectable(template),
  7362. templateUrl: makeInjectable(options.templateUrl),
  7363. transclude: options.transclude,
  7364. scope: {},
  7365. bindToController: options.bindings || {},
  7366. restrict: 'E',
  7367. require: options.require
  7368. };
  7369. // Copy annotations (starting with $) over to the DDO
  7370. forEach(options, function(val, key) {
  7371. if (key.charAt(0) === '$') ddo[key] = val;
  7372. });
  7373. return ddo;
  7374. }
  7375. // TODO(pete) remove the following `forEach` before we release 1.6.0
  7376. // The component-router@0.2.0 looks for the annotations on the controller constructor
  7377. // Nothing in Angular looks for annotations on the factory function but we can't remove
  7378. // it from 1.5.x yet.
  7379. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  7380. // These could be used by libraries such as the new component router
  7381. forEach(options, function(val, key) {
  7382. if (key.charAt(0) === '$') {
  7383. factory[key] = val;
  7384. // Don't try to copy over annotations to named controller
  7385. if (isFunction(controller)) controller[key] = val;
  7386. }
  7387. });
  7388. factory.$inject = ['$injector'];
  7389. return this.directive(name, factory);
  7390. };
  7391. /**
  7392. * @ngdoc method
  7393. * @name $compileProvider#aHrefSanitizationWhitelist
  7394. * @kind function
  7395. *
  7396. * @description
  7397. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7398. * urls during a[href] sanitization.
  7399. *
  7400. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  7401. *
  7402. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  7403. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  7404. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7405. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7406. *
  7407. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7408. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7409. * chaining otherwise.
  7410. */
  7411. this.aHrefSanitizationWhitelist = function(regexp) {
  7412. if (isDefined(regexp)) {
  7413. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  7414. return this;
  7415. } else {
  7416. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  7417. }
  7418. };
  7419. /**
  7420. * @ngdoc method
  7421. * @name $compileProvider#imgSrcSanitizationWhitelist
  7422. * @kind function
  7423. *
  7424. * @description
  7425. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7426. * urls during img[src] sanitization.
  7427. *
  7428. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  7429. *
  7430. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  7431. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  7432. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7433. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7434. *
  7435. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7436. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7437. * chaining otherwise.
  7438. */
  7439. this.imgSrcSanitizationWhitelist = function(regexp) {
  7440. if (isDefined(regexp)) {
  7441. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  7442. return this;
  7443. } else {
  7444. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  7445. }
  7446. };
  7447. /**
  7448. * @ngdoc method
  7449. * @name $compileProvider#debugInfoEnabled
  7450. *
  7451. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  7452. * current debugInfoEnabled state
  7453. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7454. *
  7455. * @kind function
  7456. *
  7457. * @description
  7458. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7459. * binding information and a reference to the current scope on to DOM elements.
  7460. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7461. * * `ng-binding` CSS class
  7462. * * `$binding` data property containing an array of the binding expressions
  7463. *
  7464. * You may want to disable this in production for a significant performance boost. See
  7465. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7466. *
  7467. * The default value is true.
  7468. */
  7469. var debugInfoEnabled = true;
  7470. this.debugInfoEnabled = function(enabled) {
  7471. if (isDefined(enabled)) {
  7472. debugInfoEnabled = enabled;
  7473. return this;
  7474. }
  7475. return debugInfoEnabled;
  7476. };
  7477. /**
  7478. * @ngdoc method
  7479. * @name $compileProvider#preAssignBindingsEnabled
  7480. *
  7481. * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the
  7482. * current preAssignBindingsEnabled state
  7483. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7484. *
  7485. * @kind function
  7486. *
  7487. * @description
  7488. * Call this method to enable/disable whether directive controllers are assigned bindings before
  7489. * calling the controller's constructor.
  7490. * If enabled (true), the compiler assigns the value of each of the bindings to the
  7491. * properties of the controller object before the constructor of this object is called.
  7492. *
  7493. * If disabled (false), the compiler calls the constructor first before assigning bindings.
  7494. *
  7495. * The default value is true in Angular 1.5.x but will switch to false in Angular 1.6.x.
  7496. */
  7497. var preAssignBindingsEnabled = false;
  7498. this.preAssignBindingsEnabled = function(enabled) {
  7499. if (isDefined(enabled)) {
  7500. preAssignBindingsEnabled = enabled;
  7501. return this;
  7502. }
  7503. return preAssignBindingsEnabled;
  7504. };
  7505. var TTL = 10;
  7506. /**
  7507. * @ngdoc method
  7508. * @name $compileProvider#onChangesTtl
  7509. * @description
  7510. *
  7511. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  7512. * assuming that the model is unstable.
  7513. *
  7514. * The current default is 10 iterations.
  7515. *
  7516. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  7517. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  7518. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  7519. * the `$onChanges` hook execution.
  7520. *
  7521. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  7522. *
  7523. * @param {number} limit The number of `$onChanges` hook iterations.
  7524. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  7525. */
  7526. this.onChangesTtl = function(value) {
  7527. if (arguments.length) {
  7528. TTL = value;
  7529. return this;
  7530. }
  7531. return TTL;
  7532. };
  7533. var commentDirectivesEnabledConfig = true;
  7534. /**
  7535. * @ngdoc method
  7536. * @name $compileProvider#commentDirectivesEnabled
  7537. * @description
  7538. *
  7539. * It indicates to the compiler
  7540. * whether or not directives on comments should be compiled.
  7541. * Defaults to `true`.
  7542. *
  7543. * Calling this function with false disables the compilation of directives
  7544. * on comments for the whole application.
  7545. * This results in a compilation performance gain,
  7546. * as the compiler doesn't have to check comments when looking for directives.
  7547. * This should however only be used if you are sure that no comment directives are used in
  7548. * the application (including any 3rd party directives).
  7549. *
  7550. * @param {boolean} enabled `false` if the compiler may ignore directives on comments
  7551. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7552. */
  7553. this.commentDirectivesEnabled = function(value) {
  7554. if (arguments.length) {
  7555. commentDirectivesEnabledConfig = value;
  7556. return this;
  7557. }
  7558. return commentDirectivesEnabledConfig;
  7559. };
  7560. var cssClassDirectivesEnabledConfig = true;
  7561. /**
  7562. * @ngdoc method
  7563. * @name $compileProvider#cssClassDirectivesEnabled
  7564. * @description
  7565. *
  7566. * It indicates to the compiler
  7567. * whether or not directives on element classes should be compiled.
  7568. * Defaults to `true`.
  7569. *
  7570. * Calling this function with false disables the compilation of directives
  7571. * on element classes for the whole application.
  7572. * This results in a compilation performance gain,
  7573. * as the compiler doesn't have to check element classes when looking for directives.
  7574. * This should however only be used if you are sure that no class directives are used in
  7575. * the application (including any 3rd party directives).
  7576. *
  7577. * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
  7578. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7579. */
  7580. this.cssClassDirectivesEnabled = function(value) {
  7581. if (arguments.length) {
  7582. cssClassDirectivesEnabledConfig = value;
  7583. return this;
  7584. }
  7585. return cssClassDirectivesEnabledConfig;
  7586. };
  7587. this.$get = [
  7588. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7589. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7590. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7591. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7592. var SIMPLE_ATTR_NAME = /^\w/;
  7593. var specialAttrHolder = window.document.createElement('div');
  7594. var commentDirectivesEnabled = commentDirectivesEnabledConfig;
  7595. var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
  7596. var onChangesTtl = TTL;
  7597. // The onChanges hooks should all be run together in a single digest
  7598. // When changes occur, the call to trigger their hooks will be added to this queue
  7599. var onChangesQueue;
  7600. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  7601. function flushOnChangesQueue() {
  7602. try {
  7603. if (!(--onChangesTtl)) {
  7604. // We have hit the TTL limit so reset everything
  7605. onChangesQueue = undefined;
  7606. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  7607. }
  7608. // We must run this hook in an apply since the $$postDigest runs outside apply
  7609. $rootScope.$apply(function() {
  7610. var errors = [];
  7611. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  7612. try {
  7613. onChangesQueue[i]();
  7614. } catch (e) {
  7615. errors.push(e);
  7616. }
  7617. }
  7618. // Reset the queue to trigger a new schedule next time there is a change
  7619. onChangesQueue = undefined;
  7620. if (errors.length) {
  7621. throw errors;
  7622. }
  7623. });
  7624. } finally {
  7625. onChangesTtl++;
  7626. }
  7627. }
  7628. function Attributes(element, attributesToCopy) {
  7629. if (attributesToCopy) {
  7630. var keys = Object.keys(attributesToCopy);
  7631. var i, l, key;
  7632. for (i = 0, l = keys.length; i < l; i++) {
  7633. key = keys[i];
  7634. this[key] = attributesToCopy[key];
  7635. }
  7636. } else {
  7637. this.$attr = {};
  7638. }
  7639. this.$$element = element;
  7640. }
  7641. Attributes.prototype = {
  7642. /**
  7643. * @ngdoc method
  7644. * @name $compile.directive.Attributes#$normalize
  7645. * @kind function
  7646. *
  7647. * @description
  7648. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7649. * `data-`) to its normalized, camelCase form.
  7650. *
  7651. * Also there is special case for Moz prefix starting with upper case letter.
  7652. *
  7653. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7654. *
  7655. * @param {string} name Name to normalize
  7656. */
  7657. $normalize: directiveNormalize,
  7658. /**
  7659. * @ngdoc method
  7660. * @name $compile.directive.Attributes#$addClass
  7661. * @kind function
  7662. *
  7663. * @description
  7664. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7665. * are enabled then an animation will be triggered for the class addition.
  7666. *
  7667. * @param {string} classVal The className value that will be added to the element
  7668. */
  7669. $addClass: function(classVal) {
  7670. if (classVal && classVal.length > 0) {
  7671. $animate.addClass(this.$$element, classVal);
  7672. }
  7673. },
  7674. /**
  7675. * @ngdoc method
  7676. * @name $compile.directive.Attributes#$removeClass
  7677. * @kind function
  7678. *
  7679. * @description
  7680. * Removes the CSS class value specified by the classVal parameter from the element. If
  7681. * animations are enabled then an animation will be triggered for the class removal.
  7682. *
  7683. * @param {string} classVal The className value that will be removed from the element
  7684. */
  7685. $removeClass: function(classVal) {
  7686. if (classVal && classVal.length > 0) {
  7687. $animate.removeClass(this.$$element, classVal);
  7688. }
  7689. },
  7690. /**
  7691. * @ngdoc method
  7692. * @name $compile.directive.Attributes#$updateClass
  7693. * @kind function
  7694. *
  7695. * @description
  7696. * Adds and removes the appropriate CSS class values to the element based on the difference
  7697. * between the new and old CSS class values (specified as newClasses and oldClasses).
  7698. *
  7699. * @param {string} newClasses The current CSS className value
  7700. * @param {string} oldClasses The former CSS className value
  7701. */
  7702. $updateClass: function(newClasses, oldClasses) {
  7703. var toAdd = tokenDifference(newClasses, oldClasses);
  7704. if (toAdd && toAdd.length) {
  7705. $animate.addClass(this.$$element, toAdd);
  7706. }
  7707. var toRemove = tokenDifference(oldClasses, newClasses);
  7708. if (toRemove && toRemove.length) {
  7709. $animate.removeClass(this.$$element, toRemove);
  7710. }
  7711. },
  7712. /**
  7713. * Set a normalized attribute on the element in a way such that all directives
  7714. * can share the attribute. This function properly handles boolean attributes.
  7715. * @param {string} key Normalized key. (ie ngAttribute)
  7716. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  7717. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  7718. * Defaults to true.
  7719. * @param {string=} attrName Optional none normalized name. Defaults to key.
  7720. */
  7721. $set: function(key, value, writeAttr, attrName) {
  7722. // TODO: decide whether or not to throw an error if "class"
  7723. //is set through this function since it may cause $updateClass to
  7724. //become unstable.
  7725. var node = this.$$element[0],
  7726. booleanKey = getBooleanAttrName(node, key),
  7727. aliasedKey = getAliasedAttrName(key),
  7728. observer = key,
  7729. nodeName;
  7730. if (booleanKey) {
  7731. this.$$element.prop(key, value);
  7732. attrName = booleanKey;
  7733. } else if (aliasedKey) {
  7734. this[aliasedKey] = value;
  7735. observer = aliasedKey;
  7736. }
  7737. this[key] = value;
  7738. // translate normalized key to actual key
  7739. if (attrName) {
  7740. this.$attr[key] = attrName;
  7741. } else {
  7742. attrName = this.$attr[key];
  7743. if (!attrName) {
  7744. this.$attr[key] = attrName = snake_case(key, '-');
  7745. }
  7746. }
  7747. nodeName = nodeName_(this.$$element);
  7748. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  7749. (nodeName === 'img' && key === 'src')) {
  7750. // sanitize a[href] and img[src] values
  7751. this[key] = value = $$sanitizeUri(value, key === 'src');
  7752. } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
  7753. // sanitize img[srcset] values
  7754. var result = '';
  7755. // first check if there are spaces because it's not the same pattern
  7756. var trimmedSrcset = trim(value);
  7757. // ( 999x ,| 999w ,| ,|, )
  7758. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  7759. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  7760. // split srcset into tuple of uri and descriptor except for the last item
  7761. var rawUris = trimmedSrcset.split(pattern);
  7762. // for each tuples
  7763. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  7764. for (var i = 0; i < nbrUrisWith2parts; i++) {
  7765. var innerIdx = i * 2;
  7766. // sanitize the uri
  7767. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  7768. // add the descriptor
  7769. result += (' ' + trim(rawUris[innerIdx + 1]));
  7770. }
  7771. // split the last item into uri and descriptor
  7772. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  7773. // sanitize the last uri
  7774. result += $$sanitizeUri(trim(lastTuple[0]), true);
  7775. // and add the last descriptor if any
  7776. if (lastTuple.length === 2) {
  7777. result += (' ' + trim(lastTuple[1]));
  7778. }
  7779. this[key] = value = result;
  7780. }
  7781. if (writeAttr !== false) {
  7782. if (value === null || isUndefined(value)) {
  7783. this.$$element.removeAttr(attrName);
  7784. } else {
  7785. if (SIMPLE_ATTR_NAME.test(attrName)) {
  7786. this.$$element.attr(attrName, value);
  7787. } else {
  7788. setSpecialAttr(this.$$element[0], attrName, value);
  7789. }
  7790. }
  7791. }
  7792. // fire observers
  7793. var $$observers = this.$$observers;
  7794. if ($$observers) {
  7795. forEach($$observers[observer], function(fn) {
  7796. try {
  7797. fn(value);
  7798. } catch (e) {
  7799. $exceptionHandler(e);
  7800. }
  7801. });
  7802. }
  7803. },
  7804. /**
  7805. * @ngdoc method
  7806. * @name $compile.directive.Attributes#$observe
  7807. * @kind function
  7808. *
  7809. * @description
  7810. * Observes an interpolated attribute.
  7811. *
  7812. * The observer function will be invoked once during the next `$digest` following
  7813. * compilation. The observer is then invoked whenever the interpolated value
  7814. * changes.
  7815. *
  7816. * @param {string} key Normalized key. (ie ngAttribute) .
  7817. * @param {function(interpolatedValue)} fn Function that will be called whenever
  7818. the interpolated value of the attribute changes.
  7819. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  7820. * guide} for more info.
  7821. * @returns {function()} Returns a deregistration function for this observer.
  7822. */
  7823. $observe: function(key, fn) {
  7824. var attrs = this,
  7825. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  7826. listeners = ($$observers[key] || ($$observers[key] = []));
  7827. listeners.push(fn);
  7828. $rootScope.$evalAsync(function() {
  7829. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  7830. // no one registered attribute interpolation function, so lets call it manually
  7831. fn(attrs[key]);
  7832. }
  7833. });
  7834. return function() {
  7835. arrayRemove(listeners, fn);
  7836. };
  7837. }
  7838. };
  7839. function setSpecialAttr(element, attrName, value) {
  7840. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  7841. // so we have to jump through some hoops to get such an attribute
  7842. // https://github.com/angular/angular.js/pull/13318
  7843. specialAttrHolder.innerHTML = '<span ' + attrName + '>';
  7844. var attributes = specialAttrHolder.firstChild.attributes;
  7845. var attribute = attributes[0];
  7846. // We have to remove the attribute from its container element before we can add it to the destination element
  7847. attributes.removeNamedItem(attribute.name);
  7848. attribute.value = value;
  7849. element.attributes.setNamedItem(attribute);
  7850. }
  7851. function safeAddClass($element, className) {
  7852. try {
  7853. $element.addClass(className);
  7854. } catch (e) {
  7855. // ignore, since it means that we are trying to set class on
  7856. // SVG element, where class name is read-only.
  7857. }
  7858. }
  7859. var startSymbol = $interpolate.startSymbol(),
  7860. endSymbol = $interpolate.endSymbol(),
  7861. denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
  7862. ? identity
  7863. : function denormalizeTemplate(template) {
  7864. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  7865. },
  7866. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  7867. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  7868. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  7869. var bindings = $element.data('$binding') || [];
  7870. if (isArray(binding)) {
  7871. bindings = bindings.concat(binding);
  7872. } else {
  7873. bindings.push(binding);
  7874. }
  7875. $element.data('$binding', bindings);
  7876. } : noop;
  7877. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  7878. safeAddClass($element, 'ng-binding');
  7879. } : noop;
  7880. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  7881. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  7882. $element.data(dataName, scope);
  7883. } : noop;
  7884. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  7885. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  7886. } : noop;
  7887. compile.$$createComment = function(directiveName, comment) {
  7888. var content = '';
  7889. if (debugInfoEnabled) {
  7890. content = ' ' + (directiveName || '') + ': ';
  7891. if (comment) content += comment + ' ';
  7892. }
  7893. return window.document.createComment(content);
  7894. };
  7895. return compile;
  7896. //================================
  7897. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  7898. previousCompileContext) {
  7899. if (!($compileNodes instanceof jqLite)) {
  7900. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  7901. // modify it.
  7902. $compileNodes = jqLite($compileNodes);
  7903. }
  7904. var compositeLinkFn =
  7905. compileNodes($compileNodes, transcludeFn, $compileNodes,
  7906. maxPriority, ignoreDirective, previousCompileContext);
  7907. compile.$$addScopeClass($compileNodes);
  7908. var namespace = null;
  7909. return function publicLinkFn(scope, cloneConnectFn, options) {
  7910. if (!$compileNodes) {
  7911. throw $compileMinErr('multilink', 'This element has already been linked.');
  7912. }
  7913. assertArg(scope, 'scope');
  7914. if (previousCompileContext && previousCompileContext.needsNewScope) {
  7915. // A parent directive did a replace and a directive on this element asked
  7916. // for transclusion, which caused us to lose a layer of element on which
  7917. // we could hold the new transclusion scope, so we will create it manually
  7918. // here.
  7919. scope = scope.$parent.$new();
  7920. }
  7921. options = options || {};
  7922. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  7923. transcludeControllers = options.transcludeControllers,
  7924. futureParentElement = options.futureParentElement;
  7925. // When `parentBoundTranscludeFn` is passed, it is a
  7926. // `controllersBoundTransclude` function (it was previously passed
  7927. // as `transclude` to directive.link) so we must unwrap it to get
  7928. // its `boundTranscludeFn`
  7929. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  7930. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  7931. }
  7932. if (!namespace) {
  7933. namespace = detectNamespaceForChildElements(futureParentElement);
  7934. }
  7935. var $linkNode;
  7936. if (namespace !== 'html') {
  7937. // When using a directive with replace:true and templateUrl the $compileNodes
  7938. // (or a child element inside of them)
  7939. // might change, so we need to recreate the namespace adapted compileNodes
  7940. // for call to the link function.
  7941. // Note: This will already clone the nodes...
  7942. $linkNode = jqLite(
  7943. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  7944. );
  7945. } else if (cloneConnectFn) {
  7946. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  7947. // and sometimes changes the structure of the DOM.
  7948. $linkNode = JQLitePrototype.clone.call($compileNodes);
  7949. } else {
  7950. $linkNode = $compileNodes;
  7951. }
  7952. if (transcludeControllers) {
  7953. for (var controllerName in transcludeControllers) {
  7954. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  7955. }
  7956. }
  7957. compile.$$addScopeInfo($linkNode, scope);
  7958. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  7959. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  7960. if (!cloneConnectFn) {
  7961. $compileNodes = compositeLinkFn = null;
  7962. }
  7963. return $linkNode;
  7964. };
  7965. }
  7966. function detectNamespaceForChildElements(parentElement) {
  7967. // TODO: Make this detect MathML as well...
  7968. var node = parentElement && parentElement[0];
  7969. if (!node) {
  7970. return 'html';
  7971. } else {
  7972. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  7973. }
  7974. }
  7975. /**
  7976. * Compile function matches each node in nodeList against the directives. Once all directives
  7977. * for a particular node are collected their compile functions are executed. The compile
  7978. * functions return values - the linking functions - are combined into a composite linking
  7979. * function, which is the a linking function for the node.
  7980. *
  7981. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  7982. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7983. * scope argument is auto-generated to the new child of the transcluded parent scope.
  7984. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  7985. * the rootElement must be set the jqLite collection of the compile root. This is
  7986. * needed so that the jqLite collection items can be replaced with widgets.
  7987. * @param {number=} maxPriority Max directive priority.
  7988. * @returns {Function} A composite linking function of all of the matched directives or null.
  7989. */
  7990. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  7991. previousCompileContext) {
  7992. var linkFns = [],
  7993. // `nodeList` can be either an element's `.childNodes` (live NodeList)
  7994. // or a jqLite/jQuery collection or an array
  7995. notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),
  7996. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  7997. for (var i = 0; i < nodeList.length; i++) {
  7998. attrs = new Attributes();
  7999. // Support: IE 11 only
  8000. // Workaround for #11781 and #14924
  8001. if (msie === 11) {
  8002. mergeConsecutiveTextNodes(nodeList, i, notLiveList);
  8003. }
  8004. // We must always refer to `nodeList[i]` hereafter,
  8005. // since the nodes can be replaced underneath us.
  8006. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  8007. ignoreDirective);
  8008. nodeLinkFn = (directives.length)
  8009. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  8010. null, [], [], previousCompileContext)
  8011. : null;
  8012. if (nodeLinkFn && nodeLinkFn.scope) {
  8013. compile.$$addScopeClass(attrs.$$element);
  8014. }
  8015. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  8016. !(childNodes = nodeList[i].childNodes) ||
  8017. !childNodes.length)
  8018. ? null
  8019. : compileNodes(childNodes,
  8020. nodeLinkFn ? (
  8021. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  8022. && nodeLinkFn.transclude) : transcludeFn);
  8023. if (nodeLinkFn || childLinkFn) {
  8024. linkFns.push(i, nodeLinkFn, childLinkFn);
  8025. linkFnFound = true;
  8026. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  8027. }
  8028. //use the previous context only for the first element in the virtual group
  8029. previousCompileContext = null;
  8030. }
  8031. // return a linking function if we have found anything, null otherwise
  8032. return linkFnFound ? compositeLinkFn : null;
  8033. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  8034. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  8035. var stableNodeList;
  8036. if (nodeLinkFnFound) {
  8037. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  8038. // offsets don't get screwed up
  8039. var nodeListLength = nodeList.length;
  8040. stableNodeList = new Array(nodeListLength);
  8041. // create a sparse array by only copying the elements which have a linkFn
  8042. for (i = 0; i < linkFns.length; i += 3) {
  8043. idx = linkFns[i];
  8044. stableNodeList[idx] = nodeList[idx];
  8045. }
  8046. } else {
  8047. stableNodeList = nodeList;
  8048. }
  8049. for (i = 0, ii = linkFns.length; i < ii;) {
  8050. node = stableNodeList[linkFns[i++]];
  8051. nodeLinkFn = linkFns[i++];
  8052. childLinkFn = linkFns[i++];
  8053. if (nodeLinkFn) {
  8054. if (nodeLinkFn.scope) {
  8055. childScope = scope.$new();
  8056. compile.$$addScopeInfo(jqLite(node), childScope);
  8057. } else {
  8058. childScope = scope;
  8059. }
  8060. if (nodeLinkFn.transcludeOnThisElement) {
  8061. childBoundTranscludeFn = createBoundTranscludeFn(
  8062. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  8063. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  8064. childBoundTranscludeFn = parentBoundTranscludeFn;
  8065. } else if (!parentBoundTranscludeFn && transcludeFn) {
  8066. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  8067. } else {
  8068. childBoundTranscludeFn = null;
  8069. }
  8070. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  8071. } else if (childLinkFn) {
  8072. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  8073. }
  8074. }
  8075. }
  8076. }
  8077. function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {
  8078. var node = nodeList[idx];
  8079. var parent = node.parentNode;
  8080. var sibling;
  8081. if (node.nodeType !== NODE_TYPE_TEXT) {
  8082. return;
  8083. }
  8084. while (true) {
  8085. sibling = parent ? node.nextSibling : nodeList[idx + 1];
  8086. if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {
  8087. break;
  8088. }
  8089. node.nodeValue = node.nodeValue + sibling.nodeValue;
  8090. if (sibling.parentNode) {
  8091. sibling.parentNode.removeChild(sibling);
  8092. }
  8093. if (notLiveList && sibling === nodeList[idx + 1]) {
  8094. nodeList.splice(idx + 1, 1);
  8095. }
  8096. }
  8097. }
  8098. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  8099. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  8100. if (!transcludedScope) {
  8101. transcludedScope = scope.$new(false, containingScope);
  8102. transcludedScope.$$transcluded = true;
  8103. }
  8104. return transcludeFn(transcludedScope, cloneFn, {
  8105. parentBoundTranscludeFn: previousBoundTranscludeFn,
  8106. transcludeControllers: controllers,
  8107. futureParentElement: futureParentElement
  8108. });
  8109. }
  8110. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  8111. // so that they are available inside the `controllersBoundTransclude` function
  8112. var boundSlots = boundTranscludeFn.$$slots = createMap();
  8113. for (var slotName in transcludeFn.$$slots) {
  8114. if (transcludeFn.$$slots[slotName]) {
  8115. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  8116. } else {
  8117. boundSlots[slotName] = null;
  8118. }
  8119. }
  8120. return boundTranscludeFn;
  8121. }
  8122. /**
  8123. * Looks for directives on the given node and adds them to the directive collection which is
  8124. * sorted.
  8125. *
  8126. * @param node Node to search.
  8127. * @param directives An array to which the directives are added to. This array is sorted before
  8128. * the function returns.
  8129. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  8130. * @param {number=} maxPriority Max directive priority.
  8131. */
  8132. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8133. var nodeType = node.nodeType,
  8134. attrsMap = attrs.$attr,
  8135. match,
  8136. nodeName,
  8137. className;
  8138. switch (nodeType) {
  8139. case NODE_TYPE_ELEMENT: /* Element */
  8140. nodeName = nodeName_(node);
  8141. // use the node name: <directive>
  8142. addDirective(directives,
  8143. directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
  8144. // iterate over the attributes
  8145. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  8146. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  8147. var attrStartName = false;
  8148. var attrEndName = false;
  8149. attr = nAttrs[j];
  8150. name = attr.name;
  8151. value = attr.value;
  8152. // support ngAttr attribute binding
  8153. ngAttrName = directiveNormalize(name);
  8154. isNgAttr = NG_ATTR_BINDING.test(ngAttrName);
  8155. if (isNgAttr) {
  8156. name = name.replace(PREFIX_REGEXP, '')
  8157. .substr(8).replace(/_(.)/g, function(match, letter) {
  8158. return letter.toUpperCase();
  8159. });
  8160. }
  8161. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  8162. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  8163. attrStartName = name;
  8164. attrEndName = name.substr(0, name.length - 5) + 'end';
  8165. name = name.substr(0, name.length - 6);
  8166. }
  8167. nName = directiveNormalize(name.toLowerCase());
  8168. attrsMap[nName] = name;
  8169. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  8170. attrs[nName] = value;
  8171. if (getBooleanAttrName(node, nName)) {
  8172. attrs[nName] = true; // presence means true
  8173. }
  8174. }
  8175. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  8176. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  8177. attrEndName);
  8178. }
  8179. if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {
  8180. // Hidden input elements can have strange behaviour when navigating back to the page
  8181. // This tells the browser not to try to cache and reinstate previous values
  8182. node.setAttribute('autocomplete', 'off');
  8183. }
  8184. // use class as directive
  8185. if (!cssClassDirectivesEnabled) break;
  8186. className = node.className;
  8187. if (isObject(className)) {
  8188. // Maybe SVGAnimatedString
  8189. className = className.animVal;
  8190. }
  8191. if (isString(className) && className !== '') {
  8192. while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
  8193. nName = directiveNormalize(match[2]);
  8194. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  8195. attrs[nName] = trim(match[3]);
  8196. }
  8197. className = className.substr(match.index + match[0].length);
  8198. }
  8199. }
  8200. break;
  8201. case NODE_TYPE_TEXT: /* Text Node */
  8202. addTextInterpolateDirective(directives, node.nodeValue);
  8203. break;
  8204. case NODE_TYPE_COMMENT: /* Comment */
  8205. if (!commentDirectivesEnabled) break;
  8206. collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
  8207. break;
  8208. }
  8209. directives.sort(byPriority);
  8210. return directives;
  8211. }
  8212. function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8213. // function created because of performance, try/catch disables
  8214. // the optimization of the whole function #14848
  8215. try {
  8216. var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  8217. if (match) {
  8218. var nName = directiveNormalize(match[1]);
  8219. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  8220. attrs[nName] = trim(match[2]);
  8221. }
  8222. }
  8223. } catch (e) {
  8224. // turns out that under some circumstances IE9 throws errors when one attempts to read
  8225. // comment's node value.
  8226. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  8227. }
  8228. }
  8229. /**
  8230. * Given a node with a directive-start it collects all of the siblings until it finds
  8231. * directive-end.
  8232. * @param node
  8233. * @param attrStart
  8234. * @param attrEnd
  8235. * @returns {*}
  8236. */
  8237. function groupScan(node, attrStart, attrEnd) {
  8238. var nodes = [];
  8239. var depth = 0;
  8240. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  8241. do {
  8242. if (!node) {
  8243. throw $compileMinErr('uterdir',
  8244. 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
  8245. attrStart, attrEnd);
  8246. }
  8247. if (node.nodeType === NODE_TYPE_ELEMENT) {
  8248. if (node.hasAttribute(attrStart)) depth++;
  8249. if (node.hasAttribute(attrEnd)) depth--;
  8250. }
  8251. nodes.push(node);
  8252. node = node.nextSibling;
  8253. } while (depth > 0);
  8254. } else {
  8255. nodes.push(node);
  8256. }
  8257. return jqLite(nodes);
  8258. }
  8259. /**
  8260. * Wrapper for linking function which converts normal linking function into a grouped
  8261. * linking function.
  8262. * @param linkFn
  8263. * @param attrStart
  8264. * @param attrEnd
  8265. * @returns {Function}
  8266. */
  8267. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  8268. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  8269. element = groupScan(element[0], attrStart, attrEnd);
  8270. return linkFn(scope, element, attrs, controllers, transcludeFn);
  8271. };
  8272. }
  8273. /**
  8274. * A function generator that is used to support both eager and lazy compilation
  8275. * linking function.
  8276. * @param eager
  8277. * @param $compileNodes
  8278. * @param transcludeFn
  8279. * @param maxPriority
  8280. * @param ignoreDirective
  8281. * @param previousCompileContext
  8282. * @returns {Function}
  8283. */
  8284. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  8285. var compiled;
  8286. if (eager) {
  8287. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8288. }
  8289. return /** @this */ function lazyCompilation() {
  8290. if (!compiled) {
  8291. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8292. // Null out all of these references in order to make them eligible for garbage collection
  8293. // since this is a potentially long lived closure
  8294. $compileNodes = transcludeFn = previousCompileContext = null;
  8295. }
  8296. return compiled.apply(this, arguments);
  8297. };
  8298. }
  8299. /**
  8300. * Once the directives have been collected, their compile functions are executed. This method
  8301. * is responsible for inlining directive templates as well as terminating the application
  8302. * of the directives if the terminal directive has been reached.
  8303. *
  8304. * @param {Array} directives Array of collected directives to execute their compile function.
  8305. * this needs to be pre-sorted by priority order.
  8306. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  8307. * @param {Object} templateAttrs The shared attribute function
  8308. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8309. * scope argument is auto-generated to the new
  8310. * child of the transcluded parent scope.
  8311. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  8312. * argument has the root jqLite array so that we can replace nodes
  8313. * on it.
  8314. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  8315. * compiling the transclusion.
  8316. * @param {Array.<Function>} preLinkFns
  8317. * @param {Array.<Function>} postLinkFns
  8318. * @param {Object} previousCompileContext Context used for previous compilation of the current
  8319. * node
  8320. * @returns {Function} linkFn
  8321. */
  8322. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  8323. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  8324. previousCompileContext) {
  8325. previousCompileContext = previousCompileContext || {};
  8326. var terminalPriority = -Number.MAX_VALUE,
  8327. newScopeDirective = previousCompileContext.newScopeDirective,
  8328. controllerDirectives = previousCompileContext.controllerDirectives,
  8329. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  8330. templateDirective = previousCompileContext.templateDirective,
  8331. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  8332. hasTranscludeDirective = false,
  8333. hasTemplate = false,
  8334. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  8335. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  8336. directive,
  8337. directiveName,
  8338. $template,
  8339. replaceDirective = originalReplaceDirective,
  8340. childTranscludeFn = transcludeFn,
  8341. linkFn,
  8342. didScanForMultipleTransclusion = false,
  8343. mightHaveMultipleTransclusionError = false,
  8344. directiveValue;
  8345. // executes all directives on the current element
  8346. for (var i = 0, ii = directives.length; i < ii; i++) {
  8347. directive = directives[i];
  8348. var attrStart = directive.$$start;
  8349. var attrEnd = directive.$$end;
  8350. // collect multiblock sections
  8351. if (attrStart) {
  8352. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  8353. }
  8354. $template = undefined;
  8355. if (terminalPriority > directive.priority) {
  8356. break; // prevent further processing of directives
  8357. }
  8358. directiveValue = directive.scope;
  8359. if (directiveValue) {
  8360. // skip the check for directives with async templates, we'll check the derived sync
  8361. // directive when the template arrives
  8362. if (!directive.templateUrl) {
  8363. if (isObject(directiveValue)) {
  8364. // This directive is trying to add an isolated scope.
  8365. // Check that there is no scope of any kind already
  8366. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  8367. directive, $compileNode);
  8368. newIsolateScopeDirective = directive;
  8369. } else {
  8370. // This directive is trying to add a child scope.
  8371. // Check that there is no isolated scope already
  8372. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  8373. $compileNode);
  8374. }
  8375. }
  8376. newScopeDirective = newScopeDirective || directive;
  8377. }
  8378. directiveName = directive.name;
  8379. // If we encounter a condition that can result in transclusion on the directive,
  8380. // then scan ahead in the remaining directives for others that may cause a multiple
  8381. // transclusion error to be thrown during the compilation process. If a matching directive
  8382. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  8383. // compile the `transclude` function rather than doing it lazily in order to throw
  8384. // exceptions at the correct time
  8385. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  8386. || (directive.transclude && !directive.$$tlb))) {
  8387. var candidateDirective;
  8388. for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
  8389. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  8390. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  8391. mightHaveMultipleTransclusionError = true;
  8392. break;
  8393. }
  8394. }
  8395. didScanForMultipleTransclusion = true;
  8396. }
  8397. if (!directive.templateUrl && directive.controller) {
  8398. controllerDirectives = controllerDirectives || createMap();
  8399. assertNoDuplicate('\'' + directiveName + '\' controller',
  8400. controllerDirectives[directiveName], directive, $compileNode);
  8401. controllerDirectives[directiveName] = directive;
  8402. }
  8403. directiveValue = directive.transclude;
  8404. if (directiveValue) {
  8405. hasTranscludeDirective = true;
  8406. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  8407. // This option should only be used by directives that know how to safely handle element transclusion,
  8408. // where the transcluded nodes are added or replaced after linking.
  8409. if (!directive.$$tlb) {
  8410. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  8411. nonTlbTranscludeDirective = directive;
  8412. }
  8413. if (directiveValue === 'element') {
  8414. hasElementTranscludeDirective = true;
  8415. terminalPriority = directive.priority;
  8416. $template = $compileNode;
  8417. $compileNode = templateAttrs.$$element =
  8418. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  8419. compileNode = $compileNode[0];
  8420. replaceWith(jqCollection, sliceArgs($template), compileNode);
  8421. // Support: Chrome < 50
  8422. // https://github.com/angular/angular.js/issues/14041
  8423. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  8424. // in the `replaceWith` function is improperly garbage collected despite still
  8425. // being referenced by the `parentNode` property of all of the child nodes. By adding
  8426. // a reference to the fragment via a different property, we can avoid that incorrect
  8427. // behavior.
  8428. // TODO: remove this line after Chrome 50 has been released
  8429. $template[0].$$parentNode = $template[0].parentNode;
  8430. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  8431. replaceDirective && replaceDirective.name, {
  8432. // Don't pass in:
  8433. // - controllerDirectives - otherwise we'll create duplicates controllers
  8434. // - newIsolateScopeDirective or templateDirective - combining templates with
  8435. // element transclusion doesn't make sense.
  8436. //
  8437. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  8438. // on the same element more than once.
  8439. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8440. });
  8441. } else {
  8442. var slots = createMap();
  8443. if (!isObject(directiveValue)) {
  8444. $template = jqLite(jqLiteClone(compileNode)).contents();
  8445. } else {
  8446. // We have transclusion slots,
  8447. // collect them up, compile them and store their transclusion functions
  8448. $template = [];
  8449. var slotMap = createMap();
  8450. var filledSlots = createMap();
  8451. // Parse the element selectors
  8452. forEach(directiveValue, function(elementSelector, slotName) {
  8453. // If an element selector starts with a ? then it is optional
  8454. var optional = (elementSelector.charAt(0) === '?');
  8455. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  8456. slotMap[elementSelector] = slotName;
  8457. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  8458. // Later when calling boundTransclusion functions with a slot name we only error if the
  8459. // slot is `undefined`
  8460. slots[slotName] = null;
  8461. // filledSlots contains `true` for all slots that are either optional or have been
  8462. // filled. This is used to check that we have not missed any required slots
  8463. filledSlots[slotName] = optional;
  8464. });
  8465. // Add the matching elements into their slot
  8466. forEach($compileNode.contents(), function(node) {
  8467. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  8468. if (slotName) {
  8469. filledSlots[slotName] = true;
  8470. slots[slotName] = slots[slotName] || [];
  8471. slots[slotName].push(node);
  8472. } else {
  8473. $template.push(node);
  8474. }
  8475. });
  8476. // Check for required slots that were not filled
  8477. forEach(filledSlots, function(filled, slotName) {
  8478. if (!filled) {
  8479. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  8480. }
  8481. });
  8482. for (var slotName in slots) {
  8483. if (slots[slotName]) {
  8484. // Only define a transclusion function if the slot was filled
  8485. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  8486. }
  8487. }
  8488. }
  8489. $compileNode.empty(); // clear contents
  8490. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  8491. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  8492. childTranscludeFn.$$slots = slots;
  8493. }
  8494. }
  8495. if (directive.template) {
  8496. hasTemplate = true;
  8497. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8498. templateDirective = directive;
  8499. directiveValue = (isFunction(directive.template))
  8500. ? directive.template($compileNode, templateAttrs)
  8501. : directive.template;
  8502. directiveValue = denormalizeTemplate(directiveValue);
  8503. if (directive.replace) {
  8504. replaceDirective = directive;
  8505. if (jqLiteIsTextNode(directiveValue)) {
  8506. $template = [];
  8507. } else {
  8508. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  8509. }
  8510. compileNode = $template[0];
  8511. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8512. throw $compileMinErr('tplrt',
  8513. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  8514. directiveName, '');
  8515. }
  8516. replaceWith(jqCollection, $compileNode, compileNode);
  8517. var newTemplateAttrs = {$attr: {}};
  8518. // combine directives from the original node and from the template:
  8519. // - take the array of directives for this element
  8520. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  8521. // - collect directives from the template and sort them by priority
  8522. // - combine directives as: processed + template + unprocessed
  8523. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  8524. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  8525. if (newIsolateScopeDirective || newScopeDirective) {
  8526. // The original directive caused the current element to be replaced but this element
  8527. // also needs to have a new scope, so we need to tell the template directives
  8528. // that they would need to get their scope from further up, if they require transclusion
  8529. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  8530. }
  8531. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  8532. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  8533. ii = directives.length;
  8534. } else {
  8535. $compileNode.html(directiveValue);
  8536. }
  8537. }
  8538. if (directive.templateUrl) {
  8539. hasTemplate = true;
  8540. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8541. templateDirective = directive;
  8542. if (directive.replace) {
  8543. replaceDirective = directive;
  8544. }
  8545. // eslint-disable-next-line no-func-assign
  8546. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  8547. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  8548. controllerDirectives: controllerDirectives,
  8549. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  8550. newIsolateScopeDirective: newIsolateScopeDirective,
  8551. templateDirective: templateDirective,
  8552. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8553. });
  8554. ii = directives.length;
  8555. } else if (directive.compile) {
  8556. try {
  8557. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  8558. var context = directive.$$originalDirective || directive;
  8559. if (isFunction(linkFn)) {
  8560. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  8561. } else if (linkFn) {
  8562. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  8563. }
  8564. } catch (e) {
  8565. $exceptionHandler(e, startingTag($compileNode));
  8566. }
  8567. }
  8568. if (directive.terminal) {
  8569. nodeLinkFn.terminal = true;
  8570. terminalPriority = Math.max(terminalPriority, directive.priority);
  8571. }
  8572. }
  8573. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  8574. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  8575. nodeLinkFn.templateOnThisElement = hasTemplate;
  8576. nodeLinkFn.transclude = childTranscludeFn;
  8577. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  8578. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  8579. return nodeLinkFn;
  8580. ////////////////////
  8581. function addLinkFns(pre, post, attrStart, attrEnd) {
  8582. if (pre) {
  8583. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  8584. pre.require = directive.require;
  8585. pre.directiveName = directiveName;
  8586. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8587. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  8588. }
  8589. preLinkFns.push(pre);
  8590. }
  8591. if (post) {
  8592. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  8593. post.require = directive.require;
  8594. post.directiveName = directiveName;
  8595. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8596. post = cloneAndAnnotateFn(post, {isolateScope: true});
  8597. }
  8598. postLinkFns.push(post);
  8599. }
  8600. }
  8601. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8602. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8603. attrs, scopeBindingInfo;
  8604. if (compileNode === linkNode) {
  8605. attrs = templateAttrs;
  8606. $element = templateAttrs.$$element;
  8607. } else {
  8608. $element = jqLite(linkNode);
  8609. attrs = new Attributes($element, templateAttrs);
  8610. }
  8611. controllerScope = scope;
  8612. if (newIsolateScopeDirective) {
  8613. isolateScope = scope.$new(true);
  8614. } else if (newScopeDirective) {
  8615. controllerScope = scope.$parent;
  8616. }
  8617. if (boundTranscludeFn) {
  8618. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8619. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8620. transcludeFn = controllersBoundTransclude;
  8621. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8622. // expose the slots on the `$transclude` function
  8623. transcludeFn.isSlotFilled = function(slotName) {
  8624. return !!boundTranscludeFn.$$slots[slotName];
  8625. };
  8626. }
  8627. if (controllerDirectives) {
  8628. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  8629. }
  8630. if (newIsolateScopeDirective) {
  8631. // Initialize isolate scope bindings for new isolate scope directive.
  8632. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8633. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8634. compile.$$addScopeClass($element, true);
  8635. isolateScope.$$isolateBindings =
  8636. newIsolateScopeDirective.$$isolateBindings;
  8637. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  8638. isolateScope.$$isolateBindings,
  8639. newIsolateScopeDirective);
  8640. if (scopeBindingInfo.removeWatches) {
  8641. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  8642. }
  8643. }
  8644. // Initialize bindToController bindings
  8645. for (var name in elementControllers) {
  8646. var controllerDirective = controllerDirectives[name];
  8647. var controller = elementControllers[name];
  8648. var bindings = controllerDirective.$$bindings.bindToController;
  8649. if (preAssignBindingsEnabled) {
  8650. if (bindings) {
  8651. controller.bindingInfo =
  8652. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8653. } else {
  8654. controller.bindingInfo = {};
  8655. }
  8656. var controllerResult = controller();
  8657. if (controllerResult !== controller.instance) {
  8658. // If the controller constructor has a return value, overwrite the instance
  8659. // from setupControllers
  8660. controller.instance = controllerResult;
  8661. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8662. if (controller.bindingInfo.removeWatches) {
  8663. controller.bindingInfo.removeWatches();
  8664. }
  8665. controller.bindingInfo =
  8666. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8667. }
  8668. } else {
  8669. controller.instance = controller();
  8670. $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
  8671. controller.bindingInfo =
  8672. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8673. }
  8674. }
  8675. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  8676. forEach(controllerDirectives, function(controllerDirective, name) {
  8677. var require = controllerDirective.require;
  8678. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  8679. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  8680. }
  8681. });
  8682. // Handle the init and destroy lifecycle hooks on all controllers that have them
  8683. forEach(elementControllers, function(controller) {
  8684. var controllerInstance = controller.instance;
  8685. if (isFunction(controllerInstance.$onChanges)) {
  8686. try {
  8687. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  8688. } catch (e) {
  8689. $exceptionHandler(e);
  8690. }
  8691. }
  8692. if (isFunction(controllerInstance.$onInit)) {
  8693. try {
  8694. controllerInstance.$onInit();
  8695. } catch (e) {
  8696. $exceptionHandler(e);
  8697. }
  8698. }
  8699. if (isFunction(controllerInstance.$doCheck)) {
  8700. controllerScope.$watch(function() { controllerInstance.$doCheck(); });
  8701. controllerInstance.$doCheck();
  8702. }
  8703. if (isFunction(controllerInstance.$onDestroy)) {
  8704. controllerScope.$on('$destroy', function callOnDestroyHook() {
  8705. controllerInstance.$onDestroy();
  8706. });
  8707. }
  8708. });
  8709. // PRELINKING
  8710. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  8711. linkFn = preLinkFns[i];
  8712. invokeLinkFn(linkFn,
  8713. linkFn.isolateScope ? isolateScope : scope,
  8714. $element,
  8715. attrs,
  8716. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8717. transcludeFn
  8718. );
  8719. }
  8720. // RECURSION
  8721. // We only pass the isolate scope, if the isolate directive has a template,
  8722. // otherwise the child elements do not belong to the isolate directive.
  8723. var scopeToChild = scope;
  8724. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  8725. scopeToChild = isolateScope;
  8726. }
  8727. if (childLinkFn) {
  8728. childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  8729. }
  8730. // POSTLINKING
  8731. for (i = postLinkFns.length - 1; i >= 0; i--) {
  8732. linkFn = postLinkFns[i];
  8733. invokeLinkFn(linkFn,
  8734. linkFn.isolateScope ? isolateScope : scope,
  8735. $element,
  8736. attrs,
  8737. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8738. transcludeFn
  8739. );
  8740. }
  8741. // Trigger $postLink lifecycle hooks
  8742. forEach(elementControllers, function(controller) {
  8743. var controllerInstance = controller.instance;
  8744. if (isFunction(controllerInstance.$postLink)) {
  8745. controllerInstance.$postLink();
  8746. }
  8747. });
  8748. // This is the function that is injected as `$transclude`.
  8749. // Note: all arguments are optional!
  8750. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  8751. var transcludeControllers;
  8752. // No scope passed in:
  8753. if (!isScope(scope)) {
  8754. slotName = futureParentElement;
  8755. futureParentElement = cloneAttachFn;
  8756. cloneAttachFn = scope;
  8757. scope = undefined;
  8758. }
  8759. if (hasElementTranscludeDirective) {
  8760. transcludeControllers = elementControllers;
  8761. }
  8762. if (!futureParentElement) {
  8763. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  8764. }
  8765. if (slotName) {
  8766. // slotTranscludeFn can be one of three things:
  8767. // * a transclude function - a filled slot
  8768. // * `null` - an optional slot that was not filled
  8769. // * `undefined` - a slot that was not declared (i.e. invalid)
  8770. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  8771. if (slotTranscludeFn) {
  8772. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8773. } else if (isUndefined(slotTranscludeFn)) {
  8774. throw $compileMinErr('noslot',
  8775. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  8776. 'Element: {1}',
  8777. slotName, startingTag($element));
  8778. }
  8779. } else {
  8780. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8781. }
  8782. }
  8783. }
  8784. }
  8785. function getControllers(directiveName, require, $element, elementControllers) {
  8786. var value;
  8787. if (isString(require)) {
  8788. var match = require.match(REQUIRE_PREFIX_REGEXP);
  8789. var name = require.substring(match[0].length);
  8790. var inheritType = match[1] || match[3];
  8791. var optional = match[2] === '?';
  8792. //If only parents then start at the parent element
  8793. if (inheritType === '^^') {
  8794. $element = $element.parent();
  8795. //Otherwise attempt getting the controller from elementControllers in case
  8796. //the element is transcluded (and has no data) and to avoid .data if possible
  8797. } else {
  8798. value = elementControllers && elementControllers[name];
  8799. value = value && value.instance;
  8800. }
  8801. if (!value) {
  8802. var dataName = '$' + name + 'Controller';
  8803. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  8804. }
  8805. if (!value && !optional) {
  8806. throw $compileMinErr('ctreq',
  8807. 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
  8808. name, directiveName);
  8809. }
  8810. } else if (isArray(require)) {
  8811. value = [];
  8812. for (var i = 0, ii = require.length; i < ii; i++) {
  8813. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  8814. }
  8815. } else if (isObject(require)) {
  8816. value = {};
  8817. forEach(require, function(controller, property) {
  8818. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  8819. });
  8820. }
  8821. return value || null;
  8822. }
  8823. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  8824. var elementControllers = createMap();
  8825. for (var controllerKey in controllerDirectives) {
  8826. var directive = controllerDirectives[controllerKey];
  8827. var locals = {
  8828. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  8829. $element: $element,
  8830. $attrs: attrs,
  8831. $transclude: transcludeFn
  8832. };
  8833. var controller = directive.controller;
  8834. if (controller === '@') {
  8835. controller = attrs[directive.name];
  8836. }
  8837. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  8838. // For directives with element transclusion the element is a comment.
  8839. // In this case .data will not attach any data.
  8840. // Instead, we save the controllers for the element in a local hash and attach to .data
  8841. // later, once we have the actual element.
  8842. elementControllers[directive.name] = controllerInstance;
  8843. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  8844. }
  8845. return elementControllers;
  8846. }
  8847. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  8848. // or child scope created. For instance:
  8849. // * if the directive has been pulled into a template because another directive with a higher priority
  8850. // asked for element transclusion
  8851. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  8852. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  8853. function markDirectiveScope(directives, isolateScope, newScope) {
  8854. for (var j = 0, jj = directives.length; j < jj; j++) {
  8855. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  8856. }
  8857. }
  8858. /**
  8859. * looks up the directive and decorates it with exception handling and proper parameters. We
  8860. * call this the boundDirective.
  8861. *
  8862. * @param {string} name name of the directive to look up.
  8863. * @param {string} location The directive must be found in specific format.
  8864. * String containing any of theses characters:
  8865. *
  8866. * * `E`: element name
  8867. * * `A': attribute
  8868. * * `C`: class
  8869. * * `M`: comment
  8870. * @returns {boolean} true if directive was added.
  8871. */
  8872. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  8873. endAttrName) {
  8874. if (name === ignoreDirective) return null;
  8875. var match = null;
  8876. if (hasDirectives.hasOwnProperty(name)) {
  8877. for (var directive, directives = $injector.get(name + Suffix),
  8878. i = 0, ii = directives.length; i < ii; i++) {
  8879. directive = directives[i];
  8880. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  8881. directive.restrict.indexOf(location) !== -1) {
  8882. if (startAttrName) {
  8883. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  8884. }
  8885. if (!directive.$$bindings) {
  8886. var bindings = directive.$$bindings =
  8887. parseDirectiveBindings(directive, directive.name);
  8888. if (isObject(bindings.isolateScope)) {
  8889. directive.$$isolateBindings = bindings.isolateScope;
  8890. }
  8891. }
  8892. tDirectives.push(directive);
  8893. match = directive;
  8894. }
  8895. }
  8896. }
  8897. return match;
  8898. }
  8899. /**
  8900. * looks up the directive and returns true if it is a multi-element directive,
  8901. * and therefore requires DOM nodes between -start and -end markers to be grouped
  8902. * together.
  8903. *
  8904. * @param {string} name name of the directive to look up.
  8905. * @returns true if directive was registered as multi-element.
  8906. */
  8907. function directiveIsMultiElement(name) {
  8908. if (hasDirectives.hasOwnProperty(name)) {
  8909. for (var directive, directives = $injector.get(name + Suffix),
  8910. i = 0, ii = directives.length; i < ii; i++) {
  8911. directive = directives[i];
  8912. if (directive.multiElement) {
  8913. return true;
  8914. }
  8915. }
  8916. }
  8917. return false;
  8918. }
  8919. /**
  8920. * When the element is replaced with HTML template then the new attributes
  8921. * on the template need to be merged with the existing attributes in the DOM.
  8922. * The desired effect is to have both of the attributes present.
  8923. *
  8924. * @param {object} dst destination attributes (original DOM)
  8925. * @param {object} src source attributes (from the directive template)
  8926. */
  8927. function mergeTemplateAttributes(dst, src) {
  8928. var srcAttr = src.$attr,
  8929. dstAttr = dst.$attr;
  8930. // reapply the old attributes to the new element
  8931. forEach(dst, function(value, key) {
  8932. if (key.charAt(0) !== '$') {
  8933. if (src[key] && src[key] !== value) {
  8934. if (value.length) {
  8935. value += (key === 'style' ? ';' : ' ') + src[key];
  8936. } else {
  8937. value = src[key];
  8938. }
  8939. }
  8940. dst.$set(key, value, true, srcAttr[key]);
  8941. }
  8942. });
  8943. // copy the new attributes on the old attrs object
  8944. forEach(src, function(value, key) {
  8945. // Check if we already set this attribute in the loop above.
  8946. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  8947. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  8948. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  8949. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  8950. dst[key] = value;
  8951. if (key !== 'class' && key !== 'style') {
  8952. dstAttr[key] = srcAttr[key];
  8953. }
  8954. }
  8955. });
  8956. }
  8957. function compileTemplateUrl(directives, $compileNode, tAttrs,
  8958. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  8959. var linkQueue = [],
  8960. afterTemplateNodeLinkFn,
  8961. afterTemplateChildLinkFn,
  8962. beforeTemplateCompileNode = $compileNode[0],
  8963. origAsyncDirective = directives.shift(),
  8964. derivedSyncDirective = inherit(origAsyncDirective, {
  8965. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  8966. }),
  8967. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  8968. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  8969. : origAsyncDirective.templateUrl,
  8970. templateNamespace = origAsyncDirective.templateNamespace;
  8971. $compileNode.empty();
  8972. $templateRequest(templateUrl)
  8973. .then(function(content) {
  8974. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  8975. content = denormalizeTemplate(content);
  8976. if (origAsyncDirective.replace) {
  8977. if (jqLiteIsTextNode(content)) {
  8978. $template = [];
  8979. } else {
  8980. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  8981. }
  8982. compileNode = $template[0];
  8983. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8984. throw $compileMinErr('tplrt',
  8985. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  8986. origAsyncDirective.name, templateUrl);
  8987. }
  8988. tempTemplateAttrs = {$attr: {}};
  8989. replaceWith($rootElement, $compileNode, compileNode);
  8990. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  8991. if (isObject(origAsyncDirective.scope)) {
  8992. // the original directive that caused the template to be loaded async required
  8993. // an isolate scope
  8994. markDirectiveScope(templateDirectives, true);
  8995. }
  8996. directives = templateDirectives.concat(directives);
  8997. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  8998. } else {
  8999. compileNode = beforeTemplateCompileNode;
  9000. $compileNode.html(content);
  9001. }
  9002. directives.unshift(derivedSyncDirective);
  9003. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  9004. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  9005. previousCompileContext);
  9006. forEach($rootElement, function(node, i) {
  9007. if (node === compileNode) {
  9008. $rootElement[i] = $compileNode[0];
  9009. }
  9010. });
  9011. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  9012. while (linkQueue.length) {
  9013. var scope = linkQueue.shift(),
  9014. beforeTemplateLinkNode = linkQueue.shift(),
  9015. linkRootElement = linkQueue.shift(),
  9016. boundTranscludeFn = linkQueue.shift(),
  9017. linkNode = $compileNode[0];
  9018. if (scope.$$destroyed) continue;
  9019. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  9020. var oldClasses = beforeTemplateLinkNode.className;
  9021. if (!(previousCompileContext.hasElementTranscludeDirective &&
  9022. origAsyncDirective.replace)) {
  9023. // it was cloned therefore we have to clone as well.
  9024. linkNode = jqLiteClone(compileNode);
  9025. }
  9026. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  9027. // Copy in CSS classes from original node
  9028. safeAddClass(jqLite(linkNode), oldClasses);
  9029. }
  9030. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9031. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9032. } else {
  9033. childBoundTranscludeFn = boundTranscludeFn;
  9034. }
  9035. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  9036. childBoundTranscludeFn);
  9037. }
  9038. linkQueue = null;
  9039. }).catch(function(error) {
  9040. if (error instanceof Error) {
  9041. $exceptionHandler(error);
  9042. }
  9043. });
  9044. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  9045. var childBoundTranscludeFn = boundTranscludeFn;
  9046. if (scope.$$destroyed) return;
  9047. if (linkQueue) {
  9048. linkQueue.push(scope,
  9049. node,
  9050. rootElement,
  9051. childBoundTranscludeFn);
  9052. } else {
  9053. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9054. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9055. }
  9056. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  9057. }
  9058. };
  9059. }
  9060. /**
  9061. * Sorting function for bound directives.
  9062. */
  9063. function byPriority(a, b) {
  9064. var diff = b.priority - a.priority;
  9065. if (diff !== 0) return diff;
  9066. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  9067. return a.index - b.index;
  9068. }
  9069. function assertNoDuplicate(what, previousDirective, directive, element) {
  9070. function wrapModuleNameIfDefined(moduleName) {
  9071. return moduleName ?
  9072. (' (module: ' + moduleName + ')') :
  9073. '';
  9074. }
  9075. if (previousDirective) {
  9076. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  9077. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  9078. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  9079. }
  9080. }
  9081. function addTextInterpolateDirective(directives, text) {
  9082. var interpolateFn = $interpolate(text, true);
  9083. if (interpolateFn) {
  9084. directives.push({
  9085. priority: 0,
  9086. compile: function textInterpolateCompileFn(templateNode) {
  9087. var templateNodeParent = templateNode.parent(),
  9088. hasCompileParent = !!templateNodeParent.length;
  9089. // When transcluding a template that has bindings in the root
  9090. // we don't have a parent and thus need to add the class during linking fn.
  9091. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  9092. return function textInterpolateLinkFn(scope, node) {
  9093. var parent = node.parent();
  9094. if (!hasCompileParent) compile.$$addBindingClass(parent);
  9095. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  9096. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  9097. node[0].nodeValue = value;
  9098. });
  9099. };
  9100. }
  9101. });
  9102. }
  9103. }
  9104. function wrapTemplate(type, template) {
  9105. type = lowercase(type || 'html');
  9106. switch (type) {
  9107. case 'svg':
  9108. case 'math':
  9109. var wrapper = window.document.createElement('div');
  9110. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  9111. return wrapper.childNodes[0].childNodes;
  9112. default:
  9113. return template;
  9114. }
  9115. }
  9116. function getTrustedContext(node, attrNormalizedName) {
  9117. if (attrNormalizedName === 'srcdoc') {
  9118. return $sce.HTML;
  9119. }
  9120. var tag = nodeName_(node);
  9121. // All tags with src attributes require a RESOURCE_URL value, except for
  9122. // img and various html5 media tags.
  9123. if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
  9124. if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) {
  9125. return $sce.RESOURCE_URL;
  9126. }
  9127. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  9128. } else if (attrNormalizedName === 'xlinkHref' ||
  9129. (tag === 'form' && attrNormalizedName === 'action') ||
  9130. // links can be stylesheets or imports, which can run script in the current origin
  9131. (tag === 'link' && attrNormalizedName === 'href')
  9132. ) {
  9133. return $sce.RESOURCE_URL;
  9134. }
  9135. }
  9136. function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {
  9137. var trustedContext = getTrustedContext(node, name);
  9138. var mustHaveExpression = !isNgAttr;
  9139. var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;
  9140. var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
  9141. // no interpolation found -> ignore
  9142. if (!interpolateFn) return;
  9143. if (name === 'multiple' && nodeName_(node) === 'select') {
  9144. throw $compileMinErr('selmulti',
  9145. 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
  9146. startingTag(node));
  9147. }
  9148. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  9149. throw $compileMinErr('nodomevents',
  9150. 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' +
  9151. 'ng- versions (such as ng-click instead of onclick) instead.');
  9152. }
  9153. directives.push({
  9154. priority: 100,
  9155. compile: function() {
  9156. return {
  9157. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  9158. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  9159. // If the attribute has changed since last $interpolate()ed
  9160. var newValue = attr[name];
  9161. if (newValue !== value) {
  9162. // we need to interpolate again since the attribute value has been updated
  9163. // (e.g. by another directive's compile function)
  9164. // ensure unset/empty values make interpolateFn falsy
  9165. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  9166. value = newValue;
  9167. }
  9168. // if attribute was updated so that there is no interpolation going on we don't want to
  9169. // register any observers
  9170. if (!interpolateFn) return;
  9171. // initialize attr object so that it's ready in case we need the value for isolate
  9172. // scope initialization, otherwise the value would not be available from isolate
  9173. // directive's linking fn during linking phase
  9174. attr[name] = interpolateFn(scope);
  9175. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  9176. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  9177. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  9178. //special case for class attribute addition + removal
  9179. //so that class changes can tap into the animation
  9180. //hooks provided by the $animate service. Be sure to
  9181. //skip animations when the first digest occurs (when
  9182. //both the new and the old values are the same) since
  9183. //the CSS classes are the non-interpolated values
  9184. if (name === 'class' && newValue !== oldValue) {
  9185. attr.$updateClass(newValue, oldValue);
  9186. } else {
  9187. attr.$set(name, newValue);
  9188. }
  9189. });
  9190. }
  9191. };
  9192. }
  9193. });
  9194. }
  9195. /**
  9196. * This is a special jqLite.replaceWith, which can replace items which
  9197. * have no parents, provided that the containing jqLite collection is provided.
  9198. *
  9199. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  9200. * in the root of the tree.
  9201. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  9202. * the shell, but replace its DOM node reference.
  9203. * @param {Node} newNode The new DOM node.
  9204. */
  9205. function replaceWith($rootElement, elementsToRemove, newNode) {
  9206. var firstElementToRemove = elementsToRemove[0],
  9207. removeCount = elementsToRemove.length,
  9208. parent = firstElementToRemove.parentNode,
  9209. i, ii;
  9210. if ($rootElement) {
  9211. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  9212. if ($rootElement[i] === firstElementToRemove) {
  9213. $rootElement[i++] = newNode;
  9214. for (var j = i, j2 = j + removeCount - 1,
  9215. jj = $rootElement.length;
  9216. j < jj; j++, j2++) {
  9217. if (j2 < jj) {
  9218. $rootElement[j] = $rootElement[j2];
  9219. } else {
  9220. delete $rootElement[j];
  9221. }
  9222. }
  9223. $rootElement.length -= removeCount - 1;
  9224. // If the replaced element is also the jQuery .context then replace it
  9225. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  9226. // http://api.jquery.com/context/
  9227. if ($rootElement.context === firstElementToRemove) {
  9228. $rootElement.context = newNode;
  9229. }
  9230. break;
  9231. }
  9232. }
  9233. }
  9234. if (parent) {
  9235. parent.replaceChild(newNode, firstElementToRemove);
  9236. }
  9237. // Append all the `elementsToRemove` to a fragment. This will...
  9238. // - remove them from the DOM
  9239. // - allow them to still be traversed with .nextSibling
  9240. // - allow a single fragment.qSA to fetch all elements being removed
  9241. var fragment = window.document.createDocumentFragment();
  9242. for (i = 0; i < removeCount; i++) {
  9243. fragment.appendChild(elementsToRemove[i]);
  9244. }
  9245. if (jqLite.hasData(firstElementToRemove)) {
  9246. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  9247. // data here because there's no public interface in jQuery to do that and copying over
  9248. // event listeners (which is the main use of private data) wouldn't work anyway.
  9249. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  9250. // Remove $destroy event listeners from `firstElementToRemove`
  9251. jqLite(firstElementToRemove).off('$destroy');
  9252. }
  9253. // Cleanup any data/listeners on the elements and children.
  9254. // This includes invoking the $destroy event on any elements with listeners.
  9255. jqLite.cleanData(fragment.querySelectorAll('*'));
  9256. // Update the jqLite collection to only contain the `newNode`
  9257. for (i = 1; i < removeCount; i++) {
  9258. delete elementsToRemove[i];
  9259. }
  9260. elementsToRemove[0] = newNode;
  9261. elementsToRemove.length = 1;
  9262. }
  9263. function cloneAndAnnotateFn(fn, annotation) {
  9264. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  9265. }
  9266. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  9267. try {
  9268. linkFn(scope, $element, attrs, controllers, transcludeFn);
  9269. } catch (e) {
  9270. $exceptionHandler(e, startingTag($element));
  9271. }
  9272. }
  9273. // Set up $watches for isolate scope and controller bindings.
  9274. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  9275. var removeWatchCollection = [];
  9276. var initialChanges = {};
  9277. var changes;
  9278. forEach(bindings, function initializeBinding(definition, scopeName) {
  9279. var attrName = definition.attrName,
  9280. optional = definition.optional,
  9281. mode = definition.mode, // @, =, <, or &
  9282. lastValue,
  9283. parentGet, parentSet, compare, removeWatch;
  9284. switch (mode) {
  9285. case '@':
  9286. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  9287. destination[scopeName] = attrs[attrName] = undefined;
  9288. }
  9289. removeWatch = attrs.$observe(attrName, function(value) {
  9290. if (isString(value) || isBoolean(value)) {
  9291. var oldValue = destination[scopeName];
  9292. recordChanges(scopeName, value, oldValue);
  9293. destination[scopeName] = value;
  9294. }
  9295. });
  9296. attrs.$$observers[attrName].$$scope = scope;
  9297. lastValue = attrs[attrName];
  9298. if (isString(lastValue)) {
  9299. // If the attribute has been provided then we trigger an interpolation to ensure
  9300. // the value is there for use in the link fn
  9301. destination[scopeName] = $interpolate(lastValue)(scope);
  9302. } else if (isBoolean(lastValue)) {
  9303. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  9304. // the value to boolean rather than a string, so we special case this situation
  9305. destination[scopeName] = lastValue;
  9306. }
  9307. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9308. removeWatchCollection.push(removeWatch);
  9309. break;
  9310. case '=':
  9311. if (!hasOwnProperty.call(attrs, attrName)) {
  9312. if (optional) break;
  9313. attrs[attrName] = undefined;
  9314. }
  9315. if (optional && !attrs[attrName]) break;
  9316. parentGet = $parse(attrs[attrName]);
  9317. if (parentGet.literal) {
  9318. compare = equals;
  9319. } else {
  9320. // eslint-disable-next-line no-self-compare
  9321. compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
  9322. }
  9323. parentSet = parentGet.assign || function() {
  9324. // reset the change, or we will throw this exception on every $digest
  9325. lastValue = destination[scopeName] = parentGet(scope);
  9326. throw $compileMinErr('nonassign',
  9327. 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
  9328. attrs[attrName], attrName, directive.name);
  9329. };
  9330. lastValue = destination[scopeName] = parentGet(scope);
  9331. var parentValueWatch = function parentValueWatch(parentValue) {
  9332. if (!compare(parentValue, destination[scopeName])) {
  9333. // we are out of sync and need to copy
  9334. if (!compare(parentValue, lastValue)) {
  9335. // parent changed and it has precedence
  9336. destination[scopeName] = parentValue;
  9337. } else {
  9338. // if the parent can be assigned then do so
  9339. parentSet(scope, parentValue = destination[scopeName]);
  9340. }
  9341. }
  9342. lastValue = parentValue;
  9343. return lastValue;
  9344. };
  9345. parentValueWatch.$stateful = true;
  9346. if (definition.collection) {
  9347. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  9348. } else {
  9349. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  9350. }
  9351. removeWatchCollection.push(removeWatch);
  9352. break;
  9353. case '<':
  9354. if (!hasOwnProperty.call(attrs, attrName)) {
  9355. if (optional) break;
  9356. attrs[attrName] = undefined;
  9357. }
  9358. if (optional && !attrs[attrName]) break;
  9359. parentGet = $parse(attrs[attrName]);
  9360. var deepWatch = parentGet.literal;
  9361. var initialValue = destination[scopeName] = parentGet(scope);
  9362. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9363. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
  9364. if (oldValue === newValue) {
  9365. if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) {
  9366. return;
  9367. }
  9368. oldValue = initialValue;
  9369. }
  9370. recordChanges(scopeName, newValue, oldValue);
  9371. destination[scopeName] = newValue;
  9372. }, deepWatch);
  9373. removeWatchCollection.push(removeWatch);
  9374. break;
  9375. case '&':
  9376. // Don't assign Object.prototype method to scope
  9377. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  9378. // Don't assign noop to destination if expression is not valid
  9379. if (parentGet === noop && optional) break;
  9380. destination[scopeName] = function(locals) {
  9381. return parentGet(scope, locals);
  9382. };
  9383. break;
  9384. }
  9385. });
  9386. function recordChanges(key, currentValue, previousValue) {
  9387. if (isFunction(destination.$onChanges) && currentValue !== previousValue &&
  9388. // eslint-disable-next-line no-self-compare
  9389. (currentValue === currentValue || previousValue === previousValue)) {
  9390. // If we have not already scheduled the top level onChangesQueue handler then do so now
  9391. if (!onChangesQueue) {
  9392. scope.$$postDigest(flushOnChangesQueue);
  9393. onChangesQueue = [];
  9394. }
  9395. // If we have not already queued a trigger of onChanges for this controller then do so now
  9396. if (!changes) {
  9397. changes = {};
  9398. onChangesQueue.push(triggerOnChangesHook);
  9399. }
  9400. // If the has been a change on this property already then we need to reuse the previous value
  9401. if (changes[key]) {
  9402. previousValue = changes[key].previousValue;
  9403. }
  9404. // Store this change
  9405. changes[key] = new SimpleChange(previousValue, currentValue);
  9406. }
  9407. }
  9408. function triggerOnChangesHook() {
  9409. destination.$onChanges(changes);
  9410. // Now clear the changes so that we schedule onChanges when more changes arrive
  9411. changes = undefined;
  9412. }
  9413. return {
  9414. initialChanges: initialChanges,
  9415. removeWatches: removeWatchCollection.length && function removeWatches() {
  9416. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  9417. removeWatchCollection[i]();
  9418. }
  9419. }
  9420. };
  9421. }
  9422. }];
  9423. }
  9424. function SimpleChange(previous, current) {
  9425. this.previousValue = previous;
  9426. this.currentValue = current;
  9427. }
  9428. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  9429. var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
  9430. var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
  9431. /**
  9432. * Converts all accepted directives format into proper directive name.
  9433. * @param name Name to normalize
  9434. */
  9435. function directiveNormalize(name) {
  9436. return name
  9437. .replace(PREFIX_REGEXP, '')
  9438. .replace(SPECIAL_CHARS_REGEXP, fnCamelCaseReplace);
  9439. }
  9440. /**
  9441. * @ngdoc type
  9442. * @name $compile.directive.Attributes
  9443. *
  9444. * @description
  9445. * A shared object between directive compile / linking functions which contains normalized DOM
  9446. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  9447. * needed since all of these are treated as equivalent in Angular:
  9448. *
  9449. * ```
  9450. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  9451. * ```
  9452. */
  9453. /**
  9454. * @ngdoc property
  9455. * @name $compile.directive.Attributes#$attr
  9456. *
  9457. * @description
  9458. * A map of DOM element attribute names to the normalized name. This is
  9459. * needed to do reverse lookup from normalized name back to actual name.
  9460. */
  9461. /**
  9462. * @ngdoc method
  9463. * @name $compile.directive.Attributes#$set
  9464. * @kind function
  9465. *
  9466. * @description
  9467. * Set DOM element attribute value.
  9468. *
  9469. *
  9470. * @param {string} name Normalized element attribute name of the property to modify. The name is
  9471. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  9472. * property to the original name.
  9473. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  9474. */
  9475. /**
  9476. * Closure compiler type information
  9477. */
  9478. function nodesetLinkingFn(
  9479. /* angular.Scope */ scope,
  9480. /* NodeList */ nodeList,
  9481. /* Element */ rootElement,
  9482. /* function(Function) */ boundTranscludeFn
  9483. ) {}
  9484. function directiveLinkingFn(
  9485. /* nodesetLinkingFn */ nodesetLinkingFn,
  9486. /* angular.Scope */ scope,
  9487. /* Node */ node,
  9488. /* Element */ rootElement,
  9489. /* function(Function) */ boundTranscludeFn
  9490. ) {}
  9491. function tokenDifference(str1, str2) {
  9492. var values = '',
  9493. tokens1 = str1.split(/\s+/),
  9494. tokens2 = str2.split(/\s+/);
  9495. outer:
  9496. for (var i = 0; i < tokens1.length; i++) {
  9497. var token = tokens1[i];
  9498. for (var j = 0; j < tokens2.length; j++) {
  9499. if (token === tokens2[j]) continue outer;
  9500. }
  9501. values += (values.length > 0 ? ' ' : '') + token;
  9502. }
  9503. return values;
  9504. }
  9505. function removeComments(jqNodes) {
  9506. jqNodes = jqLite(jqNodes);
  9507. var i = jqNodes.length;
  9508. if (i <= 1) {
  9509. return jqNodes;
  9510. }
  9511. while (i--) {
  9512. var node = jqNodes[i];
  9513. if (node.nodeType === NODE_TYPE_COMMENT ||
  9514. (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {
  9515. splice.call(jqNodes, i, 1);
  9516. }
  9517. }
  9518. return jqNodes;
  9519. }
  9520. var $controllerMinErr = minErr('$controller');
  9521. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  9522. function identifierForController(controller, ident) {
  9523. if (ident && isString(ident)) return ident;
  9524. if (isString(controller)) {
  9525. var match = CNTRL_REG.exec(controller);
  9526. if (match) return match[3];
  9527. }
  9528. }
  9529. /**
  9530. * @ngdoc provider
  9531. * @name $controllerProvider
  9532. * @this
  9533. *
  9534. * @description
  9535. * The {@link ng.$controller $controller service} is used by Angular to create new
  9536. * controllers.
  9537. *
  9538. * This provider allows controller registration via the
  9539. * {@link ng.$controllerProvider#register register} method.
  9540. */
  9541. function $ControllerProvider() {
  9542. var controllers = {},
  9543. globals = false;
  9544. /**
  9545. * @ngdoc method
  9546. * @name $controllerProvider#has
  9547. * @param {string} name Controller name to check.
  9548. */
  9549. this.has = function(name) {
  9550. return controllers.hasOwnProperty(name);
  9551. };
  9552. /**
  9553. * @ngdoc method
  9554. * @name $controllerProvider#register
  9555. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  9556. * the names and the values are the constructors.
  9557. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  9558. * annotations in the array notation).
  9559. */
  9560. this.register = function(name, constructor) {
  9561. assertNotHasOwnProperty(name, 'controller');
  9562. if (isObject(name)) {
  9563. extend(controllers, name);
  9564. } else {
  9565. controllers[name] = constructor;
  9566. }
  9567. };
  9568. /**
  9569. * @ngdoc method
  9570. * @name $controllerProvider#allowGlobals
  9571. * @description If called, allows `$controller` to find controller constructors on `window`
  9572. *
  9573. * @deprecated
  9574. * sinceVersion="v1.3.0"
  9575. * removeVersion="v1.7.0"
  9576. * This method of finding controllers has been deprecated.
  9577. */
  9578. this.allowGlobals = function() {
  9579. globals = true;
  9580. };
  9581. this.$get = ['$injector', '$window', function($injector, $window) {
  9582. /**
  9583. * @ngdoc service
  9584. * @name $controller
  9585. * @requires $injector
  9586. *
  9587. * @param {Function|string} constructor If called with a function then it's considered to be the
  9588. * controller constructor function. Otherwise it's considered to be a string which is used
  9589. * to retrieve the controller constructor using the following steps:
  9590. *
  9591. * * check if a controller with given name is registered via `$controllerProvider`
  9592. * * check if evaluating the string on the current scope returns a constructor
  9593. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  9594. * `window` object (deprecated, not recommended)
  9595. *
  9596. * The string can use the `controller as property` syntax, where the controller instance is published
  9597. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  9598. * to work correctly.
  9599. *
  9600. * @param {Object} locals Injection locals for Controller.
  9601. * @return {Object} Instance of given controller.
  9602. *
  9603. * @description
  9604. * `$controller` service is responsible for instantiating controllers.
  9605. *
  9606. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  9607. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  9608. */
  9609. return function $controller(expression, locals, later, ident) {
  9610. // PRIVATE API:
  9611. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  9612. // If true, $controller will allocate the object with the correct
  9613. // prototype chain, but will not invoke the controller until a returned
  9614. // callback is invoked.
  9615. // param `ident` --- An optional label which overrides the label parsed from the controller
  9616. // expression, if any.
  9617. var instance, match, constructor, identifier;
  9618. later = later === true;
  9619. if (ident && isString(ident)) {
  9620. identifier = ident;
  9621. }
  9622. if (isString(expression)) {
  9623. match = expression.match(CNTRL_REG);
  9624. if (!match) {
  9625. throw $controllerMinErr('ctrlfmt',
  9626. 'Badly formed controller string \'{0}\'. ' +
  9627. 'Must match `__name__ as __id__` or `__name__`.', expression);
  9628. }
  9629. constructor = match[1];
  9630. identifier = identifier || match[3];
  9631. expression = controllers.hasOwnProperty(constructor)
  9632. ? controllers[constructor]
  9633. : getter(locals.$scope, constructor, true) ||
  9634. (globals ? getter($window, constructor, true) : undefined);
  9635. if (!expression) {
  9636. throw $controllerMinErr('ctrlreg',
  9637. 'The controller with the name \'{0}\' is not registered.', constructor);
  9638. }
  9639. assertArgFn(expression, constructor, true);
  9640. }
  9641. if (later) {
  9642. // Instantiate controller later:
  9643. // This machinery is used to create an instance of the object before calling the
  9644. // controller's constructor itself.
  9645. //
  9646. // This allows properties to be added to the controller before the constructor is
  9647. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  9648. //
  9649. // This feature is not intended for use by applications, and is thus not documented
  9650. // publicly.
  9651. // Object creation: http://jsperf.com/create-constructor/2
  9652. var controllerPrototype = (isArray(expression) ?
  9653. expression[expression.length - 1] : expression).prototype;
  9654. instance = Object.create(controllerPrototype || null);
  9655. if (identifier) {
  9656. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9657. }
  9658. return extend(function $controllerInit() {
  9659. var result = $injector.invoke(expression, instance, locals, constructor);
  9660. if (result !== instance && (isObject(result) || isFunction(result))) {
  9661. instance = result;
  9662. if (identifier) {
  9663. // If result changed, re-assign controllerAs value to scope.
  9664. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9665. }
  9666. }
  9667. return instance;
  9668. }, {
  9669. instance: instance,
  9670. identifier: identifier
  9671. });
  9672. }
  9673. instance = $injector.instantiate(expression, locals, constructor);
  9674. if (identifier) {
  9675. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9676. }
  9677. return instance;
  9678. };
  9679. function addIdentifier(locals, identifier, instance, name) {
  9680. if (!(locals && isObject(locals.$scope))) {
  9681. throw minErr('$controller')('noscp',
  9682. 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
  9683. name, identifier);
  9684. }
  9685. locals.$scope[identifier] = instance;
  9686. }
  9687. }];
  9688. }
  9689. /**
  9690. * @ngdoc service
  9691. * @name $document
  9692. * @requires $window
  9693. * @this
  9694. *
  9695. * @description
  9696. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  9697. *
  9698. * @example
  9699. <example module="documentExample" name="document">
  9700. <file name="index.html">
  9701. <div ng-controller="ExampleController">
  9702. <p>$document title: <b ng-bind="title"></b></p>
  9703. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  9704. </div>
  9705. </file>
  9706. <file name="script.js">
  9707. angular.module('documentExample', [])
  9708. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  9709. $scope.title = $document[0].title;
  9710. $scope.windowTitle = angular.element(window.document)[0].title;
  9711. }]);
  9712. </file>
  9713. </example>
  9714. */
  9715. function $DocumentProvider() {
  9716. this.$get = ['$window', function(window) {
  9717. return jqLite(window.document);
  9718. }];
  9719. }
  9720. /**
  9721. * @private
  9722. * @this
  9723. * Listens for document visibility change and makes the current status accessible.
  9724. */
  9725. function $$IsDocumentHiddenProvider() {
  9726. this.$get = ['$document', '$rootScope', function($document, $rootScope) {
  9727. var doc = $document[0];
  9728. var hidden = doc && doc.hidden;
  9729. $document.on('visibilitychange', changeListener);
  9730. $rootScope.$on('$destroy', function() {
  9731. $document.off('visibilitychange', changeListener);
  9732. });
  9733. function changeListener() {
  9734. hidden = doc.hidden;
  9735. }
  9736. return function() {
  9737. return hidden;
  9738. };
  9739. }];
  9740. }
  9741. /**
  9742. * @ngdoc service
  9743. * @name $exceptionHandler
  9744. * @requires ng.$log
  9745. * @this
  9746. *
  9747. * @description
  9748. * Any uncaught exception in angular expressions is delegated to this service.
  9749. * The default implementation simply delegates to `$log.error` which logs it into
  9750. * the browser console.
  9751. *
  9752. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  9753. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  9754. *
  9755. * ## Example:
  9756. *
  9757. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  9758. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  9759. * of `$log.error()`.
  9760. *
  9761. * ```js
  9762. * angular.
  9763. * module('exceptionOverwrite', []).
  9764. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  9765. * return function myExceptionHandler(exception, cause) {
  9766. * logErrorsToBackend(exception, cause);
  9767. * $log.warn(exception, cause);
  9768. * };
  9769. * }]);
  9770. * ```
  9771. *
  9772. * <hr />
  9773. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  9774. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  9775. * (unless executed during a digest).
  9776. *
  9777. * If you wish, you can manually delegate exceptions, e.g.
  9778. * `try { ... } catch(e) { $exceptionHandler(e); }`
  9779. *
  9780. * @param {Error} exception Exception associated with the error.
  9781. * @param {string=} cause Optional information about the context in which
  9782. * the error was thrown.
  9783. *
  9784. */
  9785. function $ExceptionHandlerProvider() {
  9786. this.$get = ['$log', function($log) {
  9787. return function(exception, cause) {
  9788. $log.error.apply($log, arguments);
  9789. };
  9790. }];
  9791. }
  9792. var $$ForceReflowProvider = /** @this */ function() {
  9793. this.$get = ['$document', function($document) {
  9794. return function(domNode) {
  9795. //the line below will force the browser to perform a repaint so
  9796. //that all the animated elements within the animation frame will
  9797. //be properly updated and drawn on screen. This is required to
  9798. //ensure that the preparation animation is properly flushed so that
  9799. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  9800. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  9801. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  9802. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  9803. if (domNode) {
  9804. if (!domNode.nodeType && domNode instanceof jqLite) {
  9805. domNode = domNode[0];
  9806. }
  9807. } else {
  9808. domNode = $document[0].body;
  9809. }
  9810. return domNode.offsetWidth + 1;
  9811. };
  9812. }];
  9813. };
  9814. var APPLICATION_JSON = 'application/json';
  9815. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  9816. var JSON_START = /^\[|^\{(?!\{)/;
  9817. var JSON_ENDS = {
  9818. '[': /]$/,
  9819. '{': /}$/
  9820. };
  9821. var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/;
  9822. var $httpMinErr = minErr('$http');
  9823. function serializeValue(v) {
  9824. if (isObject(v)) {
  9825. return isDate(v) ? v.toISOString() : toJson(v);
  9826. }
  9827. return v;
  9828. }
  9829. /** @this */
  9830. function $HttpParamSerializerProvider() {
  9831. /**
  9832. * @ngdoc service
  9833. * @name $httpParamSerializer
  9834. * @description
  9835. *
  9836. * Default {@link $http `$http`} params serializer that converts objects to strings
  9837. * according to the following rules:
  9838. *
  9839. * * `{'foo': 'bar'}` results in `foo=bar`
  9840. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  9841. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  9842. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
  9843. *
  9844. * Note that serializer will sort the request parameters alphabetically.
  9845. * */
  9846. this.$get = function() {
  9847. return function ngParamSerializer(params) {
  9848. if (!params) return '';
  9849. var parts = [];
  9850. forEachSorted(params, function(value, key) {
  9851. if (value === null || isUndefined(value)) return;
  9852. if (isArray(value)) {
  9853. forEach(value, function(v) {
  9854. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  9855. });
  9856. } else {
  9857. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  9858. }
  9859. });
  9860. return parts.join('&');
  9861. };
  9862. };
  9863. }
  9864. /** @this */
  9865. function $HttpParamSerializerJQLikeProvider() {
  9866. /**
  9867. * @ngdoc service
  9868. * @name $httpParamSerializerJQLike
  9869. *
  9870. * @description
  9871. *
  9872. * Alternative {@link $http `$http`} params serializer that follows
  9873. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  9874. * The serializer will also sort the params alphabetically.
  9875. *
  9876. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  9877. *
  9878. * ```js
  9879. * $http({
  9880. * url: myUrl,
  9881. * method: 'GET',
  9882. * params: myParams,
  9883. * paramSerializer: '$httpParamSerializerJQLike'
  9884. * });
  9885. * ```
  9886. *
  9887. * It is also possible to set it as the default `paramSerializer` in the
  9888. * {@link $httpProvider#defaults `$httpProvider`}.
  9889. *
  9890. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  9891. * form data for submission:
  9892. *
  9893. * ```js
  9894. * .controller(function($http, $httpParamSerializerJQLike) {
  9895. * //...
  9896. *
  9897. * $http({
  9898. * url: myUrl,
  9899. * method: 'POST',
  9900. * data: $httpParamSerializerJQLike(myData),
  9901. * headers: {
  9902. * 'Content-Type': 'application/x-www-form-urlencoded'
  9903. * }
  9904. * });
  9905. *
  9906. * });
  9907. * ```
  9908. *
  9909. * */
  9910. this.$get = function() {
  9911. return function jQueryLikeParamSerializer(params) {
  9912. if (!params) return '';
  9913. var parts = [];
  9914. serialize(params, '', true);
  9915. return parts.join('&');
  9916. function serialize(toSerialize, prefix, topLevel) {
  9917. if (toSerialize === null || isUndefined(toSerialize)) return;
  9918. if (isArray(toSerialize)) {
  9919. forEach(toSerialize, function(value, index) {
  9920. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  9921. });
  9922. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  9923. forEachSorted(toSerialize, function(value, key) {
  9924. serialize(value, prefix +
  9925. (topLevel ? '' : '[') +
  9926. key +
  9927. (topLevel ? '' : ']'));
  9928. });
  9929. } else {
  9930. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  9931. }
  9932. }
  9933. };
  9934. };
  9935. }
  9936. function defaultHttpResponseTransform(data, headers) {
  9937. if (isString(data)) {
  9938. // Strip json vulnerability protection prefix and trim whitespace
  9939. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  9940. if (tempData) {
  9941. var contentType = headers('Content-Type');
  9942. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  9943. data = fromJson(tempData);
  9944. }
  9945. }
  9946. }
  9947. return data;
  9948. }
  9949. function isJsonLike(str) {
  9950. var jsonStart = str.match(JSON_START);
  9951. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  9952. }
  9953. /**
  9954. * Parse headers into key value object
  9955. *
  9956. * @param {string} headers Raw headers as a string
  9957. * @returns {Object} Parsed headers as key value object
  9958. */
  9959. function parseHeaders(headers) {
  9960. var parsed = createMap(), i;
  9961. function fillInParsed(key, val) {
  9962. if (key) {
  9963. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  9964. }
  9965. }
  9966. if (isString(headers)) {
  9967. forEach(headers.split('\n'), function(line) {
  9968. i = line.indexOf(':');
  9969. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  9970. });
  9971. } else if (isObject(headers)) {
  9972. forEach(headers, function(headerVal, headerKey) {
  9973. fillInParsed(lowercase(headerKey), trim(headerVal));
  9974. });
  9975. }
  9976. return parsed;
  9977. }
  9978. /**
  9979. * Returns a function that provides access to parsed headers.
  9980. *
  9981. * Headers are lazy parsed when first requested.
  9982. * @see parseHeaders
  9983. *
  9984. * @param {(string|Object)} headers Headers to provide access to.
  9985. * @returns {function(string=)} Returns a getter function which if called with:
  9986. *
  9987. * - if called with an argument returns a single header value or null
  9988. * - if called with no arguments returns an object containing all headers.
  9989. */
  9990. function headersGetter(headers) {
  9991. var headersObj;
  9992. return function(name) {
  9993. if (!headersObj) headersObj = parseHeaders(headers);
  9994. if (name) {
  9995. var value = headersObj[lowercase(name)];
  9996. if (value === undefined) {
  9997. value = null;
  9998. }
  9999. return value;
  10000. }
  10001. return headersObj;
  10002. };
  10003. }
  10004. /**
  10005. * Chain all given functions
  10006. *
  10007. * This function is used for both request and response transforming
  10008. *
  10009. * @param {*} data Data to transform.
  10010. * @param {function(string=)} headers HTTP headers getter fn.
  10011. * @param {number} status HTTP status code of the response.
  10012. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  10013. * @returns {*} Transformed data.
  10014. */
  10015. function transformData(data, headers, status, fns) {
  10016. if (isFunction(fns)) {
  10017. return fns(data, headers, status);
  10018. }
  10019. forEach(fns, function(fn) {
  10020. data = fn(data, headers, status);
  10021. });
  10022. return data;
  10023. }
  10024. function isSuccess(status) {
  10025. return 200 <= status && status < 300;
  10026. }
  10027. /**
  10028. * @ngdoc provider
  10029. * @name $httpProvider
  10030. * @this
  10031. *
  10032. * @description
  10033. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  10034. * */
  10035. function $HttpProvider() {
  10036. /**
  10037. * @ngdoc property
  10038. * @name $httpProvider#defaults
  10039. * @description
  10040. *
  10041. * Object containing default values for all {@link ng.$http $http} requests.
  10042. *
  10043. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  10044. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  10045. * by default. See {@link $http#caching $http Caching} for more information.
  10046. *
  10047. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  10048. * Defaults value is `'XSRF-TOKEN'`.
  10049. *
  10050. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  10051. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  10052. *
  10053. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  10054. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  10055. * setting default headers.
  10056. * - **`defaults.headers.common`**
  10057. * - **`defaults.headers.post`**
  10058. * - **`defaults.headers.put`**
  10059. * - **`defaults.headers.patch`**
  10060. *
  10061. *
  10062. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  10063. * used to the prepare string representation of request parameters (specified as an object).
  10064. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  10065. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  10066. *
  10067. * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the
  10068. * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the
  10069. * {@link $jsonpCallbacks} service. Defaults to `'callback'`.
  10070. *
  10071. **/
  10072. var defaults = this.defaults = {
  10073. // transform incoming response data
  10074. transformResponse: [defaultHttpResponseTransform],
  10075. // transform outgoing request data
  10076. transformRequest: [function(d) {
  10077. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  10078. }],
  10079. // default headers
  10080. headers: {
  10081. common: {
  10082. 'Accept': 'application/json, text/plain, */*'
  10083. },
  10084. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10085. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10086. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  10087. },
  10088. xsrfCookieName: 'XSRF-TOKEN',
  10089. xsrfHeaderName: 'X-XSRF-TOKEN',
  10090. paramSerializer: '$httpParamSerializer',
  10091. jsonpCallbackParam: 'callback'
  10092. };
  10093. var useApplyAsync = false;
  10094. /**
  10095. * @ngdoc method
  10096. * @name $httpProvider#useApplyAsync
  10097. * @description
  10098. *
  10099. * Configure $http service to combine processing of multiple http responses received at around
  10100. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  10101. * significant performance improvement for bigger applications that make many HTTP requests
  10102. * concurrently (common during application bootstrap).
  10103. *
  10104. * Defaults to false. If no value is specified, returns the current configured value.
  10105. *
  10106. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  10107. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  10108. * to load and share the same digest cycle.
  10109. *
  10110. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  10111. * otherwise, returns the current configured value.
  10112. **/
  10113. this.useApplyAsync = function(value) {
  10114. if (isDefined(value)) {
  10115. useApplyAsync = !!value;
  10116. return this;
  10117. }
  10118. return useApplyAsync;
  10119. };
  10120. /**
  10121. * @ngdoc property
  10122. * @name $httpProvider#interceptors
  10123. * @description
  10124. *
  10125. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  10126. * pre-processing of request or postprocessing of responses.
  10127. *
  10128. * These service factories are ordered by request, i.e. they are applied in the same order as the
  10129. * array, on request, but reverse order, on response.
  10130. *
  10131. * {@link ng.$http#interceptors Interceptors detailed info}
  10132. **/
  10133. var interceptorFactories = this.interceptors = [];
  10134. this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
  10135. function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {
  10136. var defaultCache = $cacheFactory('$http');
  10137. /**
  10138. * Make sure that default param serializer is exposed as a function
  10139. */
  10140. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  10141. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  10142. /**
  10143. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  10144. * The reversal is needed so that we can build up the interception chain around the
  10145. * server request.
  10146. */
  10147. var reversedInterceptors = [];
  10148. forEach(interceptorFactories, function(interceptorFactory) {
  10149. reversedInterceptors.unshift(isString(interceptorFactory)
  10150. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  10151. });
  10152. /**
  10153. * @ngdoc service
  10154. * @kind function
  10155. * @name $http
  10156. * @requires ng.$httpBackend
  10157. * @requires $cacheFactory
  10158. * @requires $rootScope
  10159. * @requires $q
  10160. * @requires $injector
  10161. *
  10162. * @description
  10163. * The `$http` service is a core Angular service that facilitates communication with the remote
  10164. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  10165. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  10166. *
  10167. * For unit testing applications that use `$http` service, see
  10168. * {@link ngMock.$httpBackend $httpBackend mock}.
  10169. *
  10170. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  10171. * $resource} service.
  10172. *
  10173. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  10174. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  10175. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  10176. *
  10177. *
  10178. * ## General usage
  10179. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  10180. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  10181. *
  10182. * ```js
  10183. * // Simple GET request example:
  10184. * $http({
  10185. * method: 'GET',
  10186. * url: '/someUrl'
  10187. * }).then(function successCallback(response) {
  10188. * // this callback will be called asynchronously
  10189. * // when the response is available
  10190. * }, function errorCallback(response) {
  10191. * // called asynchronously if an error occurs
  10192. * // or server returns response with an error status.
  10193. * });
  10194. * ```
  10195. *
  10196. * The response object has these properties:
  10197. *
  10198. * - **data** – `{string|Object}` – The response body transformed with the transform
  10199. * functions.
  10200. * - **status** – `{number}` – HTTP status code of the response.
  10201. * - **headers** – `{function([headerName])}` – Header getter function.
  10202. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  10203. * - **statusText** – `{string}` – HTTP status text of the response.
  10204. *
  10205. * A response status code between 200 and 299 is considered a success status and will result in
  10206. * the success callback being called. Any response status code outside of that range is
  10207. * considered an error status and will result in the error callback being called.
  10208. * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
  10209. * aborted, e.g. using a `config.timeout`.
  10210. * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
  10211. * that the outcome (success or error) will be determined by the final response status code.
  10212. *
  10213. *
  10214. * ## Shortcut methods
  10215. *
  10216. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  10217. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  10218. * last argument.
  10219. *
  10220. * ```js
  10221. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  10222. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  10223. * ```
  10224. *
  10225. * Complete list of shortcut methods:
  10226. *
  10227. * - {@link ng.$http#get $http.get}
  10228. * - {@link ng.$http#head $http.head}
  10229. * - {@link ng.$http#post $http.post}
  10230. * - {@link ng.$http#put $http.put}
  10231. * - {@link ng.$http#delete $http.delete}
  10232. * - {@link ng.$http#jsonp $http.jsonp}
  10233. * - {@link ng.$http#patch $http.patch}
  10234. *
  10235. *
  10236. * ## Writing Unit Tests that use $http
  10237. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  10238. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  10239. * request using trained responses.
  10240. *
  10241. * ```
  10242. * $httpBackend.expectGET(...);
  10243. * $http.get(...);
  10244. * $httpBackend.flush();
  10245. * ```
  10246. *
  10247. * ## Setting HTTP Headers
  10248. *
  10249. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  10250. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  10251. * object, which currently contains this default configuration:
  10252. *
  10253. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  10254. * - <code>Accept: application/json, text/plain, \*&#65279;/&#65279;\*</code>
  10255. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  10256. * - `Content-Type: application/json`
  10257. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  10258. * - `Content-Type: application/json`
  10259. *
  10260. * To add or overwrite these defaults, simply add or remove a property from these configuration
  10261. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  10262. * with the lowercased HTTP method name as the key, e.g.
  10263. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  10264. *
  10265. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  10266. * fashion. For example:
  10267. *
  10268. * ```
  10269. * module.run(function($http) {
  10270. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  10271. * });
  10272. * ```
  10273. *
  10274. * In addition, you can supply a `headers` property in the config object passed when
  10275. * calling `$http(config)`, which overrides the defaults without changing them globally.
  10276. *
  10277. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  10278. * Use the `headers` property, setting the desired header to `undefined`. For example:
  10279. *
  10280. * ```js
  10281. * var req = {
  10282. * method: 'POST',
  10283. * url: 'http://example.com',
  10284. * headers: {
  10285. * 'Content-Type': undefined
  10286. * },
  10287. * data: { test: 'test' }
  10288. * }
  10289. *
  10290. * $http(req).then(function(){...}, function(){...});
  10291. * ```
  10292. *
  10293. * ## Transforming Requests and Responses
  10294. *
  10295. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  10296. * and `transformResponse`. These properties can be a single function that returns
  10297. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  10298. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  10299. *
  10300. * <div class="alert alert-warning">
  10301. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  10302. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  10303. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  10304. * function will be reflected on the scope and in any templates where the object is data-bound.
  10305. * To prevent this, transform functions should have no side-effects.
  10306. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  10307. * </div>
  10308. *
  10309. * ### Default Transformations
  10310. *
  10311. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  10312. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  10313. * then these will be applied.
  10314. *
  10315. * You can augment or replace the default transformations by modifying these properties by adding to or
  10316. * replacing the array.
  10317. *
  10318. * Angular provides the following default transformations:
  10319. *
  10320. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  10321. *
  10322. * - If the `data` property of the request configuration object contains an object, serialize it
  10323. * into JSON format.
  10324. *
  10325. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  10326. *
  10327. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  10328. * - If JSON response is detected, deserialize it using a JSON parser.
  10329. *
  10330. *
  10331. * ### Overriding the Default Transformations Per Request
  10332. *
  10333. * If you wish to override the request/response transformations only for a single request then provide
  10334. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  10335. * into `$http`.
  10336. *
  10337. * Note that if you provide these properties on the config object the default transformations will be
  10338. * overwritten. If you wish to augment the default transformations then you must include them in your
  10339. * local transformation array.
  10340. *
  10341. * The following code demonstrates adding a new response transformation to be run after the default response
  10342. * transformations have been run.
  10343. *
  10344. * ```js
  10345. * function appendTransform(defaults, transform) {
  10346. *
  10347. * // We can't guarantee that the default transformation is an array
  10348. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  10349. *
  10350. * // Append the new transformation to the defaults
  10351. * return defaults.concat(transform);
  10352. * }
  10353. *
  10354. * $http({
  10355. * url: '...',
  10356. * method: 'GET',
  10357. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  10358. * return doTransform(value);
  10359. * })
  10360. * });
  10361. * ```
  10362. *
  10363. *
  10364. * ## Caching
  10365. *
  10366. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  10367. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  10368. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  10369. * precedence over the default cache value.
  10370. *
  10371. * In order to:
  10372. * * cache all responses - set the default cache value to TRUE or to a cache object
  10373. * * cache a specific response - set config.cache value to TRUE or to a cache object
  10374. *
  10375. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  10376. * then the default `$cacheFactory("$http")` object is used.
  10377. *
  10378. * The default cache value can be set by updating the
  10379. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  10380. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  10381. *
  10382. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  10383. * the relevant cache object. The next time the same request is made, the response is returned
  10384. * from the cache without sending a request to the server.
  10385. *
  10386. * Take note that:
  10387. *
  10388. * * Only GET and JSONP requests are cached.
  10389. * * The cache key is the request URL including search parameters; headers are not considered.
  10390. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  10391. * * If multiple identical requests are made using the same cache, which is not yet populated,
  10392. * one request will be made to the server and remaining requests will return the same response.
  10393. * * A cache-control header on the response does not affect if or how responses are cached.
  10394. *
  10395. *
  10396. * ## Interceptors
  10397. *
  10398. * Before you start creating interceptors, be sure to understand the
  10399. * {@link ng.$q $q and deferred/promise APIs}.
  10400. *
  10401. * For purposes of global error handling, authentication, or any kind of synchronous or
  10402. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  10403. * able to intercept requests before they are handed to the server and
  10404. * responses before they are handed over to the application code that
  10405. * initiated these requests. The interceptors leverage the {@link ng.$q
  10406. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  10407. *
  10408. * The interceptors are service factories that are registered with the `$httpProvider` by
  10409. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  10410. * injected with dependencies (if specified) and returns the interceptor.
  10411. *
  10412. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  10413. *
  10414. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  10415. * modify the `config` object or create a new one. The function needs to return the `config`
  10416. * object directly, or a promise containing the `config` or a new `config` object.
  10417. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  10418. * resolved with a rejection.
  10419. * * `response`: interceptors get called with http `response` object. The function is free to
  10420. * modify the `response` object or create a new one. The function needs to return the `response`
  10421. * object directly, or as a promise containing the `response` or a new `response` object.
  10422. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  10423. * resolved with a rejection.
  10424. *
  10425. *
  10426. * ```js
  10427. * // register the interceptor as a service
  10428. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  10429. * return {
  10430. * // optional method
  10431. * 'request': function(config) {
  10432. * // do something on success
  10433. * return config;
  10434. * },
  10435. *
  10436. * // optional method
  10437. * 'requestError': function(rejection) {
  10438. * // do something on error
  10439. * if (canRecover(rejection)) {
  10440. * return responseOrNewPromise
  10441. * }
  10442. * return $q.reject(rejection);
  10443. * },
  10444. *
  10445. *
  10446. *
  10447. * // optional method
  10448. * 'response': function(response) {
  10449. * // do something on success
  10450. * return response;
  10451. * },
  10452. *
  10453. * // optional method
  10454. * 'responseError': function(rejection) {
  10455. * // do something on error
  10456. * if (canRecover(rejection)) {
  10457. * return responseOrNewPromise
  10458. * }
  10459. * return $q.reject(rejection);
  10460. * }
  10461. * };
  10462. * });
  10463. *
  10464. * $httpProvider.interceptors.push('myHttpInterceptor');
  10465. *
  10466. *
  10467. * // alternatively, register the interceptor via an anonymous factory
  10468. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  10469. * return {
  10470. * 'request': function(config) {
  10471. * // same as above
  10472. * },
  10473. *
  10474. * 'response': function(response) {
  10475. * // same as above
  10476. * }
  10477. * };
  10478. * });
  10479. * ```
  10480. *
  10481. * ## Security Considerations
  10482. *
  10483. * When designing web applications, consider security threats from:
  10484. *
  10485. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10486. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  10487. *
  10488. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  10489. * pre-configured with strategies that address these issues, but for this to work backend server
  10490. * cooperation is required.
  10491. *
  10492. * ### JSON Vulnerability Protection
  10493. *
  10494. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10495. * allows third party website to turn your JSON resource URL into
  10496. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  10497. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  10498. * Angular will automatically strip the prefix before processing it as JSON.
  10499. *
  10500. * For example if your server needs to return:
  10501. * ```js
  10502. * ['one','two']
  10503. * ```
  10504. *
  10505. * which is vulnerable to attack, your server can return:
  10506. * ```js
  10507. * )]}',
  10508. * ['one','two']
  10509. * ```
  10510. *
  10511. * Angular will strip the prefix, before processing the JSON.
  10512. *
  10513. *
  10514. * ### Cross Site Request Forgery (XSRF) Protection
  10515. *
  10516. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  10517. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  10518. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  10519. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  10520. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  10521. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  10522. * The header will not be set for cross-domain requests.
  10523. *
  10524. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  10525. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  10526. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  10527. * that only JavaScript running on your domain could have sent the request. The token must be
  10528. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  10529. * making up its own tokens). We recommend that the token is a digest of your site's
  10530. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  10531. * for added security.
  10532. *
  10533. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  10534. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  10535. * or the per-request config object.
  10536. *
  10537. * In order to prevent collisions in environments where multiple Angular apps share the
  10538. * same domain or subdomain, we recommend that each application uses unique cookie name.
  10539. *
  10540. * @param {object} config Object describing the request to be made and how it should be
  10541. * processed. The object has following properties:
  10542. *
  10543. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  10544. * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;
  10545. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10546. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  10547. * with the `paramSerializer` and appended as GET parameters.
  10548. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  10549. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  10550. * HTTP headers to send to the server. If the return value of a function is null, the
  10551. * header will not be sent. Functions accept a config object as an argument.
  10552. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  10553. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  10554. * The handler will be called in the context of a `$apply` block.
  10555. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  10556. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  10557. * The handler will be called in the context of a `$apply` block.
  10558. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  10559. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  10560. * - **transformRequest** –
  10561. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  10562. * transform function or an array of such functions. The transform function takes the http
  10563. * request body and headers and returns its transformed (typically serialized) version.
  10564. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10565. * Overriding the Default Transformations}
  10566. * - **transformResponse** –
  10567. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  10568. * transform function or an array of such functions. The transform function takes the http
  10569. * response body, headers and status and returns its transformed (typically deserialized) version.
  10570. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10571. * Overriding the Default Transformations}
  10572. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  10573. * prepare the string representation of request parameters (specified as an object).
  10574. * If specified as string, it is interpreted as function registered with the
  10575. * {@link $injector $injector}, which means you can create your own serializer
  10576. * by registering it as a {@link auto.$provide#service service}.
  10577. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  10578. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  10579. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  10580. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  10581. * See {@link $http#caching $http Caching} for more information.
  10582. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  10583. * that should abort the request when resolved.
  10584. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  10585. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  10586. * for more information.
  10587. * - **responseType** - `{string}` - see
  10588. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  10589. *
  10590. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  10591. * when the request succeeds or fails.
  10592. *
  10593. *
  10594. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  10595. * requests. This is primarily meant to be used for debugging purposes.
  10596. *
  10597. *
  10598. * @example
  10599. <example module="httpExample" name="http-service">
  10600. <file name="index.html">
  10601. <div ng-controller="FetchController">
  10602. <select ng-model="method" aria-label="Request method">
  10603. <option>GET</option>
  10604. <option>JSONP</option>
  10605. </select>
  10606. <input type="text" ng-model="url" size="80" aria-label="URL" />
  10607. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  10608. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  10609. <button id="samplejsonpbtn"
  10610. ng-click="updateModel('JSONP',
  10611. 'https://angularjs.org/greet.php?name=Super%20Hero')">
  10612. Sample JSONP
  10613. </button>
  10614. <button id="invalidjsonpbtn"
  10615. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')">
  10616. Invalid JSONP
  10617. </button>
  10618. <pre>http status code: {{status}}</pre>
  10619. <pre>http response data: {{data}}</pre>
  10620. </div>
  10621. </file>
  10622. <file name="script.js">
  10623. angular.module('httpExample', [])
  10624. .config(['$sceDelegateProvider', function($sceDelegateProvider) {
  10625. // We must whitelist the JSONP endpoint that we are using to show that we trust it
  10626. $sceDelegateProvider.resourceUrlWhitelist([
  10627. 'self',
  10628. 'https://angularjs.org/**'
  10629. ]);
  10630. }])
  10631. .controller('FetchController', ['$scope', '$http', '$templateCache',
  10632. function($scope, $http, $templateCache) {
  10633. $scope.method = 'GET';
  10634. $scope.url = 'http-hello.html';
  10635. $scope.fetch = function() {
  10636. $scope.code = null;
  10637. $scope.response = null;
  10638. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  10639. then(function(response) {
  10640. $scope.status = response.status;
  10641. $scope.data = response.data;
  10642. }, function(response) {
  10643. $scope.data = response.data || 'Request failed';
  10644. $scope.status = response.status;
  10645. });
  10646. };
  10647. $scope.updateModel = function(method, url) {
  10648. $scope.method = method;
  10649. $scope.url = url;
  10650. };
  10651. }]);
  10652. </file>
  10653. <file name="http-hello.html">
  10654. Hello, $http!
  10655. </file>
  10656. <file name="protractor.js" type="protractor">
  10657. var status = element(by.binding('status'));
  10658. var data = element(by.binding('data'));
  10659. var fetchBtn = element(by.id('fetchbtn'));
  10660. var sampleGetBtn = element(by.id('samplegetbtn'));
  10661. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  10662. it('should make an xhr GET request', function() {
  10663. sampleGetBtn.click();
  10664. fetchBtn.click();
  10665. expect(status.getText()).toMatch('200');
  10666. expect(data.getText()).toMatch(/Hello, \$http!/);
  10667. });
  10668. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  10669. // it('should make a JSONP request to angularjs.org', function() {
  10670. // var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  10671. // sampleJsonpBtn.click();
  10672. // fetchBtn.click();
  10673. // expect(status.getText()).toMatch('200');
  10674. // expect(data.getText()).toMatch(/Super Hero!/);
  10675. // });
  10676. it('should make JSONP request to invalid URL and invoke the error handler',
  10677. function() {
  10678. invalidJsonpBtn.click();
  10679. fetchBtn.click();
  10680. expect(status.getText()).toMatch('0');
  10681. expect(data.getText()).toMatch('Request failed');
  10682. });
  10683. </file>
  10684. </example>
  10685. */
  10686. function $http(requestConfig) {
  10687. if (!isObject(requestConfig)) {
  10688. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  10689. }
  10690. if (!isString($sce.valueOf(requestConfig.url))) {
  10691. throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);
  10692. }
  10693. var config = extend({
  10694. method: 'get',
  10695. transformRequest: defaults.transformRequest,
  10696. transformResponse: defaults.transformResponse,
  10697. paramSerializer: defaults.paramSerializer,
  10698. jsonpCallbackParam: defaults.jsonpCallbackParam
  10699. }, requestConfig);
  10700. config.headers = mergeHeaders(requestConfig);
  10701. config.method = uppercase(config.method);
  10702. config.paramSerializer = isString(config.paramSerializer) ?
  10703. $injector.get(config.paramSerializer) : config.paramSerializer;
  10704. $browser.$$incOutstandingRequestCount();
  10705. var requestInterceptors = [];
  10706. var responseInterceptors = [];
  10707. var promise = $q.resolve(config);
  10708. // apply interceptors
  10709. forEach(reversedInterceptors, function(interceptor) {
  10710. if (interceptor.request || interceptor.requestError) {
  10711. requestInterceptors.unshift(interceptor.request, interceptor.requestError);
  10712. }
  10713. if (interceptor.response || interceptor.responseError) {
  10714. responseInterceptors.push(interceptor.response, interceptor.responseError);
  10715. }
  10716. });
  10717. promise = chainInterceptors(promise, requestInterceptors);
  10718. promise = promise.then(serverRequest);
  10719. promise = chainInterceptors(promise, responseInterceptors);
  10720. promise = promise.finally(completeOutstandingRequest);
  10721. return promise;
  10722. function chainInterceptors(promise, interceptors) {
  10723. for (var i = 0, ii = interceptors.length; i < ii;) {
  10724. var thenFn = interceptors[i++];
  10725. var rejectFn = interceptors[i++];
  10726. promise = promise.then(thenFn, rejectFn);
  10727. }
  10728. interceptors.length = 0;
  10729. return promise;
  10730. }
  10731. function completeOutstandingRequest() {
  10732. $browser.$$completeOutstandingRequest(noop);
  10733. }
  10734. function executeHeaderFns(headers, config) {
  10735. var headerContent, processedHeaders = {};
  10736. forEach(headers, function(headerFn, header) {
  10737. if (isFunction(headerFn)) {
  10738. headerContent = headerFn(config);
  10739. if (headerContent != null) {
  10740. processedHeaders[header] = headerContent;
  10741. }
  10742. } else {
  10743. processedHeaders[header] = headerFn;
  10744. }
  10745. });
  10746. return processedHeaders;
  10747. }
  10748. function mergeHeaders(config) {
  10749. var defHeaders = defaults.headers,
  10750. reqHeaders = extend({}, config.headers),
  10751. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  10752. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  10753. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  10754. defaultHeadersIteration:
  10755. for (defHeaderName in defHeaders) {
  10756. lowercaseDefHeaderName = lowercase(defHeaderName);
  10757. for (reqHeaderName in reqHeaders) {
  10758. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  10759. continue defaultHeadersIteration;
  10760. }
  10761. }
  10762. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  10763. }
  10764. // execute if header value is a function for merged headers
  10765. return executeHeaderFns(reqHeaders, shallowCopy(config));
  10766. }
  10767. function serverRequest(config) {
  10768. var headers = config.headers;
  10769. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  10770. // strip content-type if data is undefined
  10771. if (isUndefined(reqData)) {
  10772. forEach(headers, function(value, header) {
  10773. if (lowercase(header) === 'content-type') {
  10774. delete headers[header];
  10775. }
  10776. });
  10777. }
  10778. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  10779. config.withCredentials = defaults.withCredentials;
  10780. }
  10781. // send request
  10782. return sendReq(config, reqData).then(transformResponse, transformResponse);
  10783. }
  10784. function transformResponse(response) {
  10785. // make a copy since the response must be cacheable
  10786. var resp = extend({}, response);
  10787. resp.data = transformData(response.data, response.headers, response.status,
  10788. config.transformResponse);
  10789. return (isSuccess(response.status))
  10790. ? resp
  10791. : $q.reject(resp);
  10792. }
  10793. }
  10794. $http.pendingRequests = [];
  10795. /**
  10796. * @ngdoc method
  10797. * @name $http#get
  10798. *
  10799. * @description
  10800. * Shortcut method to perform `GET` request.
  10801. *
  10802. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10803. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10804. * @param {Object=} config Optional configuration object
  10805. * @returns {HttpPromise} Future object
  10806. */
  10807. /**
  10808. * @ngdoc method
  10809. * @name $http#delete
  10810. *
  10811. * @description
  10812. * Shortcut method to perform `DELETE` request.
  10813. *
  10814. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10815. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10816. * @param {Object=} config Optional configuration object
  10817. * @returns {HttpPromise} Future object
  10818. */
  10819. /**
  10820. * @ngdoc method
  10821. * @name $http#head
  10822. *
  10823. * @description
  10824. * Shortcut method to perform `HEAD` request.
  10825. *
  10826. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10827. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10828. * @param {Object=} config Optional configuration object
  10829. * @returns {HttpPromise} Future object
  10830. */
  10831. /**
  10832. * @ngdoc method
  10833. * @name $http#jsonp
  10834. *
  10835. * @description
  10836. * Shortcut method to perform `JSONP` request.
  10837. *
  10838. * Note that, since JSONP requests are sensitive because the response is given full access to the browser,
  10839. * the url must be declared, via {@link $sce} as a trusted resource URL.
  10840. * You can trust a URL by adding it to the whitelist via
  10841. * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or
  10842. * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.
  10843. *
  10844. * JSONP requests must specify a callback to be used in the response from the server. This callback
  10845. * is passed as a query parameter in the request. You must specify the name of this parameter by
  10846. * setting the `jsonpCallbackParam` property on the request config object.
  10847. *
  10848. * ```
  10849. * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
  10850. * ```
  10851. *
  10852. * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.
  10853. * Initially this is set to `'callback'`.
  10854. *
  10855. * <div class="alert alert-danger">
  10856. * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback
  10857. * parameter value should go.
  10858. * </div>
  10859. *
  10860. * If you would like to customise where and how the callbacks are stored then try overriding
  10861. * or decorating the {@link $jsonpCallbacks} service.
  10862. *
  10863. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10864. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10865. * @param {Object=} config Optional configuration object
  10866. * @returns {HttpPromise} Future object
  10867. */
  10868. createShortMethods('get', 'delete', 'head', 'jsonp');
  10869. /**
  10870. * @ngdoc method
  10871. * @name $http#post
  10872. *
  10873. * @description
  10874. * Shortcut method to perform `POST` request.
  10875. *
  10876. * @param {string} url Relative or absolute URL specifying the destination of the request
  10877. * @param {*} data Request content
  10878. * @param {Object=} config Optional configuration object
  10879. * @returns {HttpPromise} Future object
  10880. */
  10881. /**
  10882. * @ngdoc method
  10883. * @name $http#put
  10884. *
  10885. * @description
  10886. * Shortcut method to perform `PUT` request.
  10887. *
  10888. * @param {string} url Relative or absolute URL specifying the destination of the request
  10889. * @param {*} data Request content
  10890. * @param {Object=} config Optional configuration object
  10891. * @returns {HttpPromise} Future object
  10892. */
  10893. /**
  10894. * @ngdoc method
  10895. * @name $http#patch
  10896. *
  10897. * @description
  10898. * Shortcut method to perform `PATCH` request.
  10899. *
  10900. * @param {string} url Relative or absolute URL specifying the destination of the request
  10901. * @param {*} data Request content
  10902. * @param {Object=} config Optional configuration object
  10903. * @returns {HttpPromise} Future object
  10904. */
  10905. createShortMethodsWithData('post', 'put', 'patch');
  10906. /**
  10907. * @ngdoc property
  10908. * @name $http#defaults
  10909. *
  10910. * @description
  10911. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  10912. * default headers, withCredentials as well as request and response transformations.
  10913. *
  10914. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  10915. */
  10916. $http.defaults = defaults;
  10917. return $http;
  10918. function createShortMethods(names) {
  10919. forEach(arguments, function(name) {
  10920. $http[name] = function(url, config) {
  10921. return $http(extend({}, config || {}, {
  10922. method: name,
  10923. url: url
  10924. }));
  10925. };
  10926. });
  10927. }
  10928. function createShortMethodsWithData(name) {
  10929. forEach(arguments, function(name) {
  10930. $http[name] = function(url, data, config) {
  10931. return $http(extend({}, config || {}, {
  10932. method: name,
  10933. url: url,
  10934. data: data
  10935. }));
  10936. };
  10937. });
  10938. }
  10939. /**
  10940. * Makes the request.
  10941. *
  10942. * !!! ACCESSES CLOSURE VARS:
  10943. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  10944. */
  10945. function sendReq(config, reqData) {
  10946. var deferred = $q.defer(),
  10947. promise = deferred.promise,
  10948. cache,
  10949. cachedResp,
  10950. reqHeaders = config.headers,
  10951. isJsonp = lowercase(config.method) === 'jsonp',
  10952. url = config.url;
  10953. if (isJsonp) {
  10954. // JSONP is a pretty sensitive operation where we're allowing a script to have full access to
  10955. // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.
  10956. url = $sce.getTrustedResourceUrl(url);
  10957. } else if (!isString(url)) {
  10958. // If it is not a string then the URL must be a $sce trusted object
  10959. url = $sce.valueOf(url);
  10960. }
  10961. url = buildUrl(url, config.paramSerializer(config.params));
  10962. if (isJsonp) {
  10963. // Check the url and add the JSONP callback placeholder
  10964. url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);
  10965. }
  10966. $http.pendingRequests.push(config);
  10967. promise.then(removePendingReq, removePendingReq);
  10968. if ((config.cache || defaults.cache) && config.cache !== false &&
  10969. (config.method === 'GET' || config.method === 'JSONP')) {
  10970. cache = isObject(config.cache) ? config.cache
  10971. : isObject(/** @type {?} */ (defaults).cache)
  10972. ? /** @type {?} */ (defaults).cache
  10973. : defaultCache;
  10974. }
  10975. if (cache) {
  10976. cachedResp = cache.get(url);
  10977. if (isDefined(cachedResp)) {
  10978. if (isPromiseLike(cachedResp)) {
  10979. // cached request has already been sent, but there is no response yet
  10980. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  10981. } else {
  10982. // serving from cache
  10983. if (isArray(cachedResp)) {
  10984. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  10985. } else {
  10986. resolvePromise(cachedResp, 200, {}, 'OK');
  10987. }
  10988. }
  10989. } else {
  10990. // put the promise for the non-transformed response into cache as a placeholder
  10991. cache.put(url, promise);
  10992. }
  10993. }
  10994. // if we won't have the response in cache, set the xsrf headers and
  10995. // send the request to the backend
  10996. if (isUndefined(cachedResp)) {
  10997. var xsrfValue = urlIsSameOrigin(config.url)
  10998. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  10999. : undefined;
  11000. if (xsrfValue) {
  11001. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  11002. }
  11003. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  11004. config.withCredentials, config.responseType,
  11005. createApplyHandlers(config.eventHandlers),
  11006. createApplyHandlers(config.uploadEventHandlers));
  11007. }
  11008. return promise;
  11009. function createApplyHandlers(eventHandlers) {
  11010. if (eventHandlers) {
  11011. var applyHandlers = {};
  11012. forEach(eventHandlers, function(eventHandler, key) {
  11013. applyHandlers[key] = function(event) {
  11014. if (useApplyAsync) {
  11015. $rootScope.$applyAsync(callEventHandler);
  11016. } else if ($rootScope.$$phase) {
  11017. callEventHandler();
  11018. } else {
  11019. $rootScope.$apply(callEventHandler);
  11020. }
  11021. function callEventHandler() {
  11022. eventHandler(event);
  11023. }
  11024. };
  11025. });
  11026. return applyHandlers;
  11027. }
  11028. }
  11029. /**
  11030. * Callback registered to $httpBackend():
  11031. * - caches the response if desired
  11032. * - resolves the raw $http promise
  11033. * - calls $apply
  11034. */
  11035. function done(status, response, headersString, statusText) {
  11036. if (cache) {
  11037. if (isSuccess(status)) {
  11038. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  11039. } else {
  11040. // remove promise from the cache
  11041. cache.remove(url);
  11042. }
  11043. }
  11044. function resolveHttpPromise() {
  11045. resolvePromise(response, status, headersString, statusText);
  11046. }
  11047. if (useApplyAsync) {
  11048. $rootScope.$applyAsync(resolveHttpPromise);
  11049. } else {
  11050. resolveHttpPromise();
  11051. if (!$rootScope.$$phase) $rootScope.$apply();
  11052. }
  11053. }
  11054. /**
  11055. * Resolves the raw $http promise.
  11056. */
  11057. function resolvePromise(response, status, headers, statusText) {
  11058. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  11059. status = status >= -1 ? status : 0;
  11060. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  11061. data: response,
  11062. status: status,
  11063. headers: headersGetter(headers),
  11064. config: config,
  11065. statusText: statusText
  11066. });
  11067. }
  11068. function resolvePromiseWithResult(result) {
  11069. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  11070. }
  11071. function removePendingReq() {
  11072. var idx = $http.pendingRequests.indexOf(config);
  11073. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  11074. }
  11075. }
  11076. function buildUrl(url, serializedParams) {
  11077. if (serializedParams.length > 0) {
  11078. url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
  11079. }
  11080. return url;
  11081. }
  11082. function sanitizeJsonpCallbackParam(url, key) {
  11083. if (/[&?][^=]+=JSON_CALLBACK/.test(url)) {
  11084. // Throw if the url already contains a reference to JSON_CALLBACK
  11085. throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url);
  11086. }
  11087. var callbackParamRegex = new RegExp('[&?]' + key + '=');
  11088. if (callbackParamRegex.test(url)) {
  11089. // Throw if the callback param was already provided
  11090. throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', key, url);
  11091. }
  11092. // Add in the JSON_CALLBACK callback param value
  11093. url += ((url.indexOf('?') === -1) ? '?' : '&') + key + '=JSON_CALLBACK';
  11094. return url;
  11095. }
  11096. }];
  11097. }
  11098. /**
  11099. * @ngdoc service
  11100. * @name $xhrFactory
  11101. * @this
  11102. *
  11103. * @description
  11104. * Factory function used to create XMLHttpRequest objects.
  11105. *
  11106. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  11107. *
  11108. * ```
  11109. * angular.module('myApp', [])
  11110. * .factory('$xhrFactory', function() {
  11111. * return function createXhr(method, url) {
  11112. * return new window.XMLHttpRequest({mozSystem: true});
  11113. * };
  11114. * });
  11115. * ```
  11116. *
  11117. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  11118. * @param {string} url URL of the request.
  11119. */
  11120. function $xhrFactoryProvider() {
  11121. this.$get = function() {
  11122. return function createXhr() {
  11123. return new window.XMLHttpRequest();
  11124. };
  11125. };
  11126. }
  11127. /**
  11128. * @ngdoc service
  11129. * @name $httpBackend
  11130. * @requires $jsonpCallbacks
  11131. * @requires $document
  11132. * @requires $xhrFactory
  11133. * @this
  11134. *
  11135. * @description
  11136. * HTTP backend used by the {@link ng.$http service} that delegates to
  11137. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  11138. *
  11139. * You should never need to use this service directly, instead use the higher-level abstractions:
  11140. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  11141. *
  11142. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  11143. * $httpBackend} which can be trained with responses.
  11144. */
  11145. function $HttpBackendProvider() {
  11146. this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
  11147. return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
  11148. }];
  11149. }
  11150. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  11151. // TODO(vojta): fix the signature
  11152. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  11153. url = url || $browser.url();
  11154. if (lowercase(method) === 'jsonp') {
  11155. var callbackPath = callbacks.createCallback(url);
  11156. var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
  11157. // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
  11158. var response = (status === 200) && callbacks.getResponse(callbackPath);
  11159. completeRequest(callback, status, response, '', text);
  11160. callbacks.removeCallback(callbackPath);
  11161. });
  11162. } else {
  11163. var xhr = createXhr(method, url);
  11164. xhr.open(method, url, true);
  11165. forEach(headers, function(value, key) {
  11166. if (isDefined(value)) {
  11167. xhr.setRequestHeader(key, value);
  11168. }
  11169. });
  11170. xhr.onload = function requestLoaded() {
  11171. var statusText = xhr.statusText || '';
  11172. // responseText is the old-school way of retrieving response (supported by IE9)
  11173. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  11174. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  11175. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  11176. var status = xhr.status === 1223 ? 204 : xhr.status;
  11177. // fix status code when it is 0 (0 status is undocumented).
  11178. // Occurs when accessing file resources or on Android 4.1 stock browser
  11179. // while retrieving files from application cache.
  11180. if (status === 0) {
  11181. status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
  11182. }
  11183. completeRequest(callback,
  11184. status,
  11185. response,
  11186. xhr.getAllResponseHeaders(),
  11187. statusText);
  11188. };
  11189. var requestError = function() {
  11190. // The response is always empty
  11191. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  11192. completeRequest(callback, -1, null, null, '');
  11193. };
  11194. xhr.onerror = requestError;
  11195. xhr.onabort = requestError;
  11196. xhr.ontimeout = requestError;
  11197. forEach(eventHandlers, function(value, key) {
  11198. xhr.addEventListener(key, value);
  11199. });
  11200. forEach(uploadEventHandlers, function(value, key) {
  11201. xhr.upload.addEventListener(key, value);
  11202. });
  11203. if (withCredentials) {
  11204. xhr.withCredentials = true;
  11205. }
  11206. if (responseType) {
  11207. try {
  11208. xhr.responseType = responseType;
  11209. } catch (e) {
  11210. // WebKit added support for the json responseType value on 09/03/2013
  11211. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  11212. // known to throw when setting the value "json" as the response type. Other older
  11213. // browsers implementing the responseType
  11214. //
  11215. // The json response type can be ignored if not supported, because JSON payloads are
  11216. // parsed on the client-side regardless.
  11217. if (responseType !== 'json') {
  11218. throw e;
  11219. }
  11220. }
  11221. }
  11222. xhr.send(isUndefined(post) ? null : post);
  11223. }
  11224. if (timeout > 0) {
  11225. var timeoutId = $browserDefer(timeoutRequest, timeout);
  11226. } else if (isPromiseLike(timeout)) {
  11227. timeout.then(timeoutRequest);
  11228. }
  11229. function timeoutRequest() {
  11230. if (jsonpDone) {
  11231. jsonpDone();
  11232. }
  11233. if (xhr) {
  11234. xhr.abort();
  11235. }
  11236. }
  11237. function completeRequest(callback, status, response, headersString, statusText) {
  11238. // cancel timeout and subsequent timeout promise resolution
  11239. if (isDefined(timeoutId)) {
  11240. $browserDefer.cancel(timeoutId);
  11241. }
  11242. jsonpDone = xhr = null;
  11243. callback(status, response, headersString, statusText);
  11244. }
  11245. };
  11246. function jsonpReq(url, callbackPath, done) {
  11247. url = url.replace('JSON_CALLBACK', callbackPath);
  11248. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  11249. // - fetches local scripts via XHR and evals them
  11250. // - adds and immediately removes script elements from the document
  11251. var script = rawDocument.createElement('script'), callback = null;
  11252. script.type = 'text/javascript';
  11253. script.src = url;
  11254. script.async = true;
  11255. callback = function(event) {
  11256. script.removeEventListener('load', callback);
  11257. script.removeEventListener('error', callback);
  11258. rawDocument.body.removeChild(script);
  11259. script = null;
  11260. var status = -1;
  11261. var text = 'unknown';
  11262. if (event) {
  11263. if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
  11264. event = { type: 'error' };
  11265. }
  11266. text = event.type;
  11267. status = event.type === 'error' ? 404 : 200;
  11268. }
  11269. if (done) {
  11270. done(status, text);
  11271. }
  11272. };
  11273. script.addEventListener('load', callback);
  11274. script.addEventListener('error', callback);
  11275. rawDocument.body.appendChild(script);
  11276. return callback;
  11277. }
  11278. }
  11279. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  11280. $interpolateMinErr.throwNoconcat = function(text) {
  11281. throw $interpolateMinErr('noconcat',
  11282. 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
  11283. 'interpolations that concatenate multiple expressions when a trusted value is ' +
  11284. 'required. See http://docs.angularjs.org/api/ng.$sce', text);
  11285. };
  11286. $interpolateMinErr.interr = function(text, err) {
  11287. return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
  11288. };
  11289. /**
  11290. * @ngdoc provider
  11291. * @name $interpolateProvider
  11292. * @this
  11293. *
  11294. * @description
  11295. *
  11296. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  11297. *
  11298. * <div class="alert alert-danger">
  11299. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  11300. * template within a Python Jinja template (or any other template language). Mixing templating
  11301. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  11302. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  11303. * security bugs!
  11304. * </div>
  11305. *
  11306. * @example
  11307. <example name="custom-interpolation-markup" module="customInterpolationApp">
  11308. <file name="index.html">
  11309. <script>
  11310. var customInterpolationApp = angular.module('customInterpolationApp', []);
  11311. customInterpolationApp.config(function($interpolateProvider) {
  11312. $interpolateProvider.startSymbol('//');
  11313. $interpolateProvider.endSymbol('//');
  11314. });
  11315. customInterpolationApp.controller('DemoController', function() {
  11316. this.label = "This binding is brought you by // interpolation symbols.";
  11317. });
  11318. </script>
  11319. <div ng-controller="DemoController as demo">
  11320. //demo.label//
  11321. </div>
  11322. </file>
  11323. <file name="protractor.js" type="protractor">
  11324. it('should interpolate binding with custom symbols', function() {
  11325. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  11326. });
  11327. </file>
  11328. </example>
  11329. */
  11330. function $InterpolateProvider() {
  11331. var startSymbol = '{{';
  11332. var endSymbol = '}}';
  11333. /**
  11334. * @ngdoc method
  11335. * @name $interpolateProvider#startSymbol
  11336. * @description
  11337. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  11338. *
  11339. * @param {string=} value new value to set the starting symbol to.
  11340. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11341. */
  11342. this.startSymbol = function(value) {
  11343. if (value) {
  11344. startSymbol = value;
  11345. return this;
  11346. } else {
  11347. return startSymbol;
  11348. }
  11349. };
  11350. /**
  11351. * @ngdoc method
  11352. * @name $interpolateProvider#endSymbol
  11353. * @description
  11354. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11355. *
  11356. * @param {string=} value new value to set the ending symbol to.
  11357. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11358. */
  11359. this.endSymbol = function(value) {
  11360. if (value) {
  11361. endSymbol = value;
  11362. return this;
  11363. } else {
  11364. return endSymbol;
  11365. }
  11366. };
  11367. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  11368. var startSymbolLength = startSymbol.length,
  11369. endSymbolLength = endSymbol.length,
  11370. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  11371. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  11372. function escape(ch) {
  11373. return '\\\\\\' + ch;
  11374. }
  11375. function unescapeText(text) {
  11376. return text.replace(escapedStartRegexp, startSymbol).
  11377. replace(escapedEndRegexp, endSymbol);
  11378. }
  11379. // TODO: this is the same as the constantWatchDelegate in parse.js
  11380. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  11381. var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  11382. unwatch();
  11383. return constantInterp(scope);
  11384. }, listener, objectEquality);
  11385. return unwatch;
  11386. }
  11387. /**
  11388. * @ngdoc service
  11389. * @name $interpolate
  11390. * @kind function
  11391. *
  11392. * @requires $parse
  11393. * @requires $sce
  11394. *
  11395. * @description
  11396. *
  11397. * Compiles a string with markup into an interpolation function. This service is used by the
  11398. * HTML {@link ng.$compile $compile} service for data binding. See
  11399. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  11400. * interpolation markup.
  11401. *
  11402. *
  11403. * ```js
  11404. * var $interpolate = ...; // injected
  11405. * var exp = $interpolate('Hello {{name | uppercase}}!');
  11406. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  11407. * ```
  11408. *
  11409. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  11410. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  11411. * evaluate to a value other than `undefined`.
  11412. *
  11413. * ```js
  11414. * var $interpolate = ...; // injected
  11415. * var context = {greeting: 'Hello', name: undefined };
  11416. *
  11417. * // default "forgiving" mode
  11418. * var exp = $interpolate('{{greeting}} {{name}}!');
  11419. * expect(exp(context)).toEqual('Hello !');
  11420. *
  11421. * // "allOrNothing" mode
  11422. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  11423. * expect(exp(context)).toBeUndefined();
  11424. * context.name = 'Angular';
  11425. * expect(exp(context)).toEqual('Hello Angular!');
  11426. * ```
  11427. *
  11428. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  11429. *
  11430. * #### Escaped Interpolation
  11431. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  11432. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  11433. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  11434. * or binding.
  11435. *
  11436. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  11437. * degree, while also enabling code examples to work without relying on the
  11438. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  11439. *
  11440. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  11441. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  11442. * interpolation start/end markers with their escaped counterparts.**
  11443. *
  11444. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  11445. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  11446. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  11447. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  11448. * this is typically useful only when user-data is used in rendering a template from the server, or
  11449. * when otherwise untrusted data is used by a directive.
  11450. *
  11451. * <example name="interpolation">
  11452. * <file name="index.html">
  11453. * <div ng-init="username='A user'">
  11454. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  11455. * </p>
  11456. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  11457. * application, but fails to accomplish their task, because the server has correctly
  11458. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  11459. * characters.</p>
  11460. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  11461. * from the database by an administrator.</p>
  11462. * </div>
  11463. * </file>
  11464. * </example>
  11465. *
  11466. * @knownIssue
  11467. * It is currently not possible for an interpolated expression to contain the interpolation end
  11468. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  11469. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  11470. *
  11471. * @knownIssue
  11472. * All directives and components must use the standard `{{` `}}` interpolation symbols
  11473. * in their templates. If you change the application interpolation symbols the {@link $compile}
  11474. * service will attempt to denormalize the standard symbols to the custom symbols.
  11475. * The denormalization process is not clever enough to know not to replace instances of the standard
  11476. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  11477. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  11478. *
  11479. * ```
  11480. * <div data-context='{"context":{"id":3,"type":"page"}}">
  11481. * ```
  11482. *
  11483. * The workaround is to ensure that such instances are separated by whitespace:
  11484. * ```
  11485. * <div data-context='{"context":{"id":3,"type":"page"} }">
  11486. * ```
  11487. *
  11488. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  11489. *
  11490. * @param {string} text The text with markup to interpolate.
  11491. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  11492. * embedded expression in order to return an interpolation function. Strings with no
  11493. * embedded expression will return null for the interpolation function.
  11494. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  11495. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  11496. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  11497. * provides Strict Contextual Escaping for details.
  11498. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  11499. * unless all embedded expressions evaluate to a value other than `undefined`.
  11500. * @returns {function(context)} an interpolation function which is used to compute the
  11501. * interpolated string. The function has these parameters:
  11502. *
  11503. * - `context`: evaluation context for all expressions embedded in the interpolated text
  11504. */
  11505. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  11506. // Provide a quick exit and simplified result function for text with no interpolation
  11507. if (!text.length || text.indexOf(startSymbol) === -1) {
  11508. var constantInterp;
  11509. if (!mustHaveExpression) {
  11510. var unescapedText = unescapeText(text);
  11511. constantInterp = valueFn(unescapedText);
  11512. constantInterp.exp = text;
  11513. constantInterp.expressions = [];
  11514. constantInterp.$$watchDelegate = constantWatchDelegate;
  11515. }
  11516. return constantInterp;
  11517. }
  11518. allOrNothing = !!allOrNothing;
  11519. var startIndex,
  11520. endIndex,
  11521. index = 0,
  11522. expressions = [],
  11523. parseFns = [],
  11524. textLength = text.length,
  11525. exp,
  11526. concat = [],
  11527. expressionPositions = [];
  11528. while (index < textLength) {
  11529. if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
  11530. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
  11531. if (index !== startIndex) {
  11532. concat.push(unescapeText(text.substring(index, startIndex)));
  11533. }
  11534. exp = text.substring(startIndex + startSymbolLength, endIndex);
  11535. expressions.push(exp);
  11536. parseFns.push($parse(exp, parseStringifyInterceptor));
  11537. index = endIndex + endSymbolLength;
  11538. expressionPositions.push(concat.length);
  11539. concat.push('');
  11540. } else {
  11541. // we did not find an interpolation, so we have to add the remainder to the separators array
  11542. if (index !== textLength) {
  11543. concat.push(unescapeText(text.substring(index)));
  11544. }
  11545. break;
  11546. }
  11547. }
  11548. // Concatenating expressions makes it hard to reason about whether some combination of
  11549. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  11550. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  11551. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  11552. // make it obvious that you bound the value to some user controlled value. This helps reduce
  11553. // the load when auditing for XSS issues.
  11554. if (trustedContext && concat.length > 1) {
  11555. $interpolateMinErr.throwNoconcat(text);
  11556. }
  11557. if (!mustHaveExpression || expressions.length) {
  11558. var compute = function(values) {
  11559. for (var i = 0, ii = expressions.length; i < ii; i++) {
  11560. if (allOrNothing && isUndefined(values[i])) return;
  11561. concat[expressionPositions[i]] = values[i];
  11562. }
  11563. return concat.join('');
  11564. };
  11565. var getValue = function(value) {
  11566. return trustedContext ?
  11567. $sce.getTrusted(trustedContext, value) :
  11568. $sce.valueOf(value);
  11569. };
  11570. return extend(function interpolationFn(context) {
  11571. var i = 0;
  11572. var ii = expressions.length;
  11573. var values = new Array(ii);
  11574. try {
  11575. for (; i < ii; i++) {
  11576. values[i] = parseFns[i](context);
  11577. }
  11578. return compute(values);
  11579. } catch (err) {
  11580. $exceptionHandler($interpolateMinErr.interr(text, err));
  11581. }
  11582. }, {
  11583. // all of these properties are undocumented for now
  11584. exp: text, //just for compatibility with regular watchers created via $watch
  11585. expressions: expressions,
  11586. $$watchDelegate: function(scope, listener) {
  11587. var lastValue;
  11588. return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
  11589. var currValue = compute(values);
  11590. if (isFunction(listener)) {
  11591. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  11592. }
  11593. lastValue = currValue;
  11594. });
  11595. }
  11596. });
  11597. }
  11598. function parseStringifyInterceptor(value) {
  11599. try {
  11600. value = getValue(value);
  11601. return allOrNothing && !isDefined(value) ? value : stringify(value);
  11602. } catch (err) {
  11603. $exceptionHandler($interpolateMinErr.interr(text, err));
  11604. }
  11605. }
  11606. }
  11607. /**
  11608. * @ngdoc method
  11609. * @name $interpolate#startSymbol
  11610. * @description
  11611. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  11612. *
  11613. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  11614. * the symbol.
  11615. *
  11616. * @returns {string} start symbol.
  11617. */
  11618. $interpolate.startSymbol = function() {
  11619. return startSymbol;
  11620. };
  11621. /**
  11622. * @ngdoc method
  11623. * @name $interpolate#endSymbol
  11624. * @description
  11625. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11626. *
  11627. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  11628. * the symbol.
  11629. *
  11630. * @returns {string} end symbol.
  11631. */
  11632. $interpolate.endSymbol = function() {
  11633. return endSymbol;
  11634. };
  11635. return $interpolate;
  11636. }];
  11637. }
  11638. /** @this */
  11639. function $IntervalProvider() {
  11640. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  11641. function($rootScope, $window, $q, $$q, $browser) {
  11642. var intervals = {};
  11643. /**
  11644. * @ngdoc service
  11645. * @name $interval
  11646. *
  11647. * @description
  11648. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  11649. * milliseconds.
  11650. *
  11651. * The return value of registering an interval function is a promise. This promise will be
  11652. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  11653. * run indefinitely if `count` is not defined. The value of the notification will be the
  11654. * number of iterations that have run.
  11655. * To cancel an interval, call `$interval.cancel(promise)`.
  11656. *
  11657. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  11658. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  11659. * time.
  11660. *
  11661. * <div class="alert alert-warning">
  11662. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  11663. * with them. In particular they are not automatically destroyed when a controller's scope or a
  11664. * directive's element are destroyed.
  11665. * You should take this into consideration and make sure to always cancel the interval at the
  11666. * appropriate moment. See the example below for more details on how and when to do this.
  11667. * </div>
  11668. *
  11669. * @param {function()} fn A function that should be called repeatedly. If no additional arguments
  11670. * are passed (see below), the function is called with the current iteration count.
  11671. * @param {number} delay Number of milliseconds between each function call.
  11672. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  11673. * indefinitely.
  11674. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  11675. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  11676. * @param {...*=} Pass additional parameters to the executed function.
  11677. * @returns {promise} A promise which will be notified on each iteration.
  11678. *
  11679. * @example
  11680. * <example module="intervalExample" name="interval-service">
  11681. * <file name="index.html">
  11682. * <script>
  11683. * angular.module('intervalExample', [])
  11684. * .controller('ExampleController', ['$scope', '$interval',
  11685. * function($scope, $interval) {
  11686. * $scope.format = 'M/d/yy h:mm:ss a';
  11687. * $scope.blood_1 = 100;
  11688. * $scope.blood_2 = 120;
  11689. *
  11690. * var stop;
  11691. * $scope.fight = function() {
  11692. * // Don't start a new fight if we are already fighting
  11693. * if ( angular.isDefined(stop) ) return;
  11694. *
  11695. * stop = $interval(function() {
  11696. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  11697. * $scope.blood_1 = $scope.blood_1 - 3;
  11698. * $scope.blood_2 = $scope.blood_2 - 4;
  11699. * } else {
  11700. * $scope.stopFight();
  11701. * }
  11702. * }, 100);
  11703. * };
  11704. *
  11705. * $scope.stopFight = function() {
  11706. * if (angular.isDefined(stop)) {
  11707. * $interval.cancel(stop);
  11708. * stop = undefined;
  11709. * }
  11710. * };
  11711. *
  11712. * $scope.resetFight = function() {
  11713. * $scope.blood_1 = 100;
  11714. * $scope.blood_2 = 120;
  11715. * };
  11716. *
  11717. * $scope.$on('$destroy', function() {
  11718. * // Make sure that the interval is destroyed too
  11719. * $scope.stopFight();
  11720. * });
  11721. * }])
  11722. * // Register the 'myCurrentTime' directive factory method.
  11723. * // We inject $interval and dateFilter service since the factory method is DI.
  11724. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  11725. * function($interval, dateFilter) {
  11726. * // return the directive link function. (compile function not needed)
  11727. * return function(scope, element, attrs) {
  11728. * var format, // date format
  11729. * stopTime; // so that we can cancel the time updates
  11730. *
  11731. * // used to update the UI
  11732. * function updateTime() {
  11733. * element.text(dateFilter(new Date(), format));
  11734. * }
  11735. *
  11736. * // watch the expression, and update the UI on change.
  11737. * scope.$watch(attrs.myCurrentTime, function(value) {
  11738. * format = value;
  11739. * updateTime();
  11740. * });
  11741. *
  11742. * stopTime = $interval(updateTime, 1000);
  11743. *
  11744. * // listen on DOM destroy (removal) event, and cancel the next UI update
  11745. * // to prevent updating time after the DOM element was removed.
  11746. * element.on('$destroy', function() {
  11747. * $interval.cancel(stopTime);
  11748. * });
  11749. * }
  11750. * }]);
  11751. * </script>
  11752. *
  11753. * <div>
  11754. * <div ng-controller="ExampleController">
  11755. * <label>Date format: <input ng-model="format"></label> <hr/>
  11756. * Current time is: <span my-current-time="format"></span>
  11757. * <hr/>
  11758. * Blood 1 : <font color='red'>{{blood_1}}</font>
  11759. * Blood 2 : <font color='red'>{{blood_2}}</font>
  11760. * <button type="button" data-ng-click="fight()">Fight</button>
  11761. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  11762. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  11763. * </div>
  11764. * </div>
  11765. *
  11766. * </file>
  11767. * </example>
  11768. */
  11769. function interval(fn, delay, count, invokeApply) {
  11770. var hasParams = arguments.length > 4,
  11771. args = hasParams ? sliceArgs(arguments, 4) : [],
  11772. setInterval = $window.setInterval,
  11773. clearInterval = $window.clearInterval,
  11774. iteration = 0,
  11775. skipApply = (isDefined(invokeApply) && !invokeApply),
  11776. deferred = (skipApply ? $$q : $q).defer(),
  11777. promise = deferred.promise;
  11778. count = isDefined(count) ? count : 0;
  11779. promise.$$intervalId = setInterval(function tick() {
  11780. if (skipApply) {
  11781. $browser.defer(callback);
  11782. } else {
  11783. $rootScope.$evalAsync(callback);
  11784. }
  11785. deferred.notify(iteration++);
  11786. if (count > 0 && iteration >= count) {
  11787. deferred.resolve(iteration);
  11788. clearInterval(promise.$$intervalId);
  11789. delete intervals[promise.$$intervalId];
  11790. }
  11791. if (!skipApply) $rootScope.$apply();
  11792. }, delay);
  11793. intervals[promise.$$intervalId] = deferred;
  11794. return promise;
  11795. function callback() {
  11796. if (!hasParams) {
  11797. fn(iteration);
  11798. } else {
  11799. fn.apply(null, args);
  11800. }
  11801. }
  11802. }
  11803. /**
  11804. * @ngdoc method
  11805. * @name $interval#cancel
  11806. *
  11807. * @description
  11808. * Cancels a task associated with the `promise`.
  11809. *
  11810. * @param {Promise=} promise returned by the `$interval` function.
  11811. * @returns {boolean} Returns `true` if the task was successfully canceled.
  11812. */
  11813. interval.cancel = function(promise) {
  11814. if (promise && promise.$$intervalId in intervals) {
  11815. // Interval cancels should not report as unhandled promise.
  11816. intervals[promise.$$intervalId].promise.catch(noop);
  11817. intervals[promise.$$intervalId].reject('canceled');
  11818. $window.clearInterval(promise.$$intervalId);
  11819. delete intervals[promise.$$intervalId];
  11820. return true;
  11821. }
  11822. return false;
  11823. };
  11824. return interval;
  11825. }];
  11826. }
  11827. /**
  11828. * @ngdoc service
  11829. * @name $jsonpCallbacks
  11830. * @requires $window
  11831. * @description
  11832. * This service handles the lifecycle of callbacks to handle JSONP requests.
  11833. * Override this service if you wish to customise where the callbacks are stored and
  11834. * how they vary compared to the requested url.
  11835. */
  11836. var $jsonpCallbacksProvider = /** @this */ function() {
  11837. this.$get = ['$window', function($window) {
  11838. var callbacks = $window.angular.callbacks;
  11839. var callbackMap = {};
  11840. function createCallback(callbackId) {
  11841. var callback = function(data) {
  11842. callback.data = data;
  11843. callback.called = true;
  11844. };
  11845. callback.id = callbackId;
  11846. return callback;
  11847. }
  11848. return {
  11849. /**
  11850. * @ngdoc method
  11851. * @name $jsonpCallbacks#createCallback
  11852. * @param {string} url the url of the JSONP request
  11853. * @returns {string} the callback path to send to the server as part of the JSONP request
  11854. * @description
  11855. * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
  11856. * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
  11857. */
  11858. createCallback: function(url) {
  11859. var callbackId = '_' + (callbacks.$$counter++).toString(36);
  11860. var callbackPath = 'angular.callbacks.' + callbackId;
  11861. var callback = createCallback(callbackId);
  11862. callbackMap[callbackPath] = callbacks[callbackId] = callback;
  11863. return callbackPath;
  11864. },
  11865. /**
  11866. * @ngdoc method
  11867. * @name $jsonpCallbacks#wasCalled
  11868. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11869. * @returns {boolean} whether the callback has been called, as a result of the JSONP response
  11870. * @description
  11871. * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
  11872. * callback that was passed in the request.
  11873. */
  11874. wasCalled: function(callbackPath) {
  11875. return callbackMap[callbackPath].called;
  11876. },
  11877. /**
  11878. * @ngdoc method
  11879. * @name $jsonpCallbacks#getResponse
  11880. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11881. * @returns {*} the data received from the response via the registered callback
  11882. * @description
  11883. * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
  11884. * in the JSONP response.
  11885. */
  11886. getResponse: function(callbackPath) {
  11887. return callbackMap[callbackPath].data;
  11888. },
  11889. /**
  11890. * @ngdoc method
  11891. * @name $jsonpCallbacks#removeCallback
  11892. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11893. * @description
  11894. * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
  11895. * completed or timed-out.
  11896. */
  11897. removeCallback: function(callbackPath) {
  11898. var callback = callbackMap[callbackPath];
  11899. delete callbacks[callback.id];
  11900. delete callbackMap[callbackPath];
  11901. }
  11902. };
  11903. }];
  11904. };
  11905. /**
  11906. * @ngdoc service
  11907. * @name $locale
  11908. *
  11909. * @description
  11910. * $locale service provides localization rules for various Angular components. As of right now the
  11911. * only public api is:
  11912. *
  11913. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  11914. */
  11915. var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
  11916. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  11917. var $locationMinErr = minErr('$location');
  11918. /**
  11919. * Encode path using encodeUriSegment, ignoring forward slashes
  11920. *
  11921. * @param {string} path Path to encode
  11922. * @returns {string}
  11923. */
  11924. function encodePath(path) {
  11925. var segments = path.split('/'),
  11926. i = segments.length;
  11927. while (i--) {
  11928. segments[i] = encodeUriSegment(segments[i]);
  11929. }
  11930. return segments.join('/');
  11931. }
  11932. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  11933. var parsedUrl = urlResolve(absoluteUrl);
  11934. locationObj.$$protocol = parsedUrl.protocol;
  11935. locationObj.$$host = parsedUrl.hostname;
  11936. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  11937. }
  11938. var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
  11939. function parseAppUrl(url, locationObj) {
  11940. if (DOUBLE_SLASH_REGEX.test(url)) {
  11941. throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
  11942. }
  11943. var prefixed = (url.charAt(0) !== '/');
  11944. if (prefixed) {
  11945. url = '/' + url;
  11946. }
  11947. var match = urlResolve(url);
  11948. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  11949. match.pathname.substring(1) : match.pathname);
  11950. locationObj.$$search = parseKeyValue(match.search);
  11951. locationObj.$$hash = decodeURIComponent(match.hash);
  11952. // make sure path starts with '/';
  11953. if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
  11954. locationObj.$$path = '/' + locationObj.$$path;
  11955. }
  11956. }
  11957. function startsWith(str, search) {
  11958. return str.slice(0, search.length) === search;
  11959. }
  11960. /**
  11961. *
  11962. * @param {string} base
  11963. * @param {string} url
  11964. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  11965. * the expected string.
  11966. */
  11967. function stripBaseUrl(base, url) {
  11968. if (startsWith(url, base)) {
  11969. return url.substr(base.length);
  11970. }
  11971. }
  11972. function stripHash(url) {
  11973. var index = url.indexOf('#');
  11974. return index === -1 ? url : url.substr(0, index);
  11975. }
  11976. function trimEmptyHash(url) {
  11977. return url.replace(/(#.+)|#$/, '$1');
  11978. }
  11979. function stripFile(url) {
  11980. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  11981. }
  11982. /* return the server only (scheme://host:port) */
  11983. function serverBase(url) {
  11984. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  11985. }
  11986. /**
  11987. * LocationHtml5Url represents a URL
  11988. * This object is exposed as $location service when HTML5 mode is enabled and supported
  11989. *
  11990. * @constructor
  11991. * @param {string} appBase application base URL
  11992. * @param {string} appBaseNoFile application base URL stripped of any filename
  11993. * @param {string} basePrefix URL path prefix
  11994. */
  11995. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  11996. this.$$html5 = true;
  11997. basePrefix = basePrefix || '';
  11998. parseAbsoluteUrl(appBase, this);
  11999. /**
  12000. * Parse given HTML5 (regular) URL string into properties
  12001. * @param {string} url HTML5 URL
  12002. * @private
  12003. */
  12004. this.$$parse = function(url) {
  12005. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  12006. if (!isString(pathUrl)) {
  12007. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  12008. appBaseNoFile);
  12009. }
  12010. parseAppUrl(pathUrl, this);
  12011. if (!this.$$path) {
  12012. this.$$path = '/';
  12013. }
  12014. this.$$compose();
  12015. };
  12016. /**
  12017. * Compose url and update `absUrl` property
  12018. * @private
  12019. */
  12020. this.$$compose = function() {
  12021. var search = toKeyValue(this.$$search),
  12022. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12023. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12024. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  12025. this.$$urlUpdatedByLocation = true;
  12026. };
  12027. this.$$parseLinkUrl = function(url, relHref) {
  12028. if (relHref && relHref[0] === '#') {
  12029. // special case for links to hash fragments:
  12030. // keep the old url and only replace the hash fragment
  12031. this.hash(relHref.slice(1));
  12032. return true;
  12033. }
  12034. var appUrl, prevAppUrl;
  12035. var rewrittenUrl;
  12036. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  12037. prevAppUrl = appUrl;
  12038. if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  12039. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  12040. } else {
  12041. rewrittenUrl = appBase + prevAppUrl;
  12042. }
  12043. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12044. rewrittenUrl = appBaseNoFile + appUrl;
  12045. } else if (appBaseNoFile === url + '/') {
  12046. rewrittenUrl = appBaseNoFile;
  12047. }
  12048. if (rewrittenUrl) {
  12049. this.$$parse(rewrittenUrl);
  12050. }
  12051. return !!rewrittenUrl;
  12052. };
  12053. }
  12054. /**
  12055. * LocationHashbangUrl represents URL
  12056. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  12057. * It also serves as the base class for html5 mode fallback on legacy browsers.
  12058. *
  12059. * @constructor
  12060. * @param {string} appBase application base URL
  12061. * @param {string} appBaseNoFile application base URL stripped of any filename
  12062. * @param {string} hashPrefix hashbang prefix
  12063. */
  12064. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  12065. parseAbsoluteUrl(appBase, this);
  12066. /**
  12067. * Parse given hashbang URL into properties
  12068. * @param {string} url Hashbang URL
  12069. * @private
  12070. */
  12071. this.$$parse = function(url) {
  12072. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  12073. var withoutHashUrl;
  12074. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  12075. // The rest of the URL starts with a hash so we have
  12076. // got either a hashbang path or a plain hash fragment
  12077. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  12078. if (isUndefined(withoutHashUrl)) {
  12079. // There was no hashbang prefix so we just have a hash fragment
  12080. withoutHashUrl = withoutBaseUrl;
  12081. }
  12082. } else {
  12083. // There was no hashbang path nor hash fragment:
  12084. // If we are in HTML5 mode we use what is left as the path;
  12085. // Otherwise we ignore what is left
  12086. if (this.$$html5) {
  12087. withoutHashUrl = withoutBaseUrl;
  12088. } else {
  12089. withoutHashUrl = '';
  12090. if (isUndefined(withoutBaseUrl)) {
  12091. appBase = url;
  12092. /** @type {?} */ (this).replace();
  12093. }
  12094. }
  12095. }
  12096. parseAppUrl(withoutHashUrl, this);
  12097. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  12098. this.$$compose();
  12099. /*
  12100. * In Windows, on an anchor node on documents loaded from
  12101. * the filesystem, the browser will return a pathname
  12102. * prefixed with the drive name ('/C:/path') when a
  12103. * pathname without a drive is set:
  12104. * * a.setAttribute('href', '/foo')
  12105. * * a.pathname === '/C:/foo' //true
  12106. *
  12107. * Inside of Angular, we're always using pathnames that
  12108. * do not include drive names for routing.
  12109. */
  12110. function removeWindowsDriveName(path, url, base) {
  12111. /*
  12112. Matches paths for file protocol on windows,
  12113. such as /C:/foo/bar, and captures only /foo/bar.
  12114. */
  12115. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  12116. var firstPathSegmentMatch;
  12117. //Get the relative path from the input URL.
  12118. if (startsWith(url, base)) {
  12119. url = url.replace(base, '');
  12120. }
  12121. // The input URL intentionally contains a first path segment that ends with a colon.
  12122. if (windowsFilePathExp.exec(url)) {
  12123. return path;
  12124. }
  12125. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  12126. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  12127. }
  12128. };
  12129. /**
  12130. * Compose hashbang URL and update `absUrl` property
  12131. * @private
  12132. */
  12133. this.$$compose = function() {
  12134. var search = toKeyValue(this.$$search),
  12135. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12136. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12137. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  12138. this.$$urlUpdatedByLocation = true;
  12139. };
  12140. this.$$parseLinkUrl = function(url, relHref) {
  12141. if (stripHash(appBase) === stripHash(url)) {
  12142. this.$$parse(url);
  12143. return true;
  12144. }
  12145. return false;
  12146. };
  12147. }
  12148. /**
  12149. * LocationHashbangUrl represents URL
  12150. * This object is exposed as $location service when html5 history api is enabled but the browser
  12151. * does not support it.
  12152. *
  12153. * @constructor
  12154. * @param {string} appBase application base URL
  12155. * @param {string} appBaseNoFile application base URL stripped of any filename
  12156. * @param {string} hashPrefix hashbang prefix
  12157. */
  12158. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  12159. this.$$html5 = true;
  12160. LocationHashbangUrl.apply(this, arguments);
  12161. this.$$parseLinkUrl = function(url, relHref) {
  12162. if (relHref && relHref[0] === '#') {
  12163. // special case for links to hash fragments:
  12164. // keep the old url and only replace the hash fragment
  12165. this.hash(relHref.slice(1));
  12166. return true;
  12167. }
  12168. var rewrittenUrl;
  12169. var appUrl;
  12170. if (appBase === stripHash(url)) {
  12171. rewrittenUrl = url;
  12172. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12173. rewrittenUrl = appBase + hashPrefix + appUrl;
  12174. } else if (appBaseNoFile === url + '/') {
  12175. rewrittenUrl = appBaseNoFile;
  12176. }
  12177. if (rewrittenUrl) {
  12178. this.$$parse(rewrittenUrl);
  12179. }
  12180. return !!rewrittenUrl;
  12181. };
  12182. this.$$compose = function() {
  12183. var search = toKeyValue(this.$$search),
  12184. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12185. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12186. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  12187. this.$$absUrl = appBase + hashPrefix + this.$$url;
  12188. this.$$urlUpdatedByLocation = true;
  12189. };
  12190. }
  12191. var locationPrototype = {
  12192. /**
  12193. * Ensure absolute URL is initialized.
  12194. * @private
  12195. */
  12196. $$absUrl:'',
  12197. /**
  12198. * Are we in html5 mode?
  12199. * @private
  12200. */
  12201. $$html5: false,
  12202. /**
  12203. * Has any change been replacing?
  12204. * @private
  12205. */
  12206. $$replace: false,
  12207. /**
  12208. * @ngdoc method
  12209. * @name $location#absUrl
  12210. *
  12211. * @description
  12212. * This method is getter only.
  12213. *
  12214. * Return full URL representation with all segments encoded according to rules specified in
  12215. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  12216. *
  12217. *
  12218. * ```js
  12219. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12220. * var absUrl = $location.absUrl();
  12221. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  12222. * ```
  12223. *
  12224. * @return {string} full URL
  12225. */
  12226. absUrl: locationGetter('$$absUrl'),
  12227. /**
  12228. * @ngdoc method
  12229. * @name $location#url
  12230. *
  12231. * @description
  12232. * This method is getter / setter.
  12233. *
  12234. * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
  12235. *
  12236. * Change path, search and hash, when called with parameter and return `$location`.
  12237. *
  12238. *
  12239. * ```js
  12240. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12241. * var url = $location.url();
  12242. * // => "/some/path?foo=bar&baz=xoxo"
  12243. * ```
  12244. *
  12245. * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
  12246. * @return {string} url
  12247. */
  12248. url: function(url) {
  12249. if (isUndefined(url)) {
  12250. return this.$$url;
  12251. }
  12252. var match = PATH_MATCH.exec(url);
  12253. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  12254. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  12255. this.hash(match[5] || '');
  12256. return this;
  12257. },
  12258. /**
  12259. * @ngdoc method
  12260. * @name $location#protocol
  12261. *
  12262. * @description
  12263. * This method is getter only.
  12264. *
  12265. * Return protocol of current URL.
  12266. *
  12267. *
  12268. * ```js
  12269. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12270. * var protocol = $location.protocol();
  12271. * // => "http"
  12272. * ```
  12273. *
  12274. * @return {string} protocol of current URL
  12275. */
  12276. protocol: locationGetter('$$protocol'),
  12277. /**
  12278. * @ngdoc method
  12279. * @name $location#host
  12280. *
  12281. * @description
  12282. * This method is getter only.
  12283. *
  12284. * Return host of current URL.
  12285. *
  12286. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  12287. *
  12288. *
  12289. * ```js
  12290. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12291. * var host = $location.host();
  12292. * // => "example.com"
  12293. *
  12294. * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  12295. * host = $location.host();
  12296. * // => "example.com"
  12297. * host = location.host;
  12298. * // => "example.com:8080"
  12299. * ```
  12300. *
  12301. * @return {string} host of current URL.
  12302. */
  12303. host: locationGetter('$$host'),
  12304. /**
  12305. * @ngdoc method
  12306. * @name $location#port
  12307. *
  12308. * @description
  12309. * This method is getter only.
  12310. *
  12311. * Return port of current URL.
  12312. *
  12313. *
  12314. * ```js
  12315. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12316. * var port = $location.port();
  12317. * // => 80
  12318. * ```
  12319. *
  12320. * @return {Number} port
  12321. */
  12322. port: locationGetter('$$port'),
  12323. /**
  12324. * @ngdoc method
  12325. * @name $location#path
  12326. *
  12327. * @description
  12328. * This method is getter / setter.
  12329. *
  12330. * Return path of current URL when called without any parameter.
  12331. *
  12332. * Change path when called with parameter and return `$location`.
  12333. *
  12334. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  12335. * if it is missing.
  12336. *
  12337. *
  12338. * ```js
  12339. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12340. * var path = $location.path();
  12341. * // => "/some/path"
  12342. * ```
  12343. *
  12344. * @param {(string|number)=} path New path
  12345. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  12346. */
  12347. path: locationGetterSetter('$$path', function(path) {
  12348. path = path !== null ? path.toString() : '';
  12349. return path.charAt(0) === '/' ? path : '/' + path;
  12350. }),
  12351. /**
  12352. * @ngdoc method
  12353. * @name $location#search
  12354. *
  12355. * @description
  12356. * This method is getter / setter.
  12357. *
  12358. * Return search part (as object) of current URL when called without any parameter.
  12359. *
  12360. * Change search part when called with parameter and return `$location`.
  12361. *
  12362. *
  12363. * ```js
  12364. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12365. * var searchObject = $location.search();
  12366. * // => {foo: 'bar', baz: 'xoxo'}
  12367. *
  12368. * // set foo to 'yipee'
  12369. * $location.search('foo', 'yipee');
  12370. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  12371. * ```
  12372. *
  12373. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  12374. * hash object.
  12375. *
  12376. * When called with a single argument the method acts as a setter, setting the `search` component
  12377. * of `$location` to the specified value.
  12378. *
  12379. * If the argument is a hash object containing an array of values, these values will be encoded
  12380. * as duplicate search parameters in the URL.
  12381. *
  12382. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  12383. * will override only a single search property.
  12384. *
  12385. * If `paramValue` is an array, it will override the property of the `search` component of
  12386. * `$location` specified via the first argument.
  12387. *
  12388. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  12389. *
  12390. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  12391. * value nor trailing equal sign.
  12392. *
  12393. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  12394. * one or more arguments returns `$location` object itself.
  12395. */
  12396. search: function(search, paramValue) {
  12397. switch (arguments.length) {
  12398. case 0:
  12399. return this.$$search;
  12400. case 1:
  12401. if (isString(search) || isNumber(search)) {
  12402. search = search.toString();
  12403. this.$$search = parseKeyValue(search);
  12404. } else if (isObject(search)) {
  12405. search = copy(search, {});
  12406. // remove object undefined or null properties
  12407. forEach(search, function(value, key) {
  12408. if (value == null) delete search[key];
  12409. });
  12410. this.$$search = search;
  12411. } else {
  12412. throw $locationMinErr('isrcharg',
  12413. 'The first argument of the `$location#search()` call must be a string or an object.');
  12414. }
  12415. break;
  12416. default:
  12417. if (isUndefined(paramValue) || paramValue === null) {
  12418. delete this.$$search[search];
  12419. } else {
  12420. this.$$search[search] = paramValue;
  12421. }
  12422. }
  12423. this.$$compose();
  12424. return this;
  12425. },
  12426. /**
  12427. * @ngdoc method
  12428. * @name $location#hash
  12429. *
  12430. * @description
  12431. * This method is getter / setter.
  12432. *
  12433. * Returns the hash fragment when called without any parameters.
  12434. *
  12435. * Changes the hash fragment when called with a parameter and returns `$location`.
  12436. *
  12437. *
  12438. * ```js
  12439. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  12440. * var hash = $location.hash();
  12441. * // => "hashValue"
  12442. * ```
  12443. *
  12444. * @param {(string|number)=} hash New hash fragment
  12445. * @return {string} hash
  12446. */
  12447. hash: locationGetterSetter('$$hash', function(hash) {
  12448. return hash !== null ? hash.toString() : '';
  12449. }),
  12450. /**
  12451. * @ngdoc method
  12452. * @name $location#replace
  12453. *
  12454. * @description
  12455. * If called, all changes to $location during the current `$digest` will replace the current history
  12456. * record, instead of adding a new one.
  12457. */
  12458. replace: function() {
  12459. this.$$replace = true;
  12460. return this;
  12461. }
  12462. };
  12463. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  12464. Location.prototype = Object.create(locationPrototype);
  12465. /**
  12466. * @ngdoc method
  12467. * @name $location#state
  12468. *
  12469. * @description
  12470. * This method is getter / setter.
  12471. *
  12472. * Return the history state object when called without any parameter.
  12473. *
  12474. * Change the history state object when called with one parameter and return `$location`.
  12475. * The state object is later passed to `pushState` or `replaceState`.
  12476. *
  12477. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  12478. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  12479. * older browsers (like IE9 or Android < 4.0), don't use this method.
  12480. *
  12481. * @param {object=} state State object for pushState or replaceState
  12482. * @return {object} state
  12483. */
  12484. Location.prototype.state = function(state) {
  12485. if (!arguments.length) {
  12486. return this.$$state;
  12487. }
  12488. if (Location !== LocationHtml5Url || !this.$$html5) {
  12489. throw $locationMinErr('nostate', 'History API state support is available only ' +
  12490. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  12491. }
  12492. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  12493. // but we're changing the $$state reference to $browser.state() during the $digest
  12494. // so the modification window is narrow.
  12495. this.$$state = isUndefined(state) ? null : state;
  12496. this.$$urlUpdatedByLocation = true;
  12497. return this;
  12498. };
  12499. });
  12500. function locationGetter(property) {
  12501. return /** @this */ function() {
  12502. return this[property];
  12503. };
  12504. }
  12505. function locationGetterSetter(property, preprocess) {
  12506. return /** @this */ function(value) {
  12507. if (isUndefined(value)) {
  12508. return this[property];
  12509. }
  12510. this[property] = preprocess(value);
  12511. this.$$compose();
  12512. return this;
  12513. };
  12514. }
  12515. /**
  12516. * @ngdoc service
  12517. * @name $location
  12518. *
  12519. * @requires $rootElement
  12520. *
  12521. * @description
  12522. * The $location service parses the URL in the browser address bar (based on the
  12523. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  12524. * available to your application. Changes to the URL in the address bar are reflected into
  12525. * $location service and changes to $location are reflected into the browser address bar.
  12526. *
  12527. * **The $location service:**
  12528. *
  12529. * - Exposes the current URL in the browser address bar, so you can
  12530. * - Watch and observe the URL.
  12531. * - Change the URL.
  12532. * - Synchronizes the URL with the browser when the user
  12533. * - Changes the address bar.
  12534. * - Clicks the back or forward button (or clicks a History link).
  12535. * - Clicks on a link.
  12536. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  12537. *
  12538. * For more information see {@link guide/$location Developer Guide: Using $location}
  12539. */
  12540. /**
  12541. * @ngdoc provider
  12542. * @name $locationProvider
  12543. * @this
  12544. *
  12545. * @description
  12546. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  12547. */
  12548. function $LocationProvider() {
  12549. var hashPrefix = '!',
  12550. html5Mode = {
  12551. enabled: false,
  12552. requireBase: true,
  12553. rewriteLinks: true
  12554. };
  12555. /**
  12556. * @ngdoc method
  12557. * @name $locationProvider#hashPrefix
  12558. * @description
  12559. * The default value for the prefix is `'!'`.
  12560. * @param {string=} prefix Prefix for hash part (containing path and search)
  12561. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12562. */
  12563. this.hashPrefix = function(prefix) {
  12564. if (isDefined(prefix)) {
  12565. hashPrefix = prefix;
  12566. return this;
  12567. } else {
  12568. return hashPrefix;
  12569. }
  12570. };
  12571. /**
  12572. * @ngdoc method
  12573. * @name $locationProvider#html5Mode
  12574. * @description
  12575. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  12576. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  12577. * properties:
  12578. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  12579. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  12580. * support `pushState`.
  12581. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  12582. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  12583. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  12584. * See the {@link guide/$location $location guide for more information}
  12585. * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
  12586. * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
  12587. * only happen on links with an attribute that matches the given string. For example, if set
  12588. * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
  12589. * Note that [attribute name normalization](guide/directive#normalization) does not apply
  12590. * here, so `'internalLink'` will **not** match `'internal-link'`.
  12591. *
  12592. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  12593. */
  12594. this.html5Mode = function(mode) {
  12595. if (isBoolean(mode)) {
  12596. html5Mode.enabled = mode;
  12597. return this;
  12598. } else if (isObject(mode)) {
  12599. if (isBoolean(mode.enabled)) {
  12600. html5Mode.enabled = mode.enabled;
  12601. }
  12602. if (isBoolean(mode.requireBase)) {
  12603. html5Mode.requireBase = mode.requireBase;
  12604. }
  12605. if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
  12606. html5Mode.rewriteLinks = mode.rewriteLinks;
  12607. }
  12608. return this;
  12609. } else {
  12610. return html5Mode;
  12611. }
  12612. };
  12613. /**
  12614. * @ngdoc event
  12615. * @name $location#$locationChangeStart
  12616. * @eventType broadcast on root scope
  12617. * @description
  12618. * Broadcasted before a URL will change.
  12619. *
  12620. * This change can be prevented by calling
  12621. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  12622. * details about event object. Upon successful change
  12623. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  12624. *
  12625. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12626. * the browser supports the HTML5 History API.
  12627. *
  12628. * @param {Object} angularEvent Synthetic event object.
  12629. * @param {string} newUrl New URL
  12630. * @param {string=} oldUrl URL that was before it was changed.
  12631. * @param {string=} newState New history state object
  12632. * @param {string=} oldState History state object that was before it was changed.
  12633. */
  12634. /**
  12635. * @ngdoc event
  12636. * @name $location#$locationChangeSuccess
  12637. * @eventType broadcast on root scope
  12638. * @description
  12639. * Broadcasted after a URL was changed.
  12640. *
  12641. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12642. * the browser supports the HTML5 History API.
  12643. *
  12644. * @param {Object} angularEvent Synthetic event object.
  12645. * @param {string} newUrl New URL
  12646. * @param {string=} oldUrl URL that was before it was changed.
  12647. * @param {string=} newState New history state object
  12648. * @param {string=} oldState History state object that was before it was changed.
  12649. */
  12650. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  12651. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  12652. var $location,
  12653. LocationMode,
  12654. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  12655. initialUrl = $browser.url(),
  12656. appBase;
  12657. if (html5Mode.enabled) {
  12658. if (!baseHref && html5Mode.requireBase) {
  12659. throw $locationMinErr('nobase',
  12660. '$location in HTML5 mode requires a <base> tag to be present!');
  12661. }
  12662. appBase = serverBase(initialUrl) + (baseHref || '/');
  12663. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  12664. } else {
  12665. appBase = stripHash(initialUrl);
  12666. LocationMode = LocationHashbangUrl;
  12667. }
  12668. var appBaseNoFile = stripFile(appBase);
  12669. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  12670. $location.$$parseLinkUrl(initialUrl, initialUrl);
  12671. $location.$$state = $browser.state();
  12672. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  12673. function setBrowserUrlWithFallback(url, replace, state) {
  12674. var oldUrl = $location.url();
  12675. var oldState = $location.$$state;
  12676. try {
  12677. $browser.url(url, replace, state);
  12678. // Make sure $location.state() returns referentially identical (not just deeply equal)
  12679. // state object; this makes possible quick checking if the state changed in the digest
  12680. // loop. Checking deep equality would be too expensive.
  12681. $location.$$state = $browser.state();
  12682. } catch (e) {
  12683. // Restore old values if pushState fails
  12684. $location.url(oldUrl);
  12685. $location.$$state = oldState;
  12686. throw e;
  12687. }
  12688. }
  12689. $rootElement.on('click', function(event) {
  12690. var rewriteLinks = html5Mode.rewriteLinks;
  12691. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  12692. // currently we open nice url link and redirect then
  12693. if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
  12694. var elm = jqLite(event.target);
  12695. // traverse the DOM up to find first A tag
  12696. while (nodeName_(elm[0]) !== 'a') {
  12697. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  12698. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  12699. }
  12700. if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
  12701. var absHref = elm.prop('href');
  12702. // get the actual href attribute - see
  12703. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  12704. var relHref = elm.attr('href') || elm.attr('xlink:href');
  12705. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  12706. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  12707. // an animation.
  12708. absHref = urlResolve(absHref.animVal).href;
  12709. }
  12710. // Ignore when url is started with javascript: or mailto:
  12711. if (IGNORE_URI_REGEXP.test(absHref)) return;
  12712. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  12713. if ($location.$$parseLinkUrl(absHref, relHref)) {
  12714. // We do a preventDefault for all urls that are part of the angular application,
  12715. // in html5mode and also without, so that we are able to abort navigation without
  12716. // getting double entries in the location history.
  12717. event.preventDefault();
  12718. // update location manually
  12719. if ($location.absUrl() !== $browser.url()) {
  12720. $rootScope.$apply();
  12721. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  12722. $window.angular['ff-684208-preventDefault'] = true;
  12723. }
  12724. }
  12725. }
  12726. });
  12727. // rewrite hashbang url <> html5 url
  12728. if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {
  12729. $browser.url($location.absUrl(), true);
  12730. }
  12731. var initializing = true;
  12732. // update $location when $browser url changes
  12733. $browser.onUrlChange(function(newUrl, newState) {
  12734. if (!startsWith(newUrl, appBaseNoFile)) {
  12735. // If we are navigating outside of the app then force a reload
  12736. $window.location.href = newUrl;
  12737. return;
  12738. }
  12739. $rootScope.$evalAsync(function() {
  12740. var oldUrl = $location.absUrl();
  12741. var oldState = $location.$$state;
  12742. var defaultPrevented;
  12743. newUrl = trimEmptyHash(newUrl);
  12744. $location.$$parse(newUrl);
  12745. $location.$$state = newState;
  12746. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12747. newState, oldState).defaultPrevented;
  12748. // if the location was changed by a `$locationChangeStart` handler then stop
  12749. // processing this location change
  12750. if ($location.absUrl() !== newUrl) return;
  12751. if (defaultPrevented) {
  12752. $location.$$parse(oldUrl);
  12753. $location.$$state = oldState;
  12754. setBrowserUrlWithFallback(oldUrl, false, oldState);
  12755. } else {
  12756. initializing = false;
  12757. afterLocationChange(oldUrl, oldState);
  12758. }
  12759. });
  12760. if (!$rootScope.$$phase) $rootScope.$digest();
  12761. });
  12762. // update browser
  12763. $rootScope.$watch(function $locationWatch() {
  12764. if (initializing || $location.$$urlUpdatedByLocation) {
  12765. $location.$$urlUpdatedByLocation = false;
  12766. var oldUrl = trimEmptyHash($browser.url());
  12767. var newUrl = trimEmptyHash($location.absUrl());
  12768. var oldState = $browser.state();
  12769. var currentReplace = $location.$$replace;
  12770. var urlOrStateChanged = oldUrl !== newUrl ||
  12771. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  12772. if (initializing || urlOrStateChanged) {
  12773. initializing = false;
  12774. $rootScope.$evalAsync(function() {
  12775. var newUrl = $location.absUrl();
  12776. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12777. $location.$$state, oldState).defaultPrevented;
  12778. // if the location was changed by a `$locationChangeStart` handler then stop
  12779. // processing this location change
  12780. if ($location.absUrl() !== newUrl) return;
  12781. if (defaultPrevented) {
  12782. $location.$$parse(oldUrl);
  12783. $location.$$state = oldState;
  12784. } else {
  12785. if (urlOrStateChanged) {
  12786. setBrowserUrlWithFallback(newUrl, currentReplace,
  12787. oldState === $location.$$state ? null : $location.$$state);
  12788. }
  12789. afterLocationChange(oldUrl, oldState);
  12790. }
  12791. });
  12792. }
  12793. }
  12794. $location.$$replace = false;
  12795. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  12796. // there is a change
  12797. });
  12798. return $location;
  12799. function afterLocationChange(oldUrl, oldState) {
  12800. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  12801. $location.$$state, oldState);
  12802. }
  12803. }];
  12804. }
  12805. /**
  12806. * @ngdoc service
  12807. * @name $log
  12808. * @requires $window
  12809. *
  12810. * @description
  12811. * Simple service for logging. Default implementation safely writes the message
  12812. * into the browser's console (if present).
  12813. *
  12814. * The main purpose of this service is to simplify debugging and troubleshooting.
  12815. *
  12816. * The default is to log `debug` messages. You can use
  12817. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  12818. *
  12819. * @example
  12820. <example module="logExample" name="log-service">
  12821. <file name="script.js">
  12822. angular.module('logExample', [])
  12823. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  12824. $scope.$log = $log;
  12825. $scope.message = 'Hello World!';
  12826. }]);
  12827. </file>
  12828. <file name="index.html">
  12829. <div ng-controller="LogController">
  12830. <p>Reload this page with open console, enter text and hit the log button...</p>
  12831. <label>Message:
  12832. <input type="text" ng-model="message" /></label>
  12833. <button ng-click="$log.log(message)">log</button>
  12834. <button ng-click="$log.warn(message)">warn</button>
  12835. <button ng-click="$log.info(message)">info</button>
  12836. <button ng-click="$log.error(message)">error</button>
  12837. <button ng-click="$log.debug(message)">debug</button>
  12838. </div>
  12839. </file>
  12840. </example>
  12841. */
  12842. /**
  12843. * @ngdoc provider
  12844. * @name $logProvider
  12845. * @this
  12846. *
  12847. * @description
  12848. * Use the `$logProvider` to configure how the application logs messages
  12849. */
  12850. function $LogProvider() {
  12851. var debug = true,
  12852. self = this;
  12853. /**
  12854. * @ngdoc method
  12855. * @name $logProvider#debugEnabled
  12856. * @description
  12857. * @param {boolean=} flag enable or disable debug level messages
  12858. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12859. */
  12860. this.debugEnabled = function(flag) {
  12861. if (isDefined(flag)) {
  12862. debug = flag;
  12863. return this;
  12864. } else {
  12865. return debug;
  12866. }
  12867. };
  12868. this.$get = ['$window', function($window) {
  12869. return {
  12870. /**
  12871. * @ngdoc method
  12872. * @name $log#log
  12873. *
  12874. * @description
  12875. * Write a log message
  12876. */
  12877. log: consoleLog('log'),
  12878. /**
  12879. * @ngdoc method
  12880. * @name $log#info
  12881. *
  12882. * @description
  12883. * Write an information message
  12884. */
  12885. info: consoleLog('info'),
  12886. /**
  12887. * @ngdoc method
  12888. * @name $log#warn
  12889. *
  12890. * @description
  12891. * Write a warning message
  12892. */
  12893. warn: consoleLog('warn'),
  12894. /**
  12895. * @ngdoc method
  12896. * @name $log#error
  12897. *
  12898. * @description
  12899. * Write an error message
  12900. */
  12901. error: consoleLog('error'),
  12902. /**
  12903. * @ngdoc method
  12904. * @name $log#debug
  12905. *
  12906. * @description
  12907. * Write a debug message
  12908. */
  12909. debug: (function() {
  12910. var fn = consoleLog('debug');
  12911. return function() {
  12912. if (debug) {
  12913. fn.apply(self, arguments);
  12914. }
  12915. };
  12916. })()
  12917. };
  12918. function formatError(arg) {
  12919. if (arg instanceof Error) {
  12920. if (arg.stack) {
  12921. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  12922. ? 'Error: ' + arg.message + '\n' + arg.stack
  12923. : arg.stack;
  12924. } else if (arg.sourceURL) {
  12925. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  12926. }
  12927. }
  12928. return arg;
  12929. }
  12930. function consoleLog(type) {
  12931. var console = $window.console || {},
  12932. logFn = console[type] || console.log || noop,
  12933. hasApply = false;
  12934. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  12935. // The reason behind this is that console.log has type "object" in IE8...
  12936. try {
  12937. hasApply = !!logFn.apply;
  12938. } catch (e) { /* empty */ }
  12939. if (hasApply) {
  12940. return function() {
  12941. var args = [];
  12942. forEach(arguments, function(arg) {
  12943. args.push(formatError(arg));
  12944. });
  12945. return logFn.apply(console, args);
  12946. };
  12947. }
  12948. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  12949. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  12950. return function(arg1, arg2) {
  12951. logFn(arg1, arg2 == null ? '' : arg2);
  12952. };
  12953. }
  12954. }];
  12955. }
  12956. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  12957. * Any commits to this file should be reviewed with security in mind. *
  12958. * Changes to this file can potentially create security vulnerabilities. *
  12959. * An approval from 2 Core members with history of modifying *
  12960. * this file is required. *
  12961. * *
  12962. * Does the change somehow allow for arbitrary javascript to be executed? *
  12963. * Or allows for someone to change the prototype of built-in objects? *
  12964. * Or gives undesired access to variables likes document or window? *
  12965. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  12966. var $parseMinErr = minErr('$parse');
  12967. var objectValueOf = {}.constructor.prototype.valueOf;
  12968. // Sandboxing Angular Expressions
  12969. // ------------------------------
  12970. // Angular expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by
  12971. // various means such as obtaining a reference to native JS functions like the Function constructor.
  12972. //
  12973. // As an example, consider the following Angular expression:
  12974. //
  12975. // {}.toString.constructor('alert("evil JS code")')
  12976. //
  12977. // It is important to realize that if you create an expression from a string that contains user provided
  12978. // content then it is possible that your application contains a security vulnerability to an XSS style attack.
  12979. //
  12980. // See https://docs.angularjs.org/guide/security
  12981. function getStringValue(name) {
  12982. // Property names must be strings. This means that non-string objects cannot be used
  12983. // as keys in an object. Any non-string object, including a number, is typecasted
  12984. // into a string via the toString method.
  12985. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  12986. //
  12987. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  12988. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  12989. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  12990. //
  12991. // TypeError: Cannot convert object to primitive value
  12992. //
  12993. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  12994. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  12995. // such a 'broken' object as a key.
  12996. return name + '';
  12997. }
  12998. var OPERATORS = createMap();
  12999. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  13000. var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
  13001. /////////////////////////////////////////
  13002. /**
  13003. * @constructor
  13004. */
  13005. var Lexer = function Lexer(options) {
  13006. this.options = options;
  13007. };
  13008. Lexer.prototype = {
  13009. constructor: Lexer,
  13010. lex: function(text) {
  13011. this.text = text;
  13012. this.index = 0;
  13013. this.tokens = [];
  13014. while (this.index < this.text.length) {
  13015. var ch = this.text.charAt(this.index);
  13016. if (ch === '"' || ch === '\'') {
  13017. this.readString(ch);
  13018. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  13019. this.readNumber();
  13020. } else if (this.isIdentifierStart(this.peekMultichar())) {
  13021. this.readIdent();
  13022. } else if (this.is(ch, '(){}[].,;:?')) {
  13023. this.tokens.push({index: this.index, text: ch});
  13024. this.index++;
  13025. } else if (this.isWhitespace(ch)) {
  13026. this.index++;
  13027. } else {
  13028. var ch2 = ch + this.peek();
  13029. var ch3 = ch2 + this.peek(2);
  13030. var op1 = OPERATORS[ch];
  13031. var op2 = OPERATORS[ch2];
  13032. var op3 = OPERATORS[ch3];
  13033. if (op1 || op2 || op3) {
  13034. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  13035. this.tokens.push({index: this.index, text: token, operator: true});
  13036. this.index += token.length;
  13037. } else {
  13038. this.throwError('Unexpected next character ', this.index, this.index + 1);
  13039. }
  13040. }
  13041. }
  13042. return this.tokens;
  13043. },
  13044. is: function(ch, chars) {
  13045. return chars.indexOf(ch) !== -1;
  13046. },
  13047. peek: function(i) {
  13048. var num = i || 1;
  13049. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  13050. },
  13051. isNumber: function(ch) {
  13052. return ('0' <= ch && ch <= '9') && typeof ch === 'string';
  13053. },
  13054. isWhitespace: function(ch) {
  13055. // IE treats non-breaking space as \u00A0
  13056. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  13057. ch === '\n' || ch === '\v' || ch === '\u00A0');
  13058. },
  13059. isIdentifierStart: function(ch) {
  13060. return this.options.isIdentifierStart ?
  13061. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  13062. this.isValidIdentifierStart(ch);
  13063. },
  13064. isValidIdentifierStart: function(ch) {
  13065. return ('a' <= ch && ch <= 'z' ||
  13066. 'A' <= ch && ch <= 'Z' ||
  13067. '_' === ch || ch === '$');
  13068. },
  13069. isIdentifierContinue: function(ch) {
  13070. return this.options.isIdentifierContinue ?
  13071. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  13072. this.isValidIdentifierContinue(ch);
  13073. },
  13074. isValidIdentifierContinue: function(ch, cp) {
  13075. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  13076. },
  13077. codePointAt: function(ch) {
  13078. if (ch.length === 1) return ch.charCodeAt(0);
  13079. // eslint-disable-next-line no-bitwise
  13080. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  13081. },
  13082. peekMultichar: function() {
  13083. var ch = this.text.charAt(this.index);
  13084. var peek = this.peek();
  13085. if (!peek) {
  13086. return ch;
  13087. }
  13088. var cp1 = ch.charCodeAt(0);
  13089. var cp2 = peek.charCodeAt(0);
  13090. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  13091. return ch + peek;
  13092. }
  13093. return ch;
  13094. },
  13095. isExpOperator: function(ch) {
  13096. return (ch === '-' || ch === '+' || this.isNumber(ch));
  13097. },
  13098. throwError: function(error, start, end) {
  13099. end = end || this.index;
  13100. var colStr = (isDefined(start)
  13101. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  13102. : ' ' + end);
  13103. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  13104. error, colStr, this.text);
  13105. },
  13106. readNumber: function() {
  13107. var number = '';
  13108. var start = this.index;
  13109. while (this.index < this.text.length) {
  13110. var ch = lowercase(this.text.charAt(this.index));
  13111. if (ch === '.' || this.isNumber(ch)) {
  13112. number += ch;
  13113. } else {
  13114. var peekCh = this.peek();
  13115. if (ch === 'e' && this.isExpOperator(peekCh)) {
  13116. number += ch;
  13117. } else if (this.isExpOperator(ch) &&
  13118. peekCh && this.isNumber(peekCh) &&
  13119. number.charAt(number.length - 1) === 'e') {
  13120. number += ch;
  13121. } else if (this.isExpOperator(ch) &&
  13122. (!peekCh || !this.isNumber(peekCh)) &&
  13123. number.charAt(number.length - 1) === 'e') {
  13124. this.throwError('Invalid exponent');
  13125. } else {
  13126. break;
  13127. }
  13128. }
  13129. this.index++;
  13130. }
  13131. this.tokens.push({
  13132. index: start,
  13133. text: number,
  13134. constant: true,
  13135. value: Number(number)
  13136. });
  13137. },
  13138. readIdent: function() {
  13139. var start = this.index;
  13140. this.index += this.peekMultichar().length;
  13141. while (this.index < this.text.length) {
  13142. var ch = this.peekMultichar();
  13143. if (!this.isIdentifierContinue(ch)) {
  13144. break;
  13145. }
  13146. this.index += ch.length;
  13147. }
  13148. this.tokens.push({
  13149. index: start,
  13150. text: this.text.slice(start, this.index),
  13151. identifier: true
  13152. });
  13153. },
  13154. readString: function(quote) {
  13155. var start = this.index;
  13156. this.index++;
  13157. var string = '';
  13158. var rawString = quote;
  13159. var escape = false;
  13160. while (this.index < this.text.length) {
  13161. var ch = this.text.charAt(this.index);
  13162. rawString += ch;
  13163. if (escape) {
  13164. if (ch === 'u') {
  13165. var hex = this.text.substring(this.index + 1, this.index + 5);
  13166. if (!hex.match(/[\da-f]{4}/i)) {
  13167. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  13168. }
  13169. this.index += 4;
  13170. string += String.fromCharCode(parseInt(hex, 16));
  13171. } else {
  13172. var rep = ESCAPE[ch];
  13173. string = string + (rep || ch);
  13174. }
  13175. escape = false;
  13176. } else if (ch === '\\') {
  13177. escape = true;
  13178. } else if (ch === quote) {
  13179. this.index++;
  13180. this.tokens.push({
  13181. index: start,
  13182. text: rawString,
  13183. constant: true,
  13184. value: string
  13185. });
  13186. return;
  13187. } else {
  13188. string += ch;
  13189. }
  13190. this.index++;
  13191. }
  13192. this.throwError('Unterminated quote', start);
  13193. }
  13194. };
  13195. var AST = function AST(lexer, options) {
  13196. this.lexer = lexer;
  13197. this.options = options;
  13198. };
  13199. AST.Program = 'Program';
  13200. AST.ExpressionStatement = 'ExpressionStatement';
  13201. AST.AssignmentExpression = 'AssignmentExpression';
  13202. AST.ConditionalExpression = 'ConditionalExpression';
  13203. AST.LogicalExpression = 'LogicalExpression';
  13204. AST.BinaryExpression = 'BinaryExpression';
  13205. AST.UnaryExpression = 'UnaryExpression';
  13206. AST.CallExpression = 'CallExpression';
  13207. AST.MemberExpression = 'MemberExpression';
  13208. AST.Identifier = 'Identifier';
  13209. AST.Literal = 'Literal';
  13210. AST.ArrayExpression = 'ArrayExpression';
  13211. AST.Property = 'Property';
  13212. AST.ObjectExpression = 'ObjectExpression';
  13213. AST.ThisExpression = 'ThisExpression';
  13214. AST.LocalsExpression = 'LocalsExpression';
  13215. // Internal use only
  13216. AST.NGValueParameter = 'NGValueParameter';
  13217. AST.prototype = {
  13218. ast: function(text) {
  13219. this.text = text;
  13220. this.tokens = this.lexer.lex(text);
  13221. var value = this.program();
  13222. if (this.tokens.length !== 0) {
  13223. this.throwError('is an unexpected token', this.tokens[0]);
  13224. }
  13225. return value;
  13226. },
  13227. program: function() {
  13228. var body = [];
  13229. while (true) {
  13230. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  13231. body.push(this.expressionStatement());
  13232. if (!this.expect(';')) {
  13233. return { type: AST.Program, body: body};
  13234. }
  13235. }
  13236. },
  13237. expressionStatement: function() {
  13238. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  13239. },
  13240. filterChain: function() {
  13241. var left = this.expression();
  13242. while (this.expect('|')) {
  13243. left = this.filter(left);
  13244. }
  13245. return left;
  13246. },
  13247. expression: function() {
  13248. return this.assignment();
  13249. },
  13250. assignment: function() {
  13251. var result = this.ternary();
  13252. if (this.expect('=')) {
  13253. if (!isAssignable(result)) {
  13254. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  13255. }
  13256. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  13257. }
  13258. return result;
  13259. },
  13260. ternary: function() {
  13261. var test = this.logicalOR();
  13262. var alternate;
  13263. var consequent;
  13264. if (this.expect('?')) {
  13265. alternate = this.expression();
  13266. if (this.consume(':')) {
  13267. consequent = this.expression();
  13268. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  13269. }
  13270. }
  13271. return test;
  13272. },
  13273. logicalOR: function() {
  13274. var left = this.logicalAND();
  13275. while (this.expect('||')) {
  13276. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  13277. }
  13278. return left;
  13279. },
  13280. logicalAND: function() {
  13281. var left = this.equality();
  13282. while (this.expect('&&')) {
  13283. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  13284. }
  13285. return left;
  13286. },
  13287. equality: function() {
  13288. var left = this.relational();
  13289. var token;
  13290. while ((token = this.expect('==','!=','===','!=='))) {
  13291. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  13292. }
  13293. return left;
  13294. },
  13295. relational: function() {
  13296. var left = this.additive();
  13297. var token;
  13298. while ((token = this.expect('<', '>', '<=', '>='))) {
  13299. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  13300. }
  13301. return left;
  13302. },
  13303. additive: function() {
  13304. var left = this.multiplicative();
  13305. var token;
  13306. while ((token = this.expect('+','-'))) {
  13307. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  13308. }
  13309. return left;
  13310. },
  13311. multiplicative: function() {
  13312. var left = this.unary();
  13313. var token;
  13314. while ((token = this.expect('*','/','%'))) {
  13315. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  13316. }
  13317. return left;
  13318. },
  13319. unary: function() {
  13320. var token;
  13321. if ((token = this.expect('+', '-', '!'))) {
  13322. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  13323. } else {
  13324. return this.primary();
  13325. }
  13326. },
  13327. primary: function() {
  13328. var primary;
  13329. if (this.expect('(')) {
  13330. primary = this.filterChain();
  13331. this.consume(')');
  13332. } else if (this.expect('[')) {
  13333. primary = this.arrayDeclaration();
  13334. } else if (this.expect('{')) {
  13335. primary = this.object();
  13336. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  13337. primary = copy(this.selfReferential[this.consume().text]);
  13338. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  13339. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  13340. } else if (this.peek().identifier) {
  13341. primary = this.identifier();
  13342. } else if (this.peek().constant) {
  13343. primary = this.constant();
  13344. } else {
  13345. this.throwError('not a primary expression', this.peek());
  13346. }
  13347. var next;
  13348. while ((next = this.expect('(', '[', '.'))) {
  13349. if (next.text === '(') {
  13350. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  13351. this.consume(')');
  13352. } else if (next.text === '[') {
  13353. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  13354. this.consume(']');
  13355. } else if (next.text === '.') {
  13356. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  13357. } else {
  13358. this.throwError('IMPOSSIBLE');
  13359. }
  13360. }
  13361. return primary;
  13362. },
  13363. filter: function(baseExpression) {
  13364. var args = [baseExpression];
  13365. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  13366. while (this.expect(':')) {
  13367. args.push(this.expression());
  13368. }
  13369. return result;
  13370. },
  13371. parseArguments: function() {
  13372. var args = [];
  13373. if (this.peekToken().text !== ')') {
  13374. do {
  13375. args.push(this.filterChain());
  13376. } while (this.expect(','));
  13377. }
  13378. return args;
  13379. },
  13380. identifier: function() {
  13381. var token = this.consume();
  13382. if (!token.identifier) {
  13383. this.throwError('is not a valid identifier', token);
  13384. }
  13385. return { type: AST.Identifier, name: token.text };
  13386. },
  13387. constant: function() {
  13388. // TODO check that it is a constant
  13389. return { type: AST.Literal, value: this.consume().value };
  13390. },
  13391. arrayDeclaration: function() {
  13392. var elements = [];
  13393. if (this.peekToken().text !== ']') {
  13394. do {
  13395. if (this.peek(']')) {
  13396. // Support trailing commas per ES5.1.
  13397. break;
  13398. }
  13399. elements.push(this.expression());
  13400. } while (this.expect(','));
  13401. }
  13402. this.consume(']');
  13403. return { type: AST.ArrayExpression, elements: elements };
  13404. },
  13405. object: function() {
  13406. var properties = [], property;
  13407. if (this.peekToken().text !== '}') {
  13408. do {
  13409. if (this.peek('}')) {
  13410. // Support trailing commas per ES5.1.
  13411. break;
  13412. }
  13413. property = {type: AST.Property, kind: 'init'};
  13414. if (this.peek().constant) {
  13415. property.key = this.constant();
  13416. property.computed = false;
  13417. this.consume(':');
  13418. property.value = this.expression();
  13419. } else if (this.peek().identifier) {
  13420. property.key = this.identifier();
  13421. property.computed = false;
  13422. if (this.peek(':')) {
  13423. this.consume(':');
  13424. property.value = this.expression();
  13425. } else {
  13426. property.value = property.key;
  13427. }
  13428. } else if (this.peek('[')) {
  13429. this.consume('[');
  13430. property.key = this.expression();
  13431. this.consume(']');
  13432. property.computed = true;
  13433. this.consume(':');
  13434. property.value = this.expression();
  13435. } else {
  13436. this.throwError('invalid key', this.peek());
  13437. }
  13438. properties.push(property);
  13439. } while (this.expect(','));
  13440. }
  13441. this.consume('}');
  13442. return {type: AST.ObjectExpression, properties: properties };
  13443. },
  13444. throwError: function(msg, token) {
  13445. throw $parseMinErr('syntax',
  13446. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  13447. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  13448. },
  13449. consume: function(e1) {
  13450. if (this.tokens.length === 0) {
  13451. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13452. }
  13453. var token = this.expect(e1);
  13454. if (!token) {
  13455. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  13456. }
  13457. return token;
  13458. },
  13459. peekToken: function() {
  13460. if (this.tokens.length === 0) {
  13461. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13462. }
  13463. return this.tokens[0];
  13464. },
  13465. peek: function(e1, e2, e3, e4) {
  13466. return this.peekAhead(0, e1, e2, e3, e4);
  13467. },
  13468. peekAhead: function(i, e1, e2, e3, e4) {
  13469. if (this.tokens.length > i) {
  13470. var token = this.tokens[i];
  13471. var t = token.text;
  13472. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  13473. (!e1 && !e2 && !e3 && !e4)) {
  13474. return token;
  13475. }
  13476. }
  13477. return false;
  13478. },
  13479. expect: function(e1, e2, e3, e4) {
  13480. var token = this.peek(e1, e2, e3, e4);
  13481. if (token) {
  13482. this.tokens.shift();
  13483. return token;
  13484. }
  13485. return false;
  13486. },
  13487. selfReferential: {
  13488. 'this': {type: AST.ThisExpression },
  13489. '$locals': {type: AST.LocalsExpression }
  13490. }
  13491. };
  13492. function ifDefined(v, d) {
  13493. return typeof v !== 'undefined' ? v : d;
  13494. }
  13495. function plusFn(l, r) {
  13496. if (typeof l === 'undefined') return r;
  13497. if (typeof r === 'undefined') return l;
  13498. return l + r;
  13499. }
  13500. function isStateless($filter, filterName) {
  13501. var fn = $filter(filterName);
  13502. return !fn.$stateful;
  13503. }
  13504. function findConstantAndWatchExpressions(ast, $filter) {
  13505. var allConstants;
  13506. var argsToWatch;
  13507. var isStatelessFilter;
  13508. switch (ast.type) {
  13509. case AST.Program:
  13510. allConstants = true;
  13511. forEach(ast.body, function(expr) {
  13512. findConstantAndWatchExpressions(expr.expression, $filter);
  13513. allConstants = allConstants && expr.expression.constant;
  13514. });
  13515. ast.constant = allConstants;
  13516. break;
  13517. case AST.Literal:
  13518. ast.constant = true;
  13519. ast.toWatch = [];
  13520. break;
  13521. case AST.UnaryExpression:
  13522. findConstantAndWatchExpressions(ast.argument, $filter);
  13523. ast.constant = ast.argument.constant;
  13524. ast.toWatch = ast.argument.toWatch;
  13525. break;
  13526. case AST.BinaryExpression:
  13527. findConstantAndWatchExpressions(ast.left, $filter);
  13528. findConstantAndWatchExpressions(ast.right, $filter);
  13529. ast.constant = ast.left.constant && ast.right.constant;
  13530. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  13531. break;
  13532. case AST.LogicalExpression:
  13533. findConstantAndWatchExpressions(ast.left, $filter);
  13534. findConstantAndWatchExpressions(ast.right, $filter);
  13535. ast.constant = ast.left.constant && ast.right.constant;
  13536. ast.toWatch = ast.constant ? [] : [ast];
  13537. break;
  13538. case AST.ConditionalExpression:
  13539. findConstantAndWatchExpressions(ast.test, $filter);
  13540. findConstantAndWatchExpressions(ast.alternate, $filter);
  13541. findConstantAndWatchExpressions(ast.consequent, $filter);
  13542. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  13543. ast.toWatch = ast.constant ? [] : [ast];
  13544. break;
  13545. case AST.Identifier:
  13546. ast.constant = false;
  13547. ast.toWatch = [ast];
  13548. break;
  13549. case AST.MemberExpression:
  13550. findConstantAndWatchExpressions(ast.object, $filter);
  13551. if (ast.computed) {
  13552. findConstantAndWatchExpressions(ast.property, $filter);
  13553. }
  13554. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  13555. ast.toWatch = [ast];
  13556. break;
  13557. case AST.CallExpression:
  13558. isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
  13559. allConstants = isStatelessFilter;
  13560. argsToWatch = [];
  13561. forEach(ast.arguments, function(expr) {
  13562. findConstantAndWatchExpressions(expr, $filter);
  13563. allConstants = allConstants && expr.constant;
  13564. if (!expr.constant) {
  13565. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13566. }
  13567. });
  13568. ast.constant = allConstants;
  13569. ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
  13570. break;
  13571. case AST.AssignmentExpression:
  13572. findConstantAndWatchExpressions(ast.left, $filter);
  13573. findConstantAndWatchExpressions(ast.right, $filter);
  13574. ast.constant = ast.left.constant && ast.right.constant;
  13575. ast.toWatch = [ast];
  13576. break;
  13577. case AST.ArrayExpression:
  13578. allConstants = true;
  13579. argsToWatch = [];
  13580. forEach(ast.elements, function(expr) {
  13581. findConstantAndWatchExpressions(expr, $filter);
  13582. allConstants = allConstants && expr.constant;
  13583. if (!expr.constant) {
  13584. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13585. }
  13586. });
  13587. ast.constant = allConstants;
  13588. ast.toWatch = argsToWatch;
  13589. break;
  13590. case AST.ObjectExpression:
  13591. allConstants = true;
  13592. argsToWatch = [];
  13593. forEach(ast.properties, function(property) {
  13594. findConstantAndWatchExpressions(property.value, $filter);
  13595. allConstants = allConstants && property.value.constant && !property.computed;
  13596. if (!property.value.constant) {
  13597. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  13598. }
  13599. if (property.computed) {
  13600. findConstantAndWatchExpressions(property.key, $filter);
  13601. if (!property.key.constant) {
  13602. argsToWatch.push.apply(argsToWatch, property.key.toWatch);
  13603. }
  13604. }
  13605. });
  13606. ast.constant = allConstants;
  13607. ast.toWatch = argsToWatch;
  13608. break;
  13609. case AST.ThisExpression:
  13610. ast.constant = false;
  13611. ast.toWatch = [];
  13612. break;
  13613. case AST.LocalsExpression:
  13614. ast.constant = false;
  13615. ast.toWatch = [];
  13616. break;
  13617. }
  13618. }
  13619. function getInputs(body) {
  13620. if (body.length !== 1) return;
  13621. var lastExpression = body[0].expression;
  13622. var candidate = lastExpression.toWatch;
  13623. if (candidate.length !== 1) return candidate;
  13624. return candidate[0] !== lastExpression ? candidate : undefined;
  13625. }
  13626. function isAssignable(ast) {
  13627. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  13628. }
  13629. function assignableAST(ast) {
  13630. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  13631. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  13632. }
  13633. }
  13634. function isLiteral(ast) {
  13635. return ast.body.length === 0 ||
  13636. ast.body.length === 1 && (
  13637. ast.body[0].expression.type === AST.Literal ||
  13638. ast.body[0].expression.type === AST.ArrayExpression ||
  13639. ast.body[0].expression.type === AST.ObjectExpression);
  13640. }
  13641. function isConstant(ast) {
  13642. return ast.constant;
  13643. }
  13644. function ASTCompiler(astBuilder, $filter) {
  13645. this.astBuilder = astBuilder;
  13646. this.$filter = $filter;
  13647. }
  13648. ASTCompiler.prototype = {
  13649. compile: function(expression) {
  13650. var self = this;
  13651. var ast = this.astBuilder.ast(expression);
  13652. this.state = {
  13653. nextId: 0,
  13654. filters: {},
  13655. fn: {vars: [], body: [], own: {}},
  13656. assign: {vars: [], body: [], own: {}},
  13657. inputs: []
  13658. };
  13659. findConstantAndWatchExpressions(ast, self.$filter);
  13660. var extra = '';
  13661. var assignable;
  13662. this.stage = 'assign';
  13663. if ((assignable = assignableAST(ast))) {
  13664. this.state.computing = 'assign';
  13665. var result = this.nextId();
  13666. this.recurse(assignable, result);
  13667. this.return_(result);
  13668. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  13669. }
  13670. var toWatch = getInputs(ast.body);
  13671. self.stage = 'inputs';
  13672. forEach(toWatch, function(watch, key) {
  13673. var fnKey = 'fn' + key;
  13674. self.state[fnKey] = {vars: [], body: [], own: {}};
  13675. self.state.computing = fnKey;
  13676. var intoId = self.nextId();
  13677. self.recurse(watch, intoId);
  13678. self.return_(intoId);
  13679. self.state.inputs.push(fnKey);
  13680. watch.watchId = key;
  13681. });
  13682. this.state.computing = 'fn';
  13683. this.stage = 'main';
  13684. this.recurse(ast);
  13685. var fnString =
  13686. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  13687. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  13688. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  13689. this.filterPrefix() +
  13690. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  13691. extra +
  13692. this.watchFns() +
  13693. 'return fn;';
  13694. // eslint-disable-next-line no-new-func
  13695. var fn = (new Function('$filter',
  13696. 'getStringValue',
  13697. 'ifDefined',
  13698. 'plus',
  13699. fnString))(
  13700. this.$filter,
  13701. getStringValue,
  13702. ifDefined,
  13703. plusFn);
  13704. this.state = this.stage = undefined;
  13705. fn.literal = isLiteral(ast);
  13706. fn.constant = isConstant(ast);
  13707. return fn;
  13708. },
  13709. USE: 'use',
  13710. STRICT: 'strict',
  13711. watchFns: function() {
  13712. var result = [];
  13713. var fns = this.state.inputs;
  13714. var self = this;
  13715. forEach(fns, function(name) {
  13716. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  13717. });
  13718. if (fns.length) {
  13719. result.push('fn.inputs=[' + fns.join(',') + '];');
  13720. }
  13721. return result.join('');
  13722. },
  13723. generateFunction: function(name, params) {
  13724. return 'function(' + params + '){' +
  13725. this.varsPrefix(name) +
  13726. this.body(name) +
  13727. '};';
  13728. },
  13729. filterPrefix: function() {
  13730. var parts = [];
  13731. var self = this;
  13732. forEach(this.state.filters, function(id, filter) {
  13733. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  13734. });
  13735. if (parts.length) return 'var ' + parts.join(',') + ';';
  13736. return '';
  13737. },
  13738. varsPrefix: function(section) {
  13739. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  13740. },
  13741. body: function(section) {
  13742. return this.state[section].body.join('');
  13743. },
  13744. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  13745. var left, right, self = this, args, expression, computed;
  13746. recursionFn = recursionFn || noop;
  13747. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  13748. intoId = intoId || this.nextId();
  13749. this.if_('i',
  13750. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  13751. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  13752. );
  13753. return;
  13754. }
  13755. switch (ast.type) {
  13756. case AST.Program:
  13757. forEach(ast.body, function(expression, pos) {
  13758. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  13759. if (pos !== ast.body.length - 1) {
  13760. self.current().body.push(right, ';');
  13761. } else {
  13762. self.return_(right);
  13763. }
  13764. });
  13765. break;
  13766. case AST.Literal:
  13767. expression = this.escape(ast.value);
  13768. this.assign(intoId, expression);
  13769. recursionFn(intoId || expression);
  13770. break;
  13771. case AST.UnaryExpression:
  13772. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  13773. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  13774. this.assign(intoId, expression);
  13775. recursionFn(expression);
  13776. break;
  13777. case AST.BinaryExpression:
  13778. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  13779. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  13780. if (ast.operator === '+') {
  13781. expression = this.plus(left, right);
  13782. } else if (ast.operator === '-') {
  13783. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  13784. } else {
  13785. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  13786. }
  13787. this.assign(intoId, expression);
  13788. recursionFn(expression);
  13789. break;
  13790. case AST.LogicalExpression:
  13791. intoId = intoId || this.nextId();
  13792. self.recurse(ast.left, intoId);
  13793. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  13794. recursionFn(intoId);
  13795. break;
  13796. case AST.ConditionalExpression:
  13797. intoId = intoId || this.nextId();
  13798. self.recurse(ast.test, intoId);
  13799. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  13800. recursionFn(intoId);
  13801. break;
  13802. case AST.Identifier:
  13803. intoId = intoId || this.nextId();
  13804. if (nameId) {
  13805. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  13806. nameId.computed = false;
  13807. nameId.name = ast.name;
  13808. }
  13809. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  13810. function() {
  13811. self.if_(self.stage === 'inputs' || 's', function() {
  13812. if (create && create !== 1) {
  13813. self.if_(
  13814. self.isNull(self.nonComputedMember('s', ast.name)),
  13815. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  13816. }
  13817. self.assign(intoId, self.nonComputedMember('s', ast.name));
  13818. });
  13819. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  13820. );
  13821. recursionFn(intoId);
  13822. break;
  13823. case AST.MemberExpression:
  13824. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  13825. intoId = intoId || this.nextId();
  13826. self.recurse(ast.object, left, undefined, function() {
  13827. self.if_(self.notNull(left), function() {
  13828. if (ast.computed) {
  13829. right = self.nextId();
  13830. self.recurse(ast.property, right);
  13831. self.getStringValue(right);
  13832. if (create && create !== 1) {
  13833. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  13834. }
  13835. expression = self.computedMember(left, right);
  13836. self.assign(intoId, expression);
  13837. if (nameId) {
  13838. nameId.computed = true;
  13839. nameId.name = right;
  13840. }
  13841. } else {
  13842. if (create && create !== 1) {
  13843. self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  13844. }
  13845. expression = self.nonComputedMember(left, ast.property.name);
  13846. self.assign(intoId, expression);
  13847. if (nameId) {
  13848. nameId.computed = false;
  13849. nameId.name = ast.property.name;
  13850. }
  13851. }
  13852. }, function() {
  13853. self.assign(intoId, 'undefined');
  13854. });
  13855. recursionFn(intoId);
  13856. }, !!create);
  13857. break;
  13858. case AST.CallExpression:
  13859. intoId = intoId || this.nextId();
  13860. if (ast.filter) {
  13861. right = self.filter(ast.callee.name);
  13862. args = [];
  13863. forEach(ast.arguments, function(expr) {
  13864. var argument = self.nextId();
  13865. self.recurse(expr, argument);
  13866. args.push(argument);
  13867. });
  13868. expression = right + '(' + args.join(',') + ')';
  13869. self.assign(intoId, expression);
  13870. recursionFn(intoId);
  13871. } else {
  13872. right = self.nextId();
  13873. left = {};
  13874. args = [];
  13875. self.recurse(ast.callee, right, left, function() {
  13876. self.if_(self.notNull(right), function() {
  13877. forEach(ast.arguments, function(expr) {
  13878. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  13879. args.push(argument);
  13880. });
  13881. });
  13882. if (left.name) {
  13883. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  13884. } else {
  13885. expression = right + '(' + args.join(',') + ')';
  13886. }
  13887. self.assign(intoId, expression);
  13888. }, function() {
  13889. self.assign(intoId, 'undefined');
  13890. });
  13891. recursionFn(intoId);
  13892. });
  13893. }
  13894. break;
  13895. case AST.AssignmentExpression:
  13896. right = this.nextId();
  13897. left = {};
  13898. this.recurse(ast.left, undefined, left, function() {
  13899. self.if_(self.notNull(left.context), function() {
  13900. self.recurse(ast.right, right);
  13901. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  13902. self.assign(intoId, expression);
  13903. recursionFn(intoId || expression);
  13904. });
  13905. }, 1);
  13906. break;
  13907. case AST.ArrayExpression:
  13908. args = [];
  13909. forEach(ast.elements, function(expr) {
  13910. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  13911. args.push(argument);
  13912. });
  13913. });
  13914. expression = '[' + args.join(',') + ']';
  13915. this.assign(intoId, expression);
  13916. recursionFn(intoId || expression);
  13917. break;
  13918. case AST.ObjectExpression:
  13919. args = [];
  13920. computed = false;
  13921. forEach(ast.properties, function(property) {
  13922. if (property.computed) {
  13923. computed = true;
  13924. }
  13925. });
  13926. if (computed) {
  13927. intoId = intoId || this.nextId();
  13928. this.assign(intoId, '{}');
  13929. forEach(ast.properties, function(property) {
  13930. if (property.computed) {
  13931. left = self.nextId();
  13932. self.recurse(property.key, left);
  13933. } else {
  13934. left = property.key.type === AST.Identifier ?
  13935. property.key.name :
  13936. ('' + property.key.value);
  13937. }
  13938. right = self.nextId();
  13939. self.recurse(property.value, right);
  13940. self.assign(self.member(intoId, left, property.computed), right);
  13941. });
  13942. } else {
  13943. forEach(ast.properties, function(property) {
  13944. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  13945. args.push(self.escape(
  13946. property.key.type === AST.Identifier ? property.key.name :
  13947. ('' + property.key.value)) +
  13948. ':' + expr);
  13949. });
  13950. });
  13951. expression = '{' + args.join(',') + '}';
  13952. this.assign(intoId, expression);
  13953. }
  13954. recursionFn(intoId || expression);
  13955. break;
  13956. case AST.ThisExpression:
  13957. this.assign(intoId, 's');
  13958. recursionFn(intoId || 's');
  13959. break;
  13960. case AST.LocalsExpression:
  13961. this.assign(intoId, 'l');
  13962. recursionFn(intoId || 'l');
  13963. break;
  13964. case AST.NGValueParameter:
  13965. this.assign(intoId, 'v');
  13966. recursionFn(intoId || 'v');
  13967. break;
  13968. }
  13969. },
  13970. getHasOwnProperty: function(element, property) {
  13971. var key = element + '.' + property;
  13972. var own = this.current().own;
  13973. if (!own.hasOwnProperty(key)) {
  13974. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  13975. }
  13976. return own[key];
  13977. },
  13978. assign: function(id, value) {
  13979. if (!id) return;
  13980. this.current().body.push(id, '=', value, ';');
  13981. return id;
  13982. },
  13983. filter: function(filterName) {
  13984. if (!this.state.filters.hasOwnProperty(filterName)) {
  13985. this.state.filters[filterName] = this.nextId(true);
  13986. }
  13987. return this.state.filters[filterName];
  13988. },
  13989. ifDefined: function(id, defaultValue) {
  13990. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  13991. },
  13992. plus: function(left, right) {
  13993. return 'plus(' + left + ',' + right + ')';
  13994. },
  13995. return_: function(id) {
  13996. this.current().body.push('return ', id, ';');
  13997. },
  13998. if_: function(test, alternate, consequent) {
  13999. if (test === true) {
  14000. alternate();
  14001. } else {
  14002. var body = this.current().body;
  14003. body.push('if(', test, '){');
  14004. alternate();
  14005. body.push('}');
  14006. if (consequent) {
  14007. body.push('else{');
  14008. consequent();
  14009. body.push('}');
  14010. }
  14011. }
  14012. },
  14013. not: function(expression) {
  14014. return '!(' + expression + ')';
  14015. },
  14016. isNull: function(expression) {
  14017. return expression + '==null';
  14018. },
  14019. notNull: function(expression) {
  14020. return expression + '!=null';
  14021. },
  14022. nonComputedMember: function(left, right) {
  14023. var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
  14024. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  14025. if (SAFE_IDENTIFIER.test(right)) {
  14026. return left + '.' + right;
  14027. } else {
  14028. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  14029. }
  14030. },
  14031. computedMember: function(left, right) {
  14032. return left + '[' + right + ']';
  14033. },
  14034. member: function(left, right, computed) {
  14035. if (computed) return this.computedMember(left, right);
  14036. return this.nonComputedMember(left, right);
  14037. },
  14038. getStringValue: function(item) {
  14039. this.assign(item, 'getStringValue(' + item + ')');
  14040. },
  14041. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14042. var self = this;
  14043. return function() {
  14044. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  14045. };
  14046. },
  14047. lazyAssign: function(id, value) {
  14048. var self = this;
  14049. return function() {
  14050. self.assign(id, value);
  14051. };
  14052. },
  14053. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  14054. stringEscapeFn: function(c) {
  14055. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  14056. },
  14057. escape: function(value) {
  14058. if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
  14059. if (isNumber(value)) return value.toString();
  14060. if (value === true) return 'true';
  14061. if (value === false) return 'false';
  14062. if (value === null) return 'null';
  14063. if (typeof value === 'undefined') return 'undefined';
  14064. throw $parseMinErr('esc', 'IMPOSSIBLE');
  14065. },
  14066. nextId: function(skip, init) {
  14067. var id = 'v' + (this.state.nextId++);
  14068. if (!skip) {
  14069. this.current().vars.push(id + (init ? '=' + init : ''));
  14070. }
  14071. return id;
  14072. },
  14073. current: function() {
  14074. return this.state[this.state.computing];
  14075. }
  14076. };
  14077. function ASTInterpreter(astBuilder, $filter) {
  14078. this.astBuilder = astBuilder;
  14079. this.$filter = $filter;
  14080. }
  14081. ASTInterpreter.prototype = {
  14082. compile: function(expression) {
  14083. var self = this;
  14084. var ast = this.astBuilder.ast(expression);
  14085. findConstantAndWatchExpressions(ast, self.$filter);
  14086. var assignable;
  14087. var assign;
  14088. if ((assignable = assignableAST(ast))) {
  14089. assign = this.recurse(assignable);
  14090. }
  14091. var toWatch = getInputs(ast.body);
  14092. var inputs;
  14093. if (toWatch) {
  14094. inputs = [];
  14095. forEach(toWatch, function(watch, key) {
  14096. var input = self.recurse(watch);
  14097. watch.input = input;
  14098. inputs.push(input);
  14099. watch.watchId = key;
  14100. });
  14101. }
  14102. var expressions = [];
  14103. forEach(ast.body, function(expression) {
  14104. expressions.push(self.recurse(expression.expression));
  14105. });
  14106. var fn = ast.body.length === 0 ? noop :
  14107. ast.body.length === 1 ? expressions[0] :
  14108. function(scope, locals) {
  14109. var lastValue;
  14110. forEach(expressions, function(exp) {
  14111. lastValue = exp(scope, locals);
  14112. });
  14113. return lastValue;
  14114. };
  14115. if (assign) {
  14116. fn.assign = function(scope, value, locals) {
  14117. return assign(scope, locals, value);
  14118. };
  14119. }
  14120. if (inputs) {
  14121. fn.inputs = inputs;
  14122. }
  14123. fn.literal = isLiteral(ast);
  14124. fn.constant = isConstant(ast);
  14125. return fn;
  14126. },
  14127. recurse: function(ast, context, create) {
  14128. var left, right, self = this, args;
  14129. if (ast.input) {
  14130. return this.inputs(ast.input, ast.watchId);
  14131. }
  14132. switch (ast.type) {
  14133. case AST.Literal:
  14134. return this.value(ast.value, context);
  14135. case AST.UnaryExpression:
  14136. right = this.recurse(ast.argument);
  14137. return this['unary' + ast.operator](right, context);
  14138. case AST.BinaryExpression:
  14139. left = this.recurse(ast.left);
  14140. right = this.recurse(ast.right);
  14141. return this['binary' + ast.operator](left, right, context);
  14142. case AST.LogicalExpression:
  14143. left = this.recurse(ast.left);
  14144. right = this.recurse(ast.right);
  14145. return this['binary' + ast.operator](left, right, context);
  14146. case AST.ConditionalExpression:
  14147. return this['ternary?:'](
  14148. this.recurse(ast.test),
  14149. this.recurse(ast.alternate),
  14150. this.recurse(ast.consequent),
  14151. context
  14152. );
  14153. case AST.Identifier:
  14154. return self.identifier(ast.name, context, create);
  14155. case AST.MemberExpression:
  14156. left = this.recurse(ast.object, false, !!create);
  14157. if (!ast.computed) {
  14158. right = ast.property.name;
  14159. }
  14160. if (ast.computed) right = this.recurse(ast.property);
  14161. return ast.computed ?
  14162. this.computedMember(left, right, context, create) :
  14163. this.nonComputedMember(left, right, context, create);
  14164. case AST.CallExpression:
  14165. args = [];
  14166. forEach(ast.arguments, function(expr) {
  14167. args.push(self.recurse(expr));
  14168. });
  14169. if (ast.filter) right = this.$filter(ast.callee.name);
  14170. if (!ast.filter) right = this.recurse(ast.callee, true);
  14171. return ast.filter ?
  14172. function(scope, locals, assign, inputs) {
  14173. var values = [];
  14174. for (var i = 0; i < args.length; ++i) {
  14175. values.push(args[i](scope, locals, assign, inputs));
  14176. }
  14177. var value = right.apply(undefined, values, inputs);
  14178. return context ? {context: undefined, name: undefined, value: value} : value;
  14179. } :
  14180. function(scope, locals, assign, inputs) {
  14181. var rhs = right(scope, locals, assign, inputs);
  14182. var value;
  14183. if (rhs.value != null) {
  14184. var values = [];
  14185. for (var i = 0; i < args.length; ++i) {
  14186. values.push(args[i](scope, locals, assign, inputs));
  14187. }
  14188. value = rhs.value.apply(rhs.context, values);
  14189. }
  14190. return context ? {value: value} : value;
  14191. };
  14192. case AST.AssignmentExpression:
  14193. left = this.recurse(ast.left, true, 1);
  14194. right = this.recurse(ast.right);
  14195. return function(scope, locals, assign, inputs) {
  14196. var lhs = left(scope, locals, assign, inputs);
  14197. var rhs = right(scope, locals, assign, inputs);
  14198. lhs.context[lhs.name] = rhs;
  14199. return context ? {value: rhs} : rhs;
  14200. };
  14201. case AST.ArrayExpression:
  14202. args = [];
  14203. forEach(ast.elements, function(expr) {
  14204. args.push(self.recurse(expr));
  14205. });
  14206. return function(scope, locals, assign, inputs) {
  14207. var value = [];
  14208. for (var i = 0; i < args.length; ++i) {
  14209. value.push(args[i](scope, locals, assign, inputs));
  14210. }
  14211. return context ? {value: value} : value;
  14212. };
  14213. case AST.ObjectExpression:
  14214. args = [];
  14215. forEach(ast.properties, function(property) {
  14216. if (property.computed) {
  14217. args.push({key: self.recurse(property.key),
  14218. computed: true,
  14219. value: self.recurse(property.value)
  14220. });
  14221. } else {
  14222. args.push({key: property.key.type === AST.Identifier ?
  14223. property.key.name :
  14224. ('' + property.key.value),
  14225. computed: false,
  14226. value: self.recurse(property.value)
  14227. });
  14228. }
  14229. });
  14230. return function(scope, locals, assign, inputs) {
  14231. var value = {};
  14232. for (var i = 0; i < args.length; ++i) {
  14233. if (args[i].computed) {
  14234. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  14235. } else {
  14236. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  14237. }
  14238. }
  14239. return context ? {value: value} : value;
  14240. };
  14241. case AST.ThisExpression:
  14242. return function(scope) {
  14243. return context ? {value: scope} : scope;
  14244. };
  14245. case AST.LocalsExpression:
  14246. return function(scope, locals) {
  14247. return context ? {value: locals} : locals;
  14248. };
  14249. case AST.NGValueParameter:
  14250. return function(scope, locals, assign) {
  14251. return context ? {value: assign} : assign;
  14252. };
  14253. }
  14254. },
  14255. 'unary+': function(argument, context) {
  14256. return function(scope, locals, assign, inputs) {
  14257. var arg = argument(scope, locals, assign, inputs);
  14258. if (isDefined(arg)) {
  14259. arg = +arg;
  14260. } else {
  14261. arg = 0;
  14262. }
  14263. return context ? {value: arg} : arg;
  14264. };
  14265. },
  14266. 'unary-': function(argument, context) {
  14267. return function(scope, locals, assign, inputs) {
  14268. var arg = argument(scope, locals, assign, inputs);
  14269. if (isDefined(arg)) {
  14270. arg = -arg;
  14271. } else {
  14272. arg = -0;
  14273. }
  14274. return context ? {value: arg} : arg;
  14275. };
  14276. },
  14277. 'unary!': function(argument, context) {
  14278. return function(scope, locals, assign, inputs) {
  14279. var arg = !argument(scope, locals, assign, inputs);
  14280. return context ? {value: arg} : arg;
  14281. };
  14282. },
  14283. 'binary+': function(left, right, context) {
  14284. return function(scope, locals, assign, inputs) {
  14285. var lhs = left(scope, locals, assign, inputs);
  14286. var rhs = right(scope, locals, assign, inputs);
  14287. var arg = plusFn(lhs, rhs);
  14288. return context ? {value: arg} : arg;
  14289. };
  14290. },
  14291. 'binary-': function(left, right, context) {
  14292. return function(scope, locals, assign, inputs) {
  14293. var lhs = left(scope, locals, assign, inputs);
  14294. var rhs = right(scope, locals, assign, inputs);
  14295. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  14296. return context ? {value: arg} : arg;
  14297. };
  14298. },
  14299. 'binary*': function(left, right, context) {
  14300. return function(scope, locals, assign, inputs) {
  14301. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  14302. return context ? {value: arg} : arg;
  14303. };
  14304. },
  14305. 'binary/': function(left, right, context) {
  14306. return function(scope, locals, assign, inputs) {
  14307. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  14308. return context ? {value: arg} : arg;
  14309. };
  14310. },
  14311. 'binary%': function(left, right, context) {
  14312. return function(scope, locals, assign, inputs) {
  14313. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  14314. return context ? {value: arg} : arg;
  14315. };
  14316. },
  14317. 'binary===': function(left, right, context) {
  14318. return function(scope, locals, assign, inputs) {
  14319. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  14320. return context ? {value: arg} : arg;
  14321. };
  14322. },
  14323. 'binary!==': function(left, right, context) {
  14324. return function(scope, locals, assign, inputs) {
  14325. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  14326. return context ? {value: arg} : arg;
  14327. };
  14328. },
  14329. 'binary==': function(left, right, context) {
  14330. return function(scope, locals, assign, inputs) {
  14331. // eslint-disable-next-line eqeqeq
  14332. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  14333. return context ? {value: arg} : arg;
  14334. };
  14335. },
  14336. 'binary!=': function(left, right, context) {
  14337. return function(scope, locals, assign, inputs) {
  14338. // eslint-disable-next-line eqeqeq
  14339. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  14340. return context ? {value: arg} : arg;
  14341. };
  14342. },
  14343. 'binary<': function(left, right, context) {
  14344. return function(scope, locals, assign, inputs) {
  14345. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  14346. return context ? {value: arg} : arg;
  14347. };
  14348. },
  14349. 'binary>': function(left, right, context) {
  14350. return function(scope, locals, assign, inputs) {
  14351. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  14352. return context ? {value: arg} : arg;
  14353. };
  14354. },
  14355. 'binary<=': function(left, right, context) {
  14356. return function(scope, locals, assign, inputs) {
  14357. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  14358. return context ? {value: arg} : arg;
  14359. };
  14360. },
  14361. 'binary>=': function(left, right, context) {
  14362. return function(scope, locals, assign, inputs) {
  14363. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  14364. return context ? {value: arg} : arg;
  14365. };
  14366. },
  14367. 'binary&&': function(left, right, context) {
  14368. return function(scope, locals, assign, inputs) {
  14369. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  14370. return context ? {value: arg} : arg;
  14371. };
  14372. },
  14373. 'binary||': function(left, right, context) {
  14374. return function(scope, locals, assign, inputs) {
  14375. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  14376. return context ? {value: arg} : arg;
  14377. };
  14378. },
  14379. 'ternary?:': function(test, alternate, consequent, context) {
  14380. return function(scope, locals, assign, inputs) {
  14381. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  14382. return context ? {value: arg} : arg;
  14383. };
  14384. },
  14385. value: function(value, context) {
  14386. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  14387. },
  14388. identifier: function(name, context, create) {
  14389. return function(scope, locals, assign, inputs) {
  14390. var base = locals && (name in locals) ? locals : scope;
  14391. if (create && create !== 1 && base && base[name] == null) {
  14392. base[name] = {};
  14393. }
  14394. var value = base ? base[name] : undefined;
  14395. if (context) {
  14396. return {context: base, name: name, value: value};
  14397. } else {
  14398. return value;
  14399. }
  14400. };
  14401. },
  14402. computedMember: function(left, right, context, create) {
  14403. return function(scope, locals, assign, inputs) {
  14404. var lhs = left(scope, locals, assign, inputs);
  14405. var rhs;
  14406. var value;
  14407. if (lhs != null) {
  14408. rhs = right(scope, locals, assign, inputs);
  14409. rhs = getStringValue(rhs);
  14410. if (create && create !== 1) {
  14411. if (lhs && !(lhs[rhs])) {
  14412. lhs[rhs] = {};
  14413. }
  14414. }
  14415. value = lhs[rhs];
  14416. }
  14417. if (context) {
  14418. return {context: lhs, name: rhs, value: value};
  14419. } else {
  14420. return value;
  14421. }
  14422. };
  14423. },
  14424. nonComputedMember: function(left, right, context, create) {
  14425. return function(scope, locals, assign, inputs) {
  14426. var lhs = left(scope, locals, assign, inputs);
  14427. if (create && create !== 1) {
  14428. if (lhs && lhs[right] == null) {
  14429. lhs[right] = {};
  14430. }
  14431. }
  14432. var value = lhs != null ? lhs[right] : undefined;
  14433. if (context) {
  14434. return {context: lhs, name: right, value: value};
  14435. } else {
  14436. return value;
  14437. }
  14438. };
  14439. },
  14440. inputs: function(input, watchId) {
  14441. return function(scope, value, locals, inputs) {
  14442. if (inputs) return inputs[watchId];
  14443. return input(scope, value, locals);
  14444. };
  14445. }
  14446. };
  14447. /**
  14448. * @constructor
  14449. */
  14450. var Parser = function Parser(lexer, $filter, options) {
  14451. this.lexer = lexer;
  14452. this.$filter = $filter;
  14453. this.options = options;
  14454. this.ast = new AST(lexer, options);
  14455. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  14456. new ASTCompiler(this.ast, $filter);
  14457. };
  14458. Parser.prototype = {
  14459. constructor: Parser,
  14460. parse: function(text) {
  14461. return this.astCompiler.compile(text);
  14462. }
  14463. };
  14464. function getValueOf(value) {
  14465. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  14466. }
  14467. ///////////////////////////////////
  14468. /**
  14469. * @ngdoc service
  14470. * @name $parse
  14471. * @kind function
  14472. *
  14473. * @description
  14474. *
  14475. * Converts Angular {@link guide/expression expression} into a function.
  14476. *
  14477. * ```js
  14478. * var getter = $parse('user.name');
  14479. * var setter = getter.assign;
  14480. * var context = {user:{name:'angular'}};
  14481. * var locals = {user:{name:'local'}};
  14482. *
  14483. * expect(getter(context)).toEqual('angular');
  14484. * setter(context, 'newValue');
  14485. * expect(context.user.name).toEqual('newValue');
  14486. * expect(getter(context, locals)).toEqual('local');
  14487. * ```
  14488. *
  14489. *
  14490. * @param {string} expression String expression to compile.
  14491. * @returns {function(context, locals)} a function which represents the compiled expression:
  14492. *
  14493. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14494. * are evaluated against (typically a scope object).
  14495. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14496. * `context`.
  14497. *
  14498. * The returned function also has the following properties:
  14499. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  14500. * literal.
  14501. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  14502. * constant literals.
  14503. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  14504. * set to a function to change its value on the given context.
  14505. *
  14506. */
  14507. /**
  14508. * @ngdoc provider
  14509. * @name $parseProvider
  14510. * @this
  14511. *
  14512. * @description
  14513. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  14514. * service.
  14515. */
  14516. function $ParseProvider() {
  14517. var cache = createMap();
  14518. var literals = {
  14519. 'true': true,
  14520. 'false': false,
  14521. 'null': null,
  14522. 'undefined': undefined
  14523. };
  14524. var identStart, identContinue;
  14525. /**
  14526. * @ngdoc method
  14527. * @name $parseProvider#addLiteral
  14528. * @description
  14529. *
  14530. * Configure $parse service to add literal values that will be present as literal at expressions.
  14531. *
  14532. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  14533. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  14534. *
  14535. **/
  14536. this.addLiteral = function(literalName, literalValue) {
  14537. literals[literalName] = literalValue;
  14538. };
  14539. /**
  14540. * @ngdoc method
  14541. * @name $parseProvider#setIdentifierFns
  14542. *
  14543. * @description
  14544. *
  14545. * Allows defining the set of characters that are allowed in Angular expressions. The function
  14546. * `identifierStart` will get called to know if a given character is a valid character to be the
  14547. * first character for an identifier. The function `identifierContinue` will get called to know if
  14548. * a given character is a valid character to be a follow-up identifier character. The functions
  14549. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  14550. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  14551. * mind that the `string` parameter can be two characters long depending on the character
  14552. * representation. It is expected for the function to return `true` or `false`, whether that
  14553. * character is allowed or not.
  14554. *
  14555. * Since this function will be called extensively, keep the implementation of these functions fast,
  14556. * as the performance of these functions have a direct impact on the expressions parsing speed.
  14557. *
  14558. * @param {function=} identifierStart The function that will decide whether the given character is
  14559. * a valid identifier start character.
  14560. * @param {function=} identifierContinue The function that will decide whether the given character is
  14561. * a valid identifier continue character.
  14562. */
  14563. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  14564. identStart = identifierStart;
  14565. identContinue = identifierContinue;
  14566. return this;
  14567. };
  14568. this.$get = ['$filter', function($filter) {
  14569. var noUnsafeEval = csp().noUnsafeEval;
  14570. var $parseOptions = {
  14571. csp: noUnsafeEval,
  14572. literals: copy(literals),
  14573. isIdentifierStart: isFunction(identStart) && identStart,
  14574. isIdentifierContinue: isFunction(identContinue) && identContinue
  14575. };
  14576. return $parse;
  14577. function $parse(exp, interceptorFn) {
  14578. var parsedExpression, oneTime, cacheKey;
  14579. switch (typeof exp) {
  14580. case 'string':
  14581. exp = exp.trim();
  14582. cacheKey = exp;
  14583. parsedExpression = cache[cacheKey];
  14584. if (!parsedExpression) {
  14585. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  14586. oneTime = true;
  14587. exp = exp.substring(2);
  14588. }
  14589. var lexer = new Lexer($parseOptions);
  14590. var parser = new Parser(lexer, $filter, $parseOptions);
  14591. parsedExpression = parser.parse(exp);
  14592. if (parsedExpression.constant) {
  14593. parsedExpression.$$watchDelegate = constantWatchDelegate;
  14594. } else if (oneTime) {
  14595. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  14596. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  14597. } else if (parsedExpression.inputs) {
  14598. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  14599. }
  14600. cache[cacheKey] = parsedExpression;
  14601. }
  14602. return addInterceptor(parsedExpression, interceptorFn);
  14603. case 'function':
  14604. return addInterceptor(exp, interceptorFn);
  14605. default:
  14606. return addInterceptor(noop, interceptorFn);
  14607. }
  14608. }
  14609. function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) {
  14610. if (newValue == null || oldValueOfValue == null) { // null/undefined
  14611. return newValue === oldValueOfValue;
  14612. }
  14613. if (typeof newValue === 'object' && !compareObjectIdentity) {
  14614. // attempt to convert the value to a primitive type
  14615. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  14616. // be cheaply dirty-checked
  14617. newValue = getValueOf(newValue);
  14618. if (typeof newValue === 'object') {
  14619. // objects/arrays are not supported - deep-watching them would be too expensive
  14620. return false;
  14621. }
  14622. // fall-through to the primitive equality check
  14623. }
  14624. //Primitive or NaN
  14625. // eslint-disable-next-line no-self-compare
  14626. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  14627. }
  14628. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14629. var inputExpressions = parsedExpression.inputs;
  14630. var lastResult;
  14631. if (inputExpressions.length === 1) {
  14632. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14633. inputExpressions = inputExpressions[0];
  14634. return scope.$watch(function expressionInputWatch(scope) {
  14635. var newInputValue = inputExpressions(scope);
  14636. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, parsedExpression.literal)) {
  14637. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  14638. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  14639. }
  14640. return lastResult;
  14641. }, listener, objectEquality, prettyPrintExpression);
  14642. }
  14643. var oldInputValueOfValues = [];
  14644. var oldInputValues = [];
  14645. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14646. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14647. oldInputValues[i] = null;
  14648. }
  14649. return scope.$watch(function expressionInputsWatch(scope) {
  14650. var changed = false;
  14651. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14652. var newInputValue = inputExpressions[i](scope);
  14653. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], parsedExpression.literal))) {
  14654. oldInputValues[i] = newInputValue;
  14655. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  14656. }
  14657. }
  14658. if (changed) {
  14659. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  14660. }
  14661. return lastResult;
  14662. }, listener, objectEquality, prettyPrintExpression);
  14663. }
  14664. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14665. var unwatch, lastValue;
  14666. if (parsedExpression.inputs) {
  14667. unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);
  14668. } else {
  14669. unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);
  14670. }
  14671. return unwatch;
  14672. function oneTimeWatch(scope) {
  14673. return parsedExpression(scope);
  14674. }
  14675. function oneTimeListener(value, old, scope) {
  14676. lastValue = value;
  14677. if (isFunction(listener)) {
  14678. listener(value, old, scope);
  14679. }
  14680. if (isDefined(value)) {
  14681. scope.$$postDigest(function() {
  14682. if (isDefined(lastValue)) {
  14683. unwatch();
  14684. }
  14685. });
  14686. }
  14687. }
  14688. }
  14689. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14690. var unwatch, lastValue;
  14691. unwatch = scope.$watch(function oneTimeWatch(scope) {
  14692. return parsedExpression(scope);
  14693. }, function oneTimeListener(value, old, scope) {
  14694. lastValue = value;
  14695. if (isFunction(listener)) {
  14696. listener(value, old, scope);
  14697. }
  14698. if (isAllDefined(value)) {
  14699. scope.$$postDigest(function() {
  14700. if (isAllDefined(lastValue)) unwatch();
  14701. });
  14702. }
  14703. }, objectEquality);
  14704. return unwatch;
  14705. function isAllDefined(value) {
  14706. var allDefined = true;
  14707. forEach(value, function(val) {
  14708. if (!isDefined(val)) allDefined = false;
  14709. });
  14710. return allDefined;
  14711. }
  14712. }
  14713. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14714. var unwatch = scope.$watch(function constantWatch(scope) {
  14715. unwatch();
  14716. return parsedExpression(scope);
  14717. }, listener, objectEquality);
  14718. return unwatch;
  14719. }
  14720. function addInterceptor(parsedExpression, interceptorFn) {
  14721. if (!interceptorFn) return parsedExpression;
  14722. var watchDelegate = parsedExpression.$$watchDelegate;
  14723. var useInputs = false;
  14724. var regularWatch =
  14725. watchDelegate !== oneTimeLiteralWatchDelegate &&
  14726. watchDelegate !== oneTimeWatchDelegate;
  14727. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  14728. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  14729. return interceptorFn(value, scope, locals);
  14730. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  14731. var value = parsedExpression(scope, locals, assign, inputs);
  14732. var result = interceptorFn(value, scope, locals);
  14733. // we only return the interceptor's result if the
  14734. // initial value is defined (for bind-once)
  14735. return isDefined(value) ? result : value;
  14736. };
  14737. // Propagate $$watchDelegates other then inputsWatchDelegate
  14738. useInputs = !parsedExpression.inputs;
  14739. if (parsedExpression.$$watchDelegate &&
  14740. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  14741. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  14742. fn.inputs = parsedExpression.inputs;
  14743. } else if (!interceptorFn.$stateful) {
  14744. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  14745. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  14746. fn.$$watchDelegate = inputsWatchDelegate;
  14747. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  14748. }
  14749. return fn;
  14750. }
  14751. }];
  14752. }
  14753. /**
  14754. * @ngdoc service
  14755. * @name $q
  14756. * @requires $rootScope
  14757. *
  14758. * @description
  14759. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  14760. * when they are done processing.
  14761. *
  14762. * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred
  14763. * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  14764. *
  14765. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  14766. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  14767. *
  14768. * # $q constructor
  14769. *
  14770. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  14771. * function as the first argument. This is similar to the native Promise implementation from ES6,
  14772. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  14773. *
  14774. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  14775. * available yet.
  14776. *
  14777. * It can be used like so:
  14778. *
  14779. * ```js
  14780. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14781. * // are available in the current lexical scope (they could have been injected or passed in).
  14782. *
  14783. * function asyncGreet(name) {
  14784. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  14785. * return $q(function(resolve, reject) {
  14786. * setTimeout(function() {
  14787. * if (okToGreet(name)) {
  14788. * resolve('Hello, ' + name + '!');
  14789. * } else {
  14790. * reject('Greeting ' + name + ' is not allowed.');
  14791. * }
  14792. * }, 1000);
  14793. * });
  14794. * }
  14795. *
  14796. * var promise = asyncGreet('Robin Hood');
  14797. * promise.then(function(greeting) {
  14798. * alert('Success: ' + greeting);
  14799. * }, function(reason) {
  14800. * alert('Failed: ' + reason);
  14801. * });
  14802. * ```
  14803. *
  14804. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  14805. *
  14806. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  14807. *
  14808. * However, the more traditional CommonJS-style usage is still available, and documented below.
  14809. *
  14810. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  14811. * interface for interacting with an object that represents the result of an action that is
  14812. * performed asynchronously, and may or may not be finished at any given point in time.
  14813. *
  14814. * From the perspective of dealing with error handling, deferred and promise APIs are to
  14815. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  14816. *
  14817. * ```js
  14818. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14819. * // are available in the current lexical scope (they could have been injected or passed in).
  14820. *
  14821. * function asyncGreet(name) {
  14822. * var deferred = $q.defer();
  14823. *
  14824. * setTimeout(function() {
  14825. * deferred.notify('About to greet ' + name + '.');
  14826. *
  14827. * if (okToGreet(name)) {
  14828. * deferred.resolve('Hello, ' + name + '!');
  14829. * } else {
  14830. * deferred.reject('Greeting ' + name + ' is not allowed.');
  14831. * }
  14832. * }, 1000);
  14833. *
  14834. * return deferred.promise;
  14835. * }
  14836. *
  14837. * var promise = asyncGreet('Robin Hood');
  14838. * promise.then(function(greeting) {
  14839. * alert('Success: ' + greeting);
  14840. * }, function(reason) {
  14841. * alert('Failed: ' + reason);
  14842. * }, function(update) {
  14843. * alert('Got notification: ' + update);
  14844. * });
  14845. * ```
  14846. *
  14847. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  14848. * comes in the way of guarantees that promise and deferred APIs make, see
  14849. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  14850. *
  14851. * Additionally the promise api allows for composition that is very hard to do with the
  14852. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  14853. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  14854. * section on serial or parallel joining of promises.
  14855. *
  14856. * # The Deferred API
  14857. *
  14858. * A new instance of deferred is constructed by calling `$q.defer()`.
  14859. *
  14860. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  14861. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  14862. * of the task.
  14863. *
  14864. * **Methods**
  14865. *
  14866. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  14867. * constructed via `$q.reject`, the promise will be rejected instead.
  14868. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  14869. * resolving it with a rejection constructed via `$q.reject`.
  14870. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  14871. * multiple times before the promise is either resolved or rejected.
  14872. *
  14873. * **Properties**
  14874. *
  14875. * - promise – `{Promise}` – promise object associated with this deferred.
  14876. *
  14877. *
  14878. * # The Promise API
  14879. *
  14880. * A new promise instance is created when a deferred instance is created and can be retrieved by
  14881. * calling `deferred.promise`.
  14882. *
  14883. * The purpose of the promise object is to allow for interested parties to get access to the result
  14884. * of the deferred task when it completes.
  14885. *
  14886. * **Methods**
  14887. *
  14888. * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
  14889. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  14890. * as soon as the result is available. The callbacks are called with a single argument: the result
  14891. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  14892. * provide a progress indication, before the promise is resolved or rejected.
  14893. *
  14894. * This method *returns a new promise* which is resolved or rejected via the return value of the
  14895. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  14896. * with the value which is resolved in that promise using
  14897. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  14898. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  14899. * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
  14900. * arguments are optional.
  14901. *
  14902. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  14903. *
  14904. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  14905. * but to do so without modifying the final value. This is useful to release resources or do some
  14906. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  14907. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  14908. * more information.
  14909. *
  14910. * # Chaining promises
  14911. *
  14912. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  14913. * possible to create a chain of promises:
  14914. *
  14915. * ```js
  14916. * promiseB = promiseA.then(function(result) {
  14917. * return result + 1;
  14918. * });
  14919. *
  14920. * // promiseB will be resolved immediately after promiseA is resolved and its value
  14921. * // will be the result of promiseA incremented by 1
  14922. * ```
  14923. *
  14924. * It is possible to create chains of any length and since a promise can be resolved with another
  14925. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  14926. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  14927. * $http's response interceptors.
  14928. *
  14929. *
  14930. * # Differences between Kris Kowal's Q and $q
  14931. *
  14932. * There are two main differences:
  14933. *
  14934. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  14935. * mechanism in angular, which means faster propagation of resolution or rejection into your
  14936. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  14937. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  14938. * all the important functionality needed for common async tasks.
  14939. *
  14940. * # Testing
  14941. *
  14942. * ```js
  14943. * it('should simulate promise', inject(function($q, $rootScope) {
  14944. * var deferred = $q.defer();
  14945. * var promise = deferred.promise;
  14946. * var resolvedValue;
  14947. *
  14948. * promise.then(function(value) { resolvedValue = value; });
  14949. * expect(resolvedValue).toBeUndefined();
  14950. *
  14951. * // Simulate resolving of promise
  14952. * deferred.resolve(123);
  14953. * // Note that the 'then' function does not get called synchronously.
  14954. * // This is because we want the promise API to always be async, whether or not
  14955. * // it got called synchronously or asynchronously.
  14956. * expect(resolvedValue).toBeUndefined();
  14957. *
  14958. * // Propagate promise resolution to 'then' functions using $apply().
  14959. * $rootScope.$apply();
  14960. * expect(resolvedValue).toEqual(123);
  14961. * }));
  14962. * ```
  14963. *
  14964. * @param {function(function, function)} resolver Function which is responsible for resolving or
  14965. * rejecting the newly created promise. The first parameter is a function which resolves the
  14966. * promise, the second parameter is a function which rejects the promise.
  14967. *
  14968. * @returns {Promise} The newly created promise.
  14969. */
  14970. /**
  14971. * @ngdoc provider
  14972. * @name $qProvider
  14973. * @this
  14974. *
  14975. * @description
  14976. */
  14977. function $QProvider() {
  14978. var errorOnUnhandledRejections = true;
  14979. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  14980. return qFactory(function(callback) {
  14981. $rootScope.$evalAsync(callback);
  14982. }, $exceptionHandler, errorOnUnhandledRejections);
  14983. }];
  14984. /**
  14985. * @ngdoc method
  14986. * @name $qProvider#errorOnUnhandledRejections
  14987. * @kind function
  14988. *
  14989. * @description
  14990. * Retrieves or overrides whether to generate an error when a rejected promise is not handled.
  14991. * This feature is enabled by default.
  14992. *
  14993. * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.
  14994. * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for
  14995. * chaining otherwise.
  14996. */
  14997. this.errorOnUnhandledRejections = function(value) {
  14998. if (isDefined(value)) {
  14999. errorOnUnhandledRejections = value;
  15000. return this;
  15001. } else {
  15002. return errorOnUnhandledRejections;
  15003. }
  15004. };
  15005. }
  15006. /** @this */
  15007. function $$QProvider() {
  15008. var errorOnUnhandledRejections = true;
  15009. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  15010. return qFactory(function(callback) {
  15011. $browser.defer(callback);
  15012. }, $exceptionHandler, errorOnUnhandledRejections);
  15013. }];
  15014. this.errorOnUnhandledRejections = function(value) {
  15015. if (isDefined(value)) {
  15016. errorOnUnhandledRejections = value;
  15017. return this;
  15018. } else {
  15019. return errorOnUnhandledRejections;
  15020. }
  15021. };
  15022. }
  15023. /**
  15024. * Constructs a promise manager.
  15025. *
  15026. * @param {function(function)} nextTick Function for executing functions in the next turn.
  15027. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  15028. * debugging purposes.
  15029. @ param {=boolean} errorOnUnhandledRejections Whether an error should be generated on unhandled
  15030. * promises rejections.
  15031. * @returns {object} Promise manager.
  15032. */
  15033. function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {
  15034. var $qMinErr = minErr('$q', TypeError);
  15035. var queueSize = 0;
  15036. var checkQueue = [];
  15037. /**
  15038. * @ngdoc method
  15039. * @name ng.$q#defer
  15040. * @kind function
  15041. *
  15042. * @description
  15043. * Creates a `Deferred` object which represents a task which will finish in the future.
  15044. *
  15045. * @returns {Deferred} Returns a new instance of deferred.
  15046. */
  15047. function defer() {
  15048. return new Deferred();
  15049. }
  15050. function Deferred() {
  15051. var promise = this.promise = new Promise();
  15052. //Non prototype methods necessary to support unbound execution :/
  15053. this.resolve = function(val) { resolvePromise(promise, val); };
  15054. this.reject = function(reason) { rejectPromise(promise, reason); };
  15055. this.notify = function(progress) { notifyPromise(promise, progress); };
  15056. }
  15057. function Promise() {
  15058. this.$$state = { status: 0 };
  15059. }
  15060. extend(Promise.prototype, {
  15061. then: function(onFulfilled, onRejected, progressBack) {
  15062. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  15063. return this;
  15064. }
  15065. var result = new Promise();
  15066. this.$$state.pending = this.$$state.pending || [];
  15067. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  15068. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  15069. return result;
  15070. },
  15071. 'catch': function(callback) {
  15072. return this.then(null, callback);
  15073. },
  15074. 'finally': function(callback, progressBack) {
  15075. return this.then(function(value) {
  15076. return handleCallback(value, resolve, callback);
  15077. }, function(error) {
  15078. return handleCallback(error, reject, callback);
  15079. }, progressBack);
  15080. }
  15081. });
  15082. function processQueue(state) {
  15083. var fn, promise, pending;
  15084. pending = state.pending;
  15085. state.processScheduled = false;
  15086. state.pending = undefined;
  15087. try {
  15088. for (var i = 0, ii = pending.length; i < ii; ++i) {
  15089. state.pur = true;
  15090. promise = pending[i][0];
  15091. fn = pending[i][state.status];
  15092. try {
  15093. if (isFunction(fn)) {
  15094. resolvePromise(promise, fn(state.value));
  15095. } else if (state.status === 1) {
  15096. resolvePromise(promise, state.value);
  15097. } else {
  15098. rejectPromise(promise, state.value);
  15099. }
  15100. } catch (e) {
  15101. rejectPromise(promise, e);
  15102. }
  15103. }
  15104. } finally {
  15105. --queueSize;
  15106. if (errorOnUnhandledRejections && queueSize === 0) {
  15107. nextTick(processChecks);
  15108. }
  15109. }
  15110. }
  15111. function processChecks() {
  15112. // eslint-disable-next-line no-unmodified-loop-condition
  15113. while (!queueSize && checkQueue.length) {
  15114. var toCheck = checkQueue.shift();
  15115. if (!toCheck.pur) {
  15116. toCheck.pur = true;
  15117. var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);
  15118. if (toCheck.value instanceof Error) {
  15119. exceptionHandler(toCheck.value, errorMessage);
  15120. } else {
  15121. exceptionHandler(errorMessage);
  15122. }
  15123. }
  15124. }
  15125. }
  15126. function scheduleProcessQueue(state) {
  15127. if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !state.pur) {
  15128. if (queueSize === 0 && checkQueue.length === 0) {
  15129. nextTick(processChecks);
  15130. }
  15131. checkQueue.push(state);
  15132. }
  15133. if (state.processScheduled || !state.pending) return;
  15134. state.processScheduled = true;
  15135. ++queueSize;
  15136. nextTick(function() { processQueue(state); });
  15137. }
  15138. function resolvePromise(promise, val) {
  15139. if (promise.$$state.status) return;
  15140. if (val === promise) {
  15141. $$reject(promise, $qMinErr(
  15142. 'qcycle',
  15143. 'Expected promise to be resolved with value other than itself \'{0}\'',
  15144. val));
  15145. } else {
  15146. $$resolve(promise, val);
  15147. }
  15148. }
  15149. function $$resolve(promise, val) {
  15150. var then;
  15151. var done = false;
  15152. try {
  15153. if (isObject(val) || isFunction(val)) then = val.then;
  15154. if (isFunction(then)) {
  15155. promise.$$state.status = -1;
  15156. then.call(val, doResolve, doReject, doNotify);
  15157. } else {
  15158. promise.$$state.value = val;
  15159. promise.$$state.status = 1;
  15160. scheduleProcessQueue(promise.$$state);
  15161. }
  15162. } catch (e) {
  15163. doReject(e);
  15164. }
  15165. function doResolve(val) {
  15166. if (done) return;
  15167. done = true;
  15168. $$resolve(promise, val);
  15169. }
  15170. function doReject(val) {
  15171. if (done) return;
  15172. done = true;
  15173. $$reject(promise, val);
  15174. }
  15175. function doNotify(progress) {
  15176. notifyPromise(promise, progress);
  15177. }
  15178. }
  15179. function rejectPromise(promise, reason) {
  15180. if (promise.$$state.status) return;
  15181. $$reject(promise, reason);
  15182. }
  15183. function $$reject(promise, reason) {
  15184. promise.$$state.value = reason;
  15185. promise.$$state.status = 2;
  15186. scheduleProcessQueue(promise.$$state);
  15187. }
  15188. function notifyPromise(promise, progress) {
  15189. var callbacks = promise.$$state.pending;
  15190. if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {
  15191. nextTick(function() {
  15192. var callback, result;
  15193. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  15194. result = callbacks[i][0];
  15195. callback = callbacks[i][3];
  15196. try {
  15197. notifyPromise(result, isFunction(callback) ? callback(progress) : progress);
  15198. } catch (e) {
  15199. exceptionHandler(e);
  15200. }
  15201. }
  15202. });
  15203. }
  15204. }
  15205. /**
  15206. * @ngdoc method
  15207. * @name $q#reject
  15208. * @kind function
  15209. *
  15210. * @description
  15211. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  15212. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  15213. * a promise chain, you don't need to worry about it.
  15214. *
  15215. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  15216. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  15217. * a promise error callback and you want to forward the error to the promise derived from the
  15218. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  15219. * `reject`.
  15220. *
  15221. * ```js
  15222. * promiseB = promiseA.then(function(result) {
  15223. * // success: do something and resolve promiseB
  15224. * // with the old or a new result
  15225. * return result;
  15226. * }, function(reason) {
  15227. * // error: handle the error if possible and
  15228. * // resolve promiseB with newPromiseOrValue,
  15229. * // otherwise forward the rejection to promiseB
  15230. * if (canHandle(reason)) {
  15231. * // handle the error and recover
  15232. * return newPromiseOrValue;
  15233. * }
  15234. * return $q.reject(reason);
  15235. * });
  15236. * ```
  15237. *
  15238. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  15239. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  15240. */
  15241. function reject(reason) {
  15242. var result = new Promise();
  15243. rejectPromise(result, reason);
  15244. return result;
  15245. }
  15246. function handleCallback(value, resolver, callback) {
  15247. var callbackOutput = null;
  15248. try {
  15249. if (isFunction(callback)) callbackOutput = callback();
  15250. } catch (e) {
  15251. return reject(e);
  15252. }
  15253. if (isPromiseLike(callbackOutput)) {
  15254. return callbackOutput.then(function() {
  15255. return resolver(value);
  15256. }, reject);
  15257. } else {
  15258. return resolver(value);
  15259. }
  15260. }
  15261. /**
  15262. * @ngdoc method
  15263. * @name $q#when
  15264. * @kind function
  15265. *
  15266. * @description
  15267. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  15268. * This is useful when you are dealing with an object that might or might not be a promise, or if
  15269. * the promise comes from a source that can't be trusted.
  15270. *
  15271. * @param {*} value Value or a promise
  15272. * @param {Function=} successCallback
  15273. * @param {Function=} errorCallback
  15274. * @param {Function=} progressCallback
  15275. * @returns {Promise} Returns a promise of the passed value or promise
  15276. */
  15277. function when(value, callback, errback, progressBack) {
  15278. var result = new Promise();
  15279. resolvePromise(result, value);
  15280. return result.then(callback, errback, progressBack);
  15281. }
  15282. /**
  15283. * @ngdoc method
  15284. * @name $q#resolve
  15285. * @kind function
  15286. *
  15287. * @description
  15288. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  15289. *
  15290. * @param {*} value Value or a promise
  15291. * @param {Function=} successCallback
  15292. * @param {Function=} errorCallback
  15293. * @param {Function=} progressCallback
  15294. * @returns {Promise} Returns a promise of the passed value or promise
  15295. */
  15296. var resolve = when;
  15297. /**
  15298. * @ngdoc method
  15299. * @name $q#all
  15300. * @kind function
  15301. *
  15302. * @description
  15303. * Combines multiple promises into a single promise that is resolved when all of the input
  15304. * promises are resolved.
  15305. *
  15306. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15307. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  15308. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  15309. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  15310. * with the same rejection value.
  15311. */
  15312. function all(promises) {
  15313. var result = new Promise(),
  15314. counter = 0,
  15315. results = isArray(promises) ? [] : {};
  15316. forEach(promises, function(promise, key) {
  15317. counter++;
  15318. when(promise).then(function(value) {
  15319. results[key] = value;
  15320. if (!(--counter)) resolvePromise(result, results);
  15321. }, function(reason) {
  15322. rejectPromise(result, reason);
  15323. });
  15324. });
  15325. if (counter === 0) {
  15326. resolvePromise(result, results);
  15327. }
  15328. return result;
  15329. }
  15330. /**
  15331. * @ngdoc method
  15332. * @name $q#race
  15333. * @kind function
  15334. *
  15335. * @description
  15336. * Returns a promise that resolves or rejects as soon as one of those promises
  15337. * resolves or rejects, with the value or reason from that promise.
  15338. *
  15339. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15340. * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
  15341. * resolves or rejects, with the value or reason from that promise.
  15342. */
  15343. function race(promises) {
  15344. var deferred = defer();
  15345. forEach(promises, function(promise) {
  15346. when(promise).then(deferred.resolve, deferred.reject);
  15347. });
  15348. return deferred.promise;
  15349. }
  15350. function $Q(resolver) {
  15351. if (!isFunction(resolver)) {
  15352. throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
  15353. }
  15354. var promise = new Promise();
  15355. function resolveFn(value) {
  15356. resolvePromise(promise, value);
  15357. }
  15358. function rejectFn(reason) {
  15359. rejectPromise(promise, reason);
  15360. }
  15361. resolver(resolveFn, rejectFn);
  15362. return promise;
  15363. }
  15364. // Let's make the instanceof operator work for promises, so that
  15365. // `new $q(fn) instanceof $q` would evaluate to true.
  15366. $Q.prototype = Promise.prototype;
  15367. $Q.defer = defer;
  15368. $Q.reject = reject;
  15369. $Q.when = when;
  15370. $Q.resolve = resolve;
  15371. $Q.all = all;
  15372. $Q.race = race;
  15373. return $Q;
  15374. }
  15375. /** @this */
  15376. function $$RAFProvider() { //rAF
  15377. this.$get = ['$window', '$timeout', function($window, $timeout) {
  15378. var requestAnimationFrame = $window.requestAnimationFrame ||
  15379. $window.webkitRequestAnimationFrame;
  15380. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  15381. $window.webkitCancelAnimationFrame ||
  15382. $window.webkitCancelRequestAnimationFrame;
  15383. var rafSupported = !!requestAnimationFrame;
  15384. var raf = rafSupported
  15385. ? function(fn) {
  15386. var id = requestAnimationFrame(fn);
  15387. return function() {
  15388. cancelAnimationFrame(id);
  15389. };
  15390. }
  15391. : function(fn) {
  15392. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  15393. return function() {
  15394. $timeout.cancel(timer);
  15395. };
  15396. };
  15397. raf.supported = rafSupported;
  15398. return raf;
  15399. }];
  15400. }
  15401. /**
  15402. * DESIGN NOTES
  15403. *
  15404. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  15405. *
  15406. * The typical use of scope is to watch the expressions, which most of the time return the same
  15407. * value as last time so we optimize the operation.
  15408. *
  15409. * Closures construction is expensive in terms of speed as well as memory:
  15410. * - No closures, instead use prototypical inheritance for API
  15411. * - Internal state needs to be stored on scope directly, which means that private state is
  15412. * exposed as $$____ properties
  15413. *
  15414. * Loop operations are optimized by using while(count--) { ... }
  15415. * - This means that in order to keep the same order of execution as addition we have to add
  15416. * items to the array at the beginning (unshift) instead of at the end (push)
  15417. *
  15418. * Child scopes are created and removed often
  15419. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  15420. *
  15421. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  15422. * in the same way as watch. Watch requires return of the initialization function which is expensive
  15423. * to construct.
  15424. */
  15425. /**
  15426. * @ngdoc provider
  15427. * @name $rootScopeProvider
  15428. * @description
  15429. *
  15430. * Provider for the $rootScope service.
  15431. */
  15432. /**
  15433. * @ngdoc method
  15434. * @name $rootScopeProvider#digestTtl
  15435. * @description
  15436. *
  15437. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  15438. * assuming that the model is unstable.
  15439. *
  15440. * The current default is 10 iterations.
  15441. *
  15442. * In complex applications it's possible that the dependencies between `$watch`s will result in
  15443. * several digest iterations. However if an application needs more than the default 10 digest
  15444. * iterations for its model to stabilize then you should investigate what is causing the model to
  15445. * continuously change during the digest.
  15446. *
  15447. * Increasing the TTL could have performance implications, so you should not change it without
  15448. * proper justification.
  15449. *
  15450. * @param {number} limit The number of digest iterations.
  15451. */
  15452. /**
  15453. * @ngdoc service
  15454. * @name $rootScope
  15455. * @this
  15456. *
  15457. * @description
  15458. *
  15459. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  15460. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  15461. * between the model and the view, via a mechanism for watching the model for changes.
  15462. * They also provide event emission/broadcast and subscription facility. See the
  15463. * {@link guide/scope developer guide on scopes}.
  15464. */
  15465. function $RootScopeProvider() {
  15466. var TTL = 10;
  15467. var $rootScopeMinErr = minErr('$rootScope');
  15468. var lastDirtyWatch = null;
  15469. var applyAsyncId = null;
  15470. this.digestTtl = function(value) {
  15471. if (arguments.length) {
  15472. TTL = value;
  15473. }
  15474. return TTL;
  15475. };
  15476. function createChildScopeClass(parent) {
  15477. function ChildScope() {
  15478. this.$$watchers = this.$$nextSibling =
  15479. this.$$childHead = this.$$childTail = null;
  15480. this.$$listeners = {};
  15481. this.$$listenerCount = {};
  15482. this.$$watchersCount = 0;
  15483. this.$id = nextUid();
  15484. this.$$ChildScope = null;
  15485. }
  15486. ChildScope.prototype = parent;
  15487. return ChildScope;
  15488. }
  15489. this.$get = ['$exceptionHandler', '$parse', '$browser',
  15490. function($exceptionHandler, $parse, $browser) {
  15491. function destroyChildScope($event) {
  15492. $event.currentScope.$$destroyed = true;
  15493. }
  15494. function cleanUpScope($scope) {
  15495. // Support: IE 9 only
  15496. if (msie === 9) {
  15497. // There is a memory leak in IE9 if all child scopes are not disconnected
  15498. // completely when a scope is destroyed. So this code will recurse up through
  15499. // all this scopes children
  15500. //
  15501. // See issue https://github.com/angular/angular.js/issues/10706
  15502. if ($scope.$$childHead) {
  15503. cleanUpScope($scope.$$childHead);
  15504. }
  15505. if ($scope.$$nextSibling) {
  15506. cleanUpScope($scope.$$nextSibling);
  15507. }
  15508. }
  15509. // The code below works around IE9 and V8's memory leaks
  15510. //
  15511. // See:
  15512. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  15513. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  15514. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  15515. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  15516. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  15517. }
  15518. /**
  15519. * @ngdoc type
  15520. * @name $rootScope.Scope
  15521. *
  15522. * @description
  15523. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  15524. * {@link auto.$injector $injector}. Child scopes are created using the
  15525. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  15526. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  15527. * an in-depth introduction and usage examples.
  15528. *
  15529. *
  15530. * # Inheritance
  15531. * A scope can inherit from a parent scope, as in this example:
  15532. * ```js
  15533. var parent = $rootScope;
  15534. var child = parent.$new();
  15535. parent.salutation = "Hello";
  15536. expect(child.salutation).toEqual('Hello');
  15537. child.salutation = "Welcome";
  15538. expect(child.salutation).toEqual('Welcome');
  15539. expect(parent.salutation).toEqual('Hello');
  15540. * ```
  15541. *
  15542. * When interacting with `Scope` in tests, additional helper methods are available on the
  15543. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  15544. * details.
  15545. *
  15546. *
  15547. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  15548. * provided for the current scope. Defaults to {@link ng}.
  15549. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  15550. * append/override services provided by `providers`. This is handy
  15551. * when unit-testing and having the need to override a default
  15552. * service.
  15553. * @returns {Object} Newly created scope.
  15554. *
  15555. */
  15556. function Scope() {
  15557. this.$id = nextUid();
  15558. this.$$phase = this.$parent = this.$$watchers =
  15559. this.$$nextSibling = this.$$prevSibling =
  15560. this.$$childHead = this.$$childTail = null;
  15561. this.$root = this;
  15562. this.$$destroyed = false;
  15563. this.$$listeners = {};
  15564. this.$$listenerCount = {};
  15565. this.$$watchersCount = 0;
  15566. this.$$isolateBindings = null;
  15567. }
  15568. /**
  15569. * @ngdoc property
  15570. * @name $rootScope.Scope#$id
  15571. *
  15572. * @description
  15573. * Unique scope ID (monotonically increasing) useful for debugging.
  15574. */
  15575. /**
  15576. * @ngdoc property
  15577. * @name $rootScope.Scope#$parent
  15578. *
  15579. * @description
  15580. * Reference to the parent scope.
  15581. */
  15582. /**
  15583. * @ngdoc property
  15584. * @name $rootScope.Scope#$root
  15585. *
  15586. * @description
  15587. * Reference to the root scope.
  15588. */
  15589. Scope.prototype = {
  15590. constructor: Scope,
  15591. /**
  15592. * @ngdoc method
  15593. * @name $rootScope.Scope#$new
  15594. * @kind function
  15595. *
  15596. * @description
  15597. * Creates a new child {@link ng.$rootScope.Scope scope}.
  15598. *
  15599. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  15600. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  15601. *
  15602. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  15603. * desired for the scope and its child scopes to be permanently detached from the parent and
  15604. * thus stop participating in model change detection and listener notification by invoking.
  15605. *
  15606. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  15607. * parent scope. The scope is isolated, as it can not see parent scope properties.
  15608. * When creating widgets, it is useful for the widget to not accidentally read parent
  15609. * state.
  15610. *
  15611. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  15612. * of the newly created scope. Defaults to `this` scope if not provided.
  15613. * This is used when creating a transclude scope to correctly place it
  15614. * in the scope hierarchy while maintaining the correct prototypical
  15615. * inheritance.
  15616. *
  15617. * @returns {Object} The newly created child scope.
  15618. *
  15619. */
  15620. $new: function(isolate, parent) {
  15621. var child;
  15622. parent = parent || this;
  15623. if (isolate) {
  15624. child = new Scope();
  15625. child.$root = this.$root;
  15626. } else {
  15627. // Only create a child scope class if somebody asks for one,
  15628. // but cache it to allow the VM to optimize lookups.
  15629. if (!this.$$ChildScope) {
  15630. this.$$ChildScope = createChildScopeClass(this);
  15631. }
  15632. child = new this.$$ChildScope();
  15633. }
  15634. child.$parent = parent;
  15635. child.$$prevSibling = parent.$$childTail;
  15636. if (parent.$$childHead) {
  15637. parent.$$childTail.$$nextSibling = child;
  15638. parent.$$childTail = child;
  15639. } else {
  15640. parent.$$childHead = parent.$$childTail = child;
  15641. }
  15642. // When the new scope is not isolated or we inherit from `this`, and
  15643. // the parent scope is destroyed, the property `$$destroyed` is inherited
  15644. // prototypically. In all other cases, this property needs to be set
  15645. // when the parent scope is destroyed.
  15646. // The listener needs to be added after the parent is set
  15647. if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
  15648. return child;
  15649. },
  15650. /**
  15651. * @ngdoc method
  15652. * @name $rootScope.Scope#$watch
  15653. * @kind function
  15654. *
  15655. * @description
  15656. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  15657. *
  15658. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  15659. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  15660. * its value when executed multiple times with the same input because it may be executed multiple
  15661. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  15662. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
  15663. * - The `listener` is called only when the value from the current `watchExpression` and the
  15664. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  15665. * see below). Inequality is determined according to reference inequality,
  15666. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  15667. * via the `!==` Javascript operator, unless `objectEquality == true`
  15668. * (see next point)
  15669. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  15670. * according to the {@link angular.equals} function. To save the value of the object for
  15671. * later comparison, the {@link angular.copy} function is used. This therefore means that
  15672. * watching complex objects will have adverse memory and performance implications.
  15673. * - This should not be used to watch for changes in objects that are
  15674. * or contain [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.
  15675. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  15676. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  15677. * iteration limit is 10 to prevent an infinite loop deadlock.
  15678. *
  15679. *
  15680. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  15681. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  15682. * multiple calls to your `watchExpression` because it will execute multiple times in a
  15683. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  15684. *
  15685. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  15686. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  15687. * watcher. In rare cases, this is undesirable because the listener is called when the result
  15688. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  15689. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  15690. * listener was called due to initialization.
  15691. *
  15692. *
  15693. *
  15694. * # Example
  15695. * ```js
  15696. // let's assume that scope was dependency injected as the $rootScope
  15697. var scope = $rootScope;
  15698. scope.name = 'misko';
  15699. scope.counter = 0;
  15700. expect(scope.counter).toEqual(0);
  15701. scope.$watch('name', function(newValue, oldValue) {
  15702. scope.counter = scope.counter + 1;
  15703. });
  15704. expect(scope.counter).toEqual(0);
  15705. scope.$digest();
  15706. // the listener is always called during the first $digest loop after it was registered
  15707. expect(scope.counter).toEqual(1);
  15708. scope.$digest();
  15709. // but now it will not be called unless the value changes
  15710. expect(scope.counter).toEqual(1);
  15711. scope.name = 'adam';
  15712. scope.$digest();
  15713. expect(scope.counter).toEqual(2);
  15714. // Using a function as a watchExpression
  15715. var food;
  15716. scope.foodCounter = 0;
  15717. expect(scope.foodCounter).toEqual(0);
  15718. scope.$watch(
  15719. // This function returns the value being watched. It is called for each turn of the $digest loop
  15720. function() { return food; },
  15721. // This is the change listener, called when the value returned from the above function changes
  15722. function(newValue, oldValue) {
  15723. if ( newValue !== oldValue ) {
  15724. // Only increment the counter if the value changed
  15725. scope.foodCounter = scope.foodCounter + 1;
  15726. }
  15727. }
  15728. );
  15729. // No digest has been run so the counter will be zero
  15730. expect(scope.foodCounter).toEqual(0);
  15731. // Run the digest but since food has not changed count will still be zero
  15732. scope.$digest();
  15733. expect(scope.foodCounter).toEqual(0);
  15734. // Update food and run digest. Now the counter will increment
  15735. food = 'cheeseburger';
  15736. scope.$digest();
  15737. expect(scope.foodCounter).toEqual(1);
  15738. * ```
  15739. *
  15740. *
  15741. *
  15742. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  15743. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  15744. * a call to the `listener`.
  15745. *
  15746. * - `string`: Evaluated as {@link guide/expression expression}
  15747. * - `function(scope)`: called with current `scope` as a parameter.
  15748. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  15749. * of `watchExpression` changes.
  15750. *
  15751. * - `newVal` contains the current value of the `watchExpression`
  15752. * - `oldVal` contains the previous value of the `watchExpression`
  15753. * - `scope` refers to the current scope
  15754. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  15755. * comparing for reference equality.
  15756. * @returns {function()} Returns a deregistration function for this listener.
  15757. */
  15758. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  15759. var get = $parse(watchExp);
  15760. if (get.$$watchDelegate) {
  15761. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  15762. }
  15763. var scope = this,
  15764. array = scope.$$watchers,
  15765. watcher = {
  15766. fn: listener,
  15767. last: initWatchVal,
  15768. get: get,
  15769. exp: prettyPrintExpression || watchExp,
  15770. eq: !!objectEquality
  15771. };
  15772. lastDirtyWatch = null;
  15773. if (!isFunction(listener)) {
  15774. watcher.fn = noop;
  15775. }
  15776. if (!array) {
  15777. array = scope.$$watchers = [];
  15778. array.$$digestWatchIndex = -1;
  15779. }
  15780. // we use unshift since we use a while loop in $digest for speed.
  15781. // the while loop reads in reverse order.
  15782. array.unshift(watcher);
  15783. array.$$digestWatchIndex++;
  15784. incrementWatchersCount(this, 1);
  15785. return function deregisterWatch() {
  15786. var index = arrayRemove(array, watcher);
  15787. if (index >= 0) {
  15788. incrementWatchersCount(scope, -1);
  15789. if (index < array.$$digestWatchIndex) {
  15790. array.$$digestWatchIndex--;
  15791. }
  15792. }
  15793. lastDirtyWatch = null;
  15794. };
  15795. },
  15796. /**
  15797. * @ngdoc method
  15798. * @name $rootScope.Scope#$watchGroup
  15799. * @kind function
  15800. *
  15801. * @description
  15802. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  15803. * If any one expression in the collection changes the `listener` is executed.
  15804. *
  15805. * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return
  15806. * values are examined for changes on every call to `$digest`.
  15807. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  15808. *
  15809. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  15810. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  15811. *
  15812. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  15813. * expression in `watchExpressions` changes
  15814. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  15815. * those of `watchExpression`
  15816. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  15817. * those of `watchExpression`
  15818. * The `scope` refers to the current scope.
  15819. * @returns {function()} Returns a de-registration function for all listeners.
  15820. */
  15821. $watchGroup: function(watchExpressions, listener) {
  15822. var oldValues = new Array(watchExpressions.length);
  15823. var newValues = new Array(watchExpressions.length);
  15824. var deregisterFns = [];
  15825. var self = this;
  15826. var changeReactionScheduled = false;
  15827. var firstRun = true;
  15828. if (!watchExpressions.length) {
  15829. // No expressions means we call the listener ASAP
  15830. var shouldCall = true;
  15831. self.$evalAsync(function() {
  15832. if (shouldCall) listener(newValues, newValues, self);
  15833. });
  15834. return function deregisterWatchGroup() {
  15835. shouldCall = false;
  15836. };
  15837. }
  15838. if (watchExpressions.length === 1) {
  15839. // Special case size of one
  15840. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  15841. newValues[0] = value;
  15842. oldValues[0] = oldValue;
  15843. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  15844. });
  15845. }
  15846. forEach(watchExpressions, function(expr, i) {
  15847. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  15848. newValues[i] = value;
  15849. oldValues[i] = oldValue;
  15850. if (!changeReactionScheduled) {
  15851. changeReactionScheduled = true;
  15852. self.$evalAsync(watchGroupAction);
  15853. }
  15854. });
  15855. deregisterFns.push(unwatchFn);
  15856. });
  15857. function watchGroupAction() {
  15858. changeReactionScheduled = false;
  15859. if (firstRun) {
  15860. firstRun = false;
  15861. listener(newValues, newValues, self);
  15862. } else {
  15863. listener(newValues, oldValues, self);
  15864. }
  15865. }
  15866. return function deregisterWatchGroup() {
  15867. while (deregisterFns.length) {
  15868. deregisterFns.shift()();
  15869. }
  15870. };
  15871. },
  15872. /**
  15873. * @ngdoc method
  15874. * @name $rootScope.Scope#$watchCollection
  15875. * @kind function
  15876. *
  15877. * @description
  15878. * Shallow watches the properties of an object and fires whenever any of the properties change
  15879. * (for arrays, this implies watching the array items; for object maps, this implies watching
  15880. * the properties). If a change is detected, the `listener` callback is fired.
  15881. *
  15882. * - The `obj` collection is observed via standard $watch operation and is examined on every
  15883. * call to $digest() to see if any items have been added, removed, or moved.
  15884. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  15885. * adding, removing, and moving items belonging to an object or array.
  15886. *
  15887. *
  15888. * # Example
  15889. * ```js
  15890. $scope.names = ['igor', 'matias', 'misko', 'james'];
  15891. $scope.dataCount = 4;
  15892. $scope.$watchCollection('names', function(newNames, oldNames) {
  15893. $scope.dataCount = newNames.length;
  15894. });
  15895. expect($scope.dataCount).toEqual(4);
  15896. $scope.$digest();
  15897. //still at 4 ... no changes
  15898. expect($scope.dataCount).toEqual(4);
  15899. $scope.names.pop();
  15900. $scope.$digest();
  15901. //now there's been a change
  15902. expect($scope.dataCount).toEqual(3);
  15903. * ```
  15904. *
  15905. *
  15906. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  15907. * expression value should evaluate to an object or an array which is observed on each
  15908. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  15909. * collection will trigger a call to the `listener`.
  15910. *
  15911. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  15912. * when a change is detected.
  15913. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  15914. * - The `oldCollection` object is a copy of the former collection data.
  15915. * Due to performance considerations, the`oldCollection` value is computed only if the
  15916. * `listener` function declares two or more arguments.
  15917. * - The `scope` argument refers to the current scope.
  15918. *
  15919. * @returns {function()} Returns a de-registration function for this listener. When the
  15920. * de-registration function is executed, the internal watch operation is terminated.
  15921. */
  15922. $watchCollection: function(obj, listener) {
  15923. $watchCollectionInterceptor.$stateful = true;
  15924. var self = this;
  15925. // the current value, updated on each dirty-check run
  15926. var newValue;
  15927. // a shallow copy of the newValue from the last dirty-check run,
  15928. // updated to match newValue during dirty-check run
  15929. var oldValue;
  15930. // a shallow copy of the newValue from when the last change happened
  15931. var veryOldValue;
  15932. // only track veryOldValue if the listener is asking for it
  15933. var trackVeryOldValue = (listener.length > 1);
  15934. var changeDetected = 0;
  15935. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  15936. var internalArray = [];
  15937. var internalObject = {};
  15938. var initRun = true;
  15939. var oldLength = 0;
  15940. function $watchCollectionInterceptor(_value) {
  15941. newValue = _value;
  15942. var newLength, key, bothNaN, newItem, oldItem;
  15943. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  15944. if (isUndefined(newValue)) return;
  15945. if (!isObject(newValue)) { // if primitive
  15946. if (oldValue !== newValue) {
  15947. oldValue = newValue;
  15948. changeDetected++;
  15949. }
  15950. } else if (isArrayLike(newValue)) {
  15951. if (oldValue !== internalArray) {
  15952. // we are transitioning from something which was not an array into array.
  15953. oldValue = internalArray;
  15954. oldLength = oldValue.length = 0;
  15955. changeDetected++;
  15956. }
  15957. newLength = newValue.length;
  15958. if (oldLength !== newLength) {
  15959. // if lengths do not match we need to trigger change notification
  15960. changeDetected++;
  15961. oldValue.length = oldLength = newLength;
  15962. }
  15963. // copy the items to oldValue and look for changes.
  15964. for (var i = 0; i < newLength; i++) {
  15965. oldItem = oldValue[i];
  15966. newItem = newValue[i];
  15967. // eslint-disable-next-line no-self-compare
  15968. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  15969. if (!bothNaN && (oldItem !== newItem)) {
  15970. changeDetected++;
  15971. oldValue[i] = newItem;
  15972. }
  15973. }
  15974. } else {
  15975. if (oldValue !== internalObject) {
  15976. // we are transitioning from something which was not an object into object.
  15977. oldValue = internalObject = {};
  15978. oldLength = 0;
  15979. changeDetected++;
  15980. }
  15981. // copy the items to oldValue and look for changes.
  15982. newLength = 0;
  15983. for (key in newValue) {
  15984. if (hasOwnProperty.call(newValue, key)) {
  15985. newLength++;
  15986. newItem = newValue[key];
  15987. oldItem = oldValue[key];
  15988. if (key in oldValue) {
  15989. // eslint-disable-next-line no-self-compare
  15990. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  15991. if (!bothNaN && (oldItem !== newItem)) {
  15992. changeDetected++;
  15993. oldValue[key] = newItem;
  15994. }
  15995. } else {
  15996. oldLength++;
  15997. oldValue[key] = newItem;
  15998. changeDetected++;
  15999. }
  16000. }
  16001. }
  16002. if (oldLength > newLength) {
  16003. // we used to have more keys, need to find them and destroy them.
  16004. changeDetected++;
  16005. for (key in oldValue) {
  16006. if (!hasOwnProperty.call(newValue, key)) {
  16007. oldLength--;
  16008. delete oldValue[key];
  16009. }
  16010. }
  16011. }
  16012. }
  16013. return changeDetected;
  16014. }
  16015. function $watchCollectionAction() {
  16016. if (initRun) {
  16017. initRun = false;
  16018. listener(newValue, newValue, self);
  16019. } else {
  16020. listener(newValue, veryOldValue, self);
  16021. }
  16022. // make a copy for the next time a collection is changed
  16023. if (trackVeryOldValue) {
  16024. if (!isObject(newValue)) {
  16025. //primitive
  16026. veryOldValue = newValue;
  16027. } else if (isArrayLike(newValue)) {
  16028. veryOldValue = new Array(newValue.length);
  16029. for (var i = 0; i < newValue.length; i++) {
  16030. veryOldValue[i] = newValue[i];
  16031. }
  16032. } else { // if object
  16033. veryOldValue = {};
  16034. for (var key in newValue) {
  16035. if (hasOwnProperty.call(newValue, key)) {
  16036. veryOldValue[key] = newValue[key];
  16037. }
  16038. }
  16039. }
  16040. }
  16041. }
  16042. return this.$watch(changeDetector, $watchCollectionAction);
  16043. },
  16044. /**
  16045. * @ngdoc method
  16046. * @name $rootScope.Scope#$digest
  16047. * @kind function
  16048. *
  16049. * @description
  16050. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  16051. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  16052. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  16053. * until no more listeners are firing. This means that it is possible to get into an infinite
  16054. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  16055. * iterations exceeds 10.
  16056. *
  16057. * Usually, you don't call `$digest()` directly in
  16058. * {@link ng.directive:ngController controllers} or in
  16059. * {@link ng.$compileProvider#directive directives}.
  16060. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  16061. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  16062. *
  16063. * If you want to be notified whenever `$digest()` is called,
  16064. * you can register a `watchExpression` function with
  16065. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  16066. *
  16067. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  16068. *
  16069. * # Example
  16070. * ```js
  16071. var scope = ...;
  16072. scope.name = 'misko';
  16073. scope.counter = 0;
  16074. expect(scope.counter).toEqual(0);
  16075. scope.$watch('name', function(newValue, oldValue) {
  16076. scope.counter = scope.counter + 1;
  16077. });
  16078. expect(scope.counter).toEqual(0);
  16079. scope.$digest();
  16080. // the listener is always called during the first $digest loop after it was registered
  16081. expect(scope.counter).toEqual(1);
  16082. scope.$digest();
  16083. // but now it will not be called unless the value changes
  16084. expect(scope.counter).toEqual(1);
  16085. scope.name = 'adam';
  16086. scope.$digest();
  16087. expect(scope.counter).toEqual(2);
  16088. * ```
  16089. *
  16090. */
  16091. $digest: function() {
  16092. var watch, value, last, fn, get,
  16093. watchers,
  16094. dirty, ttl = TTL,
  16095. next, current, target = this,
  16096. watchLog = [],
  16097. logIdx, asyncTask;
  16098. beginPhase('$digest');
  16099. // Check for changes to browser url that happened in sync before the call to $digest
  16100. $browser.$$checkUrlChange();
  16101. if (this === $rootScope && applyAsyncId !== null) {
  16102. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  16103. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  16104. $browser.defer.cancel(applyAsyncId);
  16105. flushApplyAsync();
  16106. }
  16107. lastDirtyWatch = null;
  16108. do { // "while dirty" loop
  16109. dirty = false;
  16110. current = target;
  16111. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  16112. // be reentered recursively. Calling $digest from a function passed to $applyAsync would
  16113. // lead to a '$digest already in progress' error.
  16114. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  16115. try {
  16116. asyncTask = asyncQueue[asyncQueuePosition];
  16117. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  16118. } catch (e) {
  16119. $exceptionHandler(e);
  16120. }
  16121. lastDirtyWatch = null;
  16122. }
  16123. asyncQueue.length = 0;
  16124. traverseScopesLoop:
  16125. do { // "traverse the scopes" loop
  16126. if ((watchers = current.$$watchers)) {
  16127. // process our watches
  16128. watchers.$$digestWatchIndex = watchers.length;
  16129. while (watchers.$$digestWatchIndex--) {
  16130. try {
  16131. watch = watchers[watchers.$$digestWatchIndex];
  16132. // Most common watches are on primitives, in which case we can short
  16133. // circuit it with === operator, only when === fails do we use .equals
  16134. if (watch) {
  16135. get = watch.get;
  16136. if ((value = get(current)) !== (last = watch.last) &&
  16137. !(watch.eq
  16138. ? equals(value, last)
  16139. : (isNumberNaN(value) && isNumberNaN(last)))) {
  16140. dirty = true;
  16141. lastDirtyWatch = watch;
  16142. watch.last = watch.eq ? copy(value, null) : value;
  16143. fn = watch.fn;
  16144. fn(value, ((last === initWatchVal) ? value : last), current);
  16145. if (ttl < 5) {
  16146. logIdx = 4 - ttl;
  16147. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  16148. watchLog[logIdx].push({
  16149. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  16150. newVal: value,
  16151. oldVal: last
  16152. });
  16153. }
  16154. } else if (watch === lastDirtyWatch) {
  16155. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  16156. // have already been tested.
  16157. dirty = false;
  16158. break traverseScopesLoop;
  16159. }
  16160. }
  16161. } catch (e) {
  16162. $exceptionHandler(e);
  16163. }
  16164. }
  16165. }
  16166. // Insanity Warning: scope depth-first traversal
  16167. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16168. // this piece should be kept in sync with the traversal in $broadcast
  16169. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  16170. (current !== target && current.$$nextSibling)))) {
  16171. while (current !== target && !(next = current.$$nextSibling)) {
  16172. current = current.$parent;
  16173. }
  16174. }
  16175. } while ((current = next));
  16176. // `break traverseScopesLoop;` takes us to here
  16177. if ((dirty || asyncQueue.length) && !(ttl--)) {
  16178. clearPhase();
  16179. throw $rootScopeMinErr('infdig',
  16180. '{0} $digest() iterations reached. Aborting!\n' +
  16181. 'Watchers fired in the last 5 iterations: {1}',
  16182. TTL, watchLog);
  16183. }
  16184. } while (dirty || asyncQueue.length);
  16185. clearPhase();
  16186. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  16187. while (postDigestQueuePosition < postDigestQueue.length) {
  16188. try {
  16189. postDigestQueue[postDigestQueuePosition++]();
  16190. } catch (e) {
  16191. $exceptionHandler(e);
  16192. }
  16193. }
  16194. postDigestQueue.length = postDigestQueuePosition = 0;
  16195. // Check for changes to browser url that happened during the $digest
  16196. // (for which no event is fired; e.g. via `history.pushState()`)
  16197. $browser.$$checkUrlChange();
  16198. },
  16199. /**
  16200. * @ngdoc event
  16201. * @name $rootScope.Scope#$destroy
  16202. * @eventType broadcast on scope being destroyed
  16203. *
  16204. * @description
  16205. * Broadcasted when a scope and its children are being destroyed.
  16206. *
  16207. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16208. * clean up DOM bindings before an element is removed from the DOM.
  16209. */
  16210. /**
  16211. * @ngdoc method
  16212. * @name $rootScope.Scope#$destroy
  16213. * @kind function
  16214. *
  16215. * @description
  16216. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  16217. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  16218. * propagate to the current scope and its children. Removal also implies that the current
  16219. * scope is eligible for garbage collection.
  16220. *
  16221. * The `$destroy()` is usually used by directives such as
  16222. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  16223. * unrolling of the loop.
  16224. *
  16225. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  16226. * Application code can register a `$destroy` event handler that will give it a chance to
  16227. * perform any necessary cleanup.
  16228. *
  16229. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16230. * clean up DOM bindings before an element is removed from the DOM.
  16231. */
  16232. $destroy: function() {
  16233. // We can't destroy a scope that has been already destroyed.
  16234. if (this.$$destroyed) return;
  16235. var parent = this.$parent;
  16236. this.$broadcast('$destroy');
  16237. this.$$destroyed = true;
  16238. if (this === $rootScope) {
  16239. //Remove handlers attached to window when $rootScope is removed
  16240. $browser.$$applicationDestroyed();
  16241. }
  16242. incrementWatchersCount(this, -this.$$watchersCount);
  16243. for (var eventName in this.$$listenerCount) {
  16244. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  16245. }
  16246. // sever all the references to parent scopes (after this cleanup, the current scope should
  16247. // not be retained by any of our references and should be eligible for garbage collection)
  16248. if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
  16249. if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
  16250. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  16251. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  16252. // Disable listeners, watchers and apply/digest methods
  16253. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  16254. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  16255. this.$$listeners = {};
  16256. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  16257. this.$$nextSibling = null;
  16258. cleanUpScope(this);
  16259. },
  16260. /**
  16261. * @ngdoc method
  16262. * @name $rootScope.Scope#$eval
  16263. * @kind function
  16264. *
  16265. * @description
  16266. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  16267. * the expression are propagated (uncaught). This is useful when evaluating Angular
  16268. * expressions.
  16269. *
  16270. * # Example
  16271. * ```js
  16272. var scope = ng.$rootScope.Scope();
  16273. scope.a = 1;
  16274. scope.b = 2;
  16275. expect(scope.$eval('a+b')).toEqual(3);
  16276. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  16277. * ```
  16278. *
  16279. * @param {(string|function())=} expression An angular expression to be executed.
  16280. *
  16281. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16282. * - `function(scope)`: execute the function with the current `scope` parameter.
  16283. *
  16284. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16285. * @returns {*} The result of evaluating the expression.
  16286. */
  16287. $eval: function(expr, locals) {
  16288. return $parse(expr)(this, locals);
  16289. },
  16290. /**
  16291. * @ngdoc method
  16292. * @name $rootScope.Scope#$evalAsync
  16293. * @kind function
  16294. *
  16295. * @description
  16296. * Executes the expression on the current scope at a later point in time.
  16297. *
  16298. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  16299. * that:
  16300. *
  16301. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  16302. * rendering).
  16303. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  16304. * `expression` execution.
  16305. *
  16306. * Any exceptions from the execution of the expression are forwarded to the
  16307. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16308. *
  16309. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  16310. * will be scheduled. However, it is encouraged to always call code that changes the model
  16311. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  16312. *
  16313. * @param {(string|function())=} expression An angular expression to be executed.
  16314. *
  16315. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16316. * - `function(scope)`: execute the function with the current `scope` parameter.
  16317. *
  16318. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16319. */
  16320. $evalAsync: function(expr, locals) {
  16321. // if we are outside of an $digest loop and this is the first time we are scheduling async
  16322. // task also schedule async auto-flush
  16323. if (!$rootScope.$$phase && !asyncQueue.length) {
  16324. $browser.defer(function() {
  16325. if (asyncQueue.length) {
  16326. $rootScope.$digest();
  16327. }
  16328. });
  16329. }
  16330. asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
  16331. },
  16332. $$postDigest: function(fn) {
  16333. postDigestQueue.push(fn);
  16334. },
  16335. /**
  16336. * @ngdoc method
  16337. * @name $rootScope.Scope#$apply
  16338. * @kind function
  16339. *
  16340. * @description
  16341. * `$apply()` is used to execute an expression in angular from outside of the angular
  16342. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  16343. * Because we are calling into the angular framework we need to perform proper scope life
  16344. * cycle of {@link ng.$exceptionHandler exception handling},
  16345. * {@link ng.$rootScope.Scope#$digest executing watches}.
  16346. *
  16347. * ## Life cycle
  16348. *
  16349. * # Pseudo-Code of `$apply()`
  16350. * ```js
  16351. function $apply(expr) {
  16352. try {
  16353. return $eval(expr);
  16354. } catch (e) {
  16355. $exceptionHandler(e);
  16356. } finally {
  16357. $root.$digest();
  16358. }
  16359. }
  16360. * ```
  16361. *
  16362. *
  16363. * Scope's `$apply()` method transitions through the following stages:
  16364. *
  16365. * 1. The {@link guide/expression expression} is executed using the
  16366. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  16367. * 2. Any exceptions from the execution of the expression are forwarded to the
  16368. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16369. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  16370. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  16371. *
  16372. *
  16373. * @param {(string|function())=} exp An angular expression to be executed.
  16374. *
  16375. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16376. * - `function(scope)`: execute the function with current `scope` parameter.
  16377. *
  16378. * @returns {*} The result of evaluating the expression.
  16379. */
  16380. $apply: function(expr) {
  16381. try {
  16382. beginPhase('$apply');
  16383. try {
  16384. return this.$eval(expr);
  16385. } finally {
  16386. clearPhase();
  16387. }
  16388. } catch (e) {
  16389. $exceptionHandler(e);
  16390. } finally {
  16391. try {
  16392. $rootScope.$digest();
  16393. } catch (e) {
  16394. $exceptionHandler(e);
  16395. // eslint-disable-next-line no-unsafe-finally
  16396. throw e;
  16397. }
  16398. }
  16399. },
  16400. /**
  16401. * @ngdoc method
  16402. * @name $rootScope.Scope#$applyAsync
  16403. * @kind function
  16404. *
  16405. * @description
  16406. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  16407. * varies across browsers, but is typically around ~10 milliseconds.
  16408. *
  16409. * This can be used to queue up multiple expressions which need to be evaluated in the same
  16410. * digest.
  16411. *
  16412. * @param {(string|function())=} exp An angular expression to be executed.
  16413. *
  16414. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16415. * - `function(scope)`: execute the function with current `scope` parameter.
  16416. */
  16417. $applyAsync: function(expr) {
  16418. var scope = this;
  16419. if (expr) {
  16420. applyAsyncQueue.push($applyAsyncExpression);
  16421. }
  16422. expr = $parse(expr);
  16423. scheduleApplyAsync();
  16424. function $applyAsyncExpression() {
  16425. scope.$eval(expr);
  16426. }
  16427. },
  16428. /**
  16429. * @ngdoc method
  16430. * @name $rootScope.Scope#$on
  16431. * @kind function
  16432. *
  16433. * @description
  16434. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  16435. * discussion of event life cycle.
  16436. *
  16437. * The event listener function format is: `function(event, args...)`. The `event` object
  16438. * passed into the listener has the following attributes:
  16439. *
  16440. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  16441. * `$broadcast`-ed.
  16442. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  16443. * event propagates through the scope hierarchy, this property is set to null.
  16444. * - `name` - `{string}`: name of the event.
  16445. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  16446. * further event propagation (available only for events that were `$emit`-ed).
  16447. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  16448. * to true.
  16449. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  16450. *
  16451. * @param {string} name Event name to listen on.
  16452. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  16453. * @returns {function()} Returns a deregistration function for this listener.
  16454. */
  16455. $on: function(name, listener) {
  16456. var namedListeners = this.$$listeners[name];
  16457. if (!namedListeners) {
  16458. this.$$listeners[name] = namedListeners = [];
  16459. }
  16460. namedListeners.push(listener);
  16461. var current = this;
  16462. do {
  16463. if (!current.$$listenerCount[name]) {
  16464. current.$$listenerCount[name] = 0;
  16465. }
  16466. current.$$listenerCount[name]++;
  16467. } while ((current = current.$parent));
  16468. var self = this;
  16469. return function() {
  16470. var indexOfListener = namedListeners.indexOf(listener);
  16471. if (indexOfListener !== -1) {
  16472. namedListeners[indexOfListener] = null;
  16473. decrementListenerCount(self, 1, name);
  16474. }
  16475. };
  16476. },
  16477. /**
  16478. * @ngdoc method
  16479. * @name $rootScope.Scope#$emit
  16480. * @kind function
  16481. *
  16482. * @description
  16483. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  16484. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16485. *
  16486. * The event life cycle starts at the scope on which `$emit` was called. All
  16487. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16488. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  16489. * registered listeners along the way. The event will stop propagating if one of the listeners
  16490. * cancels it.
  16491. *
  16492. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16493. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16494. *
  16495. * @param {string} name Event name to emit.
  16496. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16497. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  16498. */
  16499. $emit: function(name, args) {
  16500. var empty = [],
  16501. namedListeners,
  16502. scope = this,
  16503. stopPropagation = false,
  16504. event = {
  16505. name: name,
  16506. targetScope: scope,
  16507. stopPropagation: function() {stopPropagation = true;},
  16508. preventDefault: function() {
  16509. event.defaultPrevented = true;
  16510. },
  16511. defaultPrevented: false
  16512. },
  16513. listenerArgs = concat([event], arguments, 1),
  16514. i, length;
  16515. do {
  16516. namedListeners = scope.$$listeners[name] || empty;
  16517. event.currentScope = scope;
  16518. for (i = 0, length = namedListeners.length; i < length; i++) {
  16519. // if listeners were deregistered, defragment the array
  16520. if (!namedListeners[i]) {
  16521. namedListeners.splice(i, 1);
  16522. i--;
  16523. length--;
  16524. continue;
  16525. }
  16526. try {
  16527. //allow all listeners attached to the current scope to run
  16528. namedListeners[i].apply(null, listenerArgs);
  16529. } catch (e) {
  16530. $exceptionHandler(e);
  16531. }
  16532. }
  16533. //if any listener on the current scope stops propagation, prevent bubbling
  16534. if (stopPropagation) {
  16535. event.currentScope = null;
  16536. return event;
  16537. }
  16538. //traverse upwards
  16539. scope = scope.$parent;
  16540. } while (scope);
  16541. event.currentScope = null;
  16542. return event;
  16543. },
  16544. /**
  16545. * @ngdoc method
  16546. * @name $rootScope.Scope#$broadcast
  16547. * @kind function
  16548. *
  16549. * @description
  16550. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  16551. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16552. *
  16553. * The event life cycle starts at the scope on which `$broadcast` was called. All
  16554. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16555. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  16556. * scope and calls all registered listeners along the way. The event cannot be canceled.
  16557. *
  16558. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16559. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16560. *
  16561. * @param {string} name Event name to broadcast.
  16562. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16563. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  16564. */
  16565. $broadcast: function(name, args) {
  16566. var target = this,
  16567. current = target,
  16568. next = target,
  16569. event = {
  16570. name: name,
  16571. targetScope: target,
  16572. preventDefault: function() {
  16573. event.defaultPrevented = true;
  16574. },
  16575. defaultPrevented: false
  16576. };
  16577. if (!target.$$listenerCount[name]) return event;
  16578. var listenerArgs = concat([event], arguments, 1),
  16579. listeners, i, length;
  16580. //down while you can, then up and next sibling or up and next sibling until back at root
  16581. while ((current = next)) {
  16582. event.currentScope = current;
  16583. listeners = current.$$listeners[name] || [];
  16584. for (i = 0, length = listeners.length; i < length; i++) {
  16585. // if listeners were deregistered, defragment the array
  16586. if (!listeners[i]) {
  16587. listeners.splice(i, 1);
  16588. i--;
  16589. length--;
  16590. continue;
  16591. }
  16592. try {
  16593. listeners[i].apply(null, listenerArgs);
  16594. } catch (e) {
  16595. $exceptionHandler(e);
  16596. }
  16597. }
  16598. // Insanity Warning: scope depth-first traversal
  16599. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16600. // this piece should be kept in sync with the traversal in $digest
  16601. // (though it differs due to having the extra check for $$listenerCount)
  16602. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  16603. (current !== target && current.$$nextSibling)))) {
  16604. while (current !== target && !(next = current.$$nextSibling)) {
  16605. current = current.$parent;
  16606. }
  16607. }
  16608. }
  16609. event.currentScope = null;
  16610. return event;
  16611. }
  16612. };
  16613. var $rootScope = new Scope();
  16614. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  16615. var asyncQueue = $rootScope.$$asyncQueue = [];
  16616. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  16617. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  16618. var postDigestQueuePosition = 0;
  16619. return $rootScope;
  16620. function beginPhase(phase) {
  16621. if ($rootScope.$$phase) {
  16622. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  16623. }
  16624. $rootScope.$$phase = phase;
  16625. }
  16626. function clearPhase() {
  16627. $rootScope.$$phase = null;
  16628. }
  16629. function incrementWatchersCount(current, count) {
  16630. do {
  16631. current.$$watchersCount += count;
  16632. } while ((current = current.$parent));
  16633. }
  16634. function decrementListenerCount(current, count, name) {
  16635. do {
  16636. current.$$listenerCount[name] -= count;
  16637. if (current.$$listenerCount[name] === 0) {
  16638. delete current.$$listenerCount[name];
  16639. }
  16640. } while ((current = current.$parent));
  16641. }
  16642. /**
  16643. * function used as an initial value for watchers.
  16644. * because it's unique we can easily tell it apart from other values
  16645. */
  16646. function initWatchVal() {}
  16647. function flushApplyAsync() {
  16648. while (applyAsyncQueue.length) {
  16649. try {
  16650. applyAsyncQueue.shift()();
  16651. } catch (e) {
  16652. $exceptionHandler(e);
  16653. }
  16654. }
  16655. applyAsyncId = null;
  16656. }
  16657. function scheduleApplyAsync() {
  16658. if (applyAsyncId === null) {
  16659. applyAsyncId = $browser.defer(function() {
  16660. $rootScope.$apply(flushApplyAsync);
  16661. });
  16662. }
  16663. }
  16664. }];
  16665. }
  16666. /**
  16667. * @ngdoc service
  16668. * @name $rootElement
  16669. *
  16670. * @description
  16671. * The root element of Angular application. This is either the element where {@link
  16672. * ng.directive:ngApp ngApp} was declared or the element passed into
  16673. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  16674. * location where the application's {@link auto.$injector $injector} service gets
  16675. * published, and can be retrieved using `$rootElement.injector()`.
  16676. */
  16677. // the implementation is in angular.bootstrap
  16678. /**
  16679. * @this
  16680. * @description
  16681. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  16682. */
  16683. function $$SanitizeUriProvider() {
  16684. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  16685. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  16686. /**
  16687. * @description
  16688. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16689. * urls during a[href] sanitization.
  16690. *
  16691. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16692. *
  16693. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  16694. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  16695. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16696. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16697. *
  16698. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16699. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16700. * chaining otherwise.
  16701. */
  16702. this.aHrefSanitizationWhitelist = function(regexp) {
  16703. if (isDefined(regexp)) {
  16704. aHrefSanitizationWhitelist = regexp;
  16705. return this;
  16706. }
  16707. return aHrefSanitizationWhitelist;
  16708. };
  16709. /**
  16710. * @description
  16711. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16712. * urls during img[src] sanitization.
  16713. *
  16714. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16715. *
  16716. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  16717. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  16718. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16719. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16720. *
  16721. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16722. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16723. * chaining otherwise.
  16724. */
  16725. this.imgSrcSanitizationWhitelist = function(regexp) {
  16726. if (isDefined(regexp)) {
  16727. imgSrcSanitizationWhitelist = regexp;
  16728. return this;
  16729. }
  16730. return imgSrcSanitizationWhitelist;
  16731. };
  16732. this.$get = function() {
  16733. return function sanitizeUri(uri, isImage) {
  16734. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  16735. var normalizedVal;
  16736. normalizedVal = urlResolve(uri).href;
  16737. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  16738. return 'unsafe:' + normalizedVal;
  16739. }
  16740. return uri;
  16741. };
  16742. };
  16743. }
  16744. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  16745. * Any commits to this file should be reviewed with security in mind. *
  16746. * Changes to this file can potentially create security vulnerabilities. *
  16747. * An approval from 2 Core members with history of modifying *
  16748. * this file is required. *
  16749. * *
  16750. * Does the change somehow allow for arbitrary javascript to be executed? *
  16751. * Or allows for someone to change the prototype of built-in objects? *
  16752. * Or gives undesired access to variables likes document or window? *
  16753. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  16754. /* exported $SceProvider, $SceDelegateProvider */
  16755. var $sceMinErr = minErr('$sce');
  16756. var SCE_CONTEXTS = {
  16757. HTML: 'html',
  16758. CSS: 'css',
  16759. URL: 'url',
  16760. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  16761. // url. (e.g. ng-include, script src, templateUrl)
  16762. RESOURCE_URL: 'resourceUrl',
  16763. JS: 'js'
  16764. };
  16765. // Helper functions follow.
  16766. var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;
  16767. function snakeToCamel(name) {
  16768. return name
  16769. .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);
  16770. }
  16771. function adjustMatcher(matcher) {
  16772. if (matcher === 'self') {
  16773. return matcher;
  16774. } else if (isString(matcher)) {
  16775. // Strings match exactly except for 2 wildcards - '*' and '**'.
  16776. // '*' matches any character except those from the set ':/.?&'.
  16777. // '**' matches any character (like .* in a RegExp).
  16778. // More than 2 *'s raises an error as it's ill defined.
  16779. if (matcher.indexOf('***') > -1) {
  16780. throw $sceMinErr('iwcard',
  16781. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  16782. }
  16783. matcher = escapeForRegexp(matcher).
  16784. replace(/\\\*\\\*/g, '.*').
  16785. replace(/\\\*/g, '[^:/.?&;]*');
  16786. return new RegExp('^' + matcher + '$');
  16787. } else if (isRegExp(matcher)) {
  16788. // The only other type of matcher allowed is a Regexp.
  16789. // Match entire URL / disallow partial matches.
  16790. // Flags are reset (i.e. no global, ignoreCase or multiline)
  16791. return new RegExp('^' + matcher.source + '$');
  16792. } else {
  16793. throw $sceMinErr('imatcher',
  16794. 'Matchers may only be "self", string patterns or RegExp objects');
  16795. }
  16796. }
  16797. function adjustMatchers(matchers) {
  16798. var adjustedMatchers = [];
  16799. if (isDefined(matchers)) {
  16800. forEach(matchers, function(matcher) {
  16801. adjustedMatchers.push(adjustMatcher(matcher));
  16802. });
  16803. }
  16804. return adjustedMatchers;
  16805. }
  16806. /**
  16807. * @ngdoc service
  16808. * @name $sceDelegate
  16809. * @kind function
  16810. *
  16811. * @description
  16812. *
  16813. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  16814. * Contextual Escaping (SCE)} services to AngularJS.
  16815. *
  16816. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  16817. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  16818. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  16819. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  16820. * work because `$sce` delegates to `$sceDelegate` for these operations.
  16821. *
  16822. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  16823. *
  16824. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  16825. * can override it completely to change the behavior of `$sce`, the common case would
  16826. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  16827. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  16828. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  16829. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  16830. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16831. */
  16832. /**
  16833. * @ngdoc provider
  16834. * @name $sceDelegateProvider
  16835. * @this
  16836. *
  16837. * @description
  16838. *
  16839. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  16840. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  16841. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  16842. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  16843. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16844. *
  16845. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  16846. * Strict Contextual Escaping (SCE)}.
  16847. *
  16848. * **Example**: Consider the following case. <a name="example"></a>
  16849. *
  16850. * - your app is hosted at url `http://myapp.example.com/`
  16851. * - but some of your templates are hosted on other domains you control such as
  16852. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  16853. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  16854. *
  16855. * Here is what a secure configuration for this scenario might look like:
  16856. *
  16857. * ```
  16858. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  16859. * $sceDelegateProvider.resourceUrlWhitelist([
  16860. * // Allow same origin resource loads.
  16861. * 'self',
  16862. * // Allow loading from our assets domain. Notice the difference between * and **.
  16863. * 'http://srv*.assets.example.com/**'
  16864. * ]);
  16865. *
  16866. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  16867. * $sceDelegateProvider.resourceUrlBlacklist([
  16868. * 'http://myapp.example.com/clickThru**'
  16869. * ]);
  16870. * });
  16871. * ```
  16872. */
  16873. function $SceDelegateProvider() {
  16874. this.SCE_CONTEXTS = SCE_CONTEXTS;
  16875. // Resource URLs can also be trusted by policy.
  16876. var resourceUrlWhitelist = ['self'],
  16877. resourceUrlBlacklist = [];
  16878. /**
  16879. * @ngdoc method
  16880. * @name $sceDelegateProvider#resourceUrlWhitelist
  16881. * @kind function
  16882. *
  16883. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  16884. * provided. This must be an array or null. A snapshot of this array is used so further
  16885. * changes to the array are ignored.
  16886. *
  16887. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  16888. * allowed in this array.
  16889. *
  16890. * <div class="alert alert-warning">
  16891. * **Note:** an empty whitelist array will block all URLs!
  16892. * </div>
  16893. *
  16894. * @return {Array} the currently set whitelist array.
  16895. *
  16896. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  16897. * same origin resource requests.
  16898. *
  16899. * @description
  16900. * Sets/Gets the whitelist of trusted resource URLs.
  16901. */
  16902. this.resourceUrlWhitelist = function(value) {
  16903. if (arguments.length) {
  16904. resourceUrlWhitelist = adjustMatchers(value);
  16905. }
  16906. return resourceUrlWhitelist;
  16907. };
  16908. /**
  16909. * @ngdoc method
  16910. * @name $sceDelegateProvider#resourceUrlBlacklist
  16911. * @kind function
  16912. *
  16913. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  16914. * provided. This must be an array or null. A snapshot of this array is used so further
  16915. * changes to the array are ignored.
  16916. *
  16917. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  16918. * allowed in this array.
  16919. *
  16920. * The typical usage for the blacklist is to **block
  16921. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  16922. * these would otherwise be trusted but actually return content from the redirected domain.
  16923. *
  16924. * Finally, **the blacklist overrides the whitelist** and has the final say.
  16925. *
  16926. * @return {Array} the currently set blacklist array.
  16927. *
  16928. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  16929. * is no blacklist.)
  16930. *
  16931. * @description
  16932. * Sets/Gets the blacklist of trusted resource URLs.
  16933. */
  16934. this.resourceUrlBlacklist = function(value) {
  16935. if (arguments.length) {
  16936. resourceUrlBlacklist = adjustMatchers(value);
  16937. }
  16938. return resourceUrlBlacklist;
  16939. };
  16940. this.$get = ['$injector', function($injector) {
  16941. var htmlSanitizer = function htmlSanitizer(html) {
  16942. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  16943. };
  16944. if ($injector.has('$sanitize')) {
  16945. htmlSanitizer = $injector.get('$sanitize');
  16946. }
  16947. function matchUrl(matcher, parsedUrl) {
  16948. if (matcher === 'self') {
  16949. return urlIsSameOrigin(parsedUrl);
  16950. } else {
  16951. // definitely a regex. See adjustMatchers()
  16952. return !!matcher.exec(parsedUrl.href);
  16953. }
  16954. }
  16955. function isResourceUrlAllowedByPolicy(url) {
  16956. var parsedUrl = urlResolve(url.toString());
  16957. var i, n, allowed = false;
  16958. // Ensure that at least one item from the whitelist allows this url.
  16959. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  16960. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  16961. allowed = true;
  16962. break;
  16963. }
  16964. }
  16965. if (allowed) {
  16966. // Ensure that no item from the blacklist blocked this url.
  16967. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  16968. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  16969. allowed = false;
  16970. break;
  16971. }
  16972. }
  16973. }
  16974. return allowed;
  16975. }
  16976. function generateHolderType(Base) {
  16977. var holderType = function TrustedValueHolderType(trustedValue) {
  16978. this.$$unwrapTrustedValue = function() {
  16979. return trustedValue;
  16980. };
  16981. };
  16982. if (Base) {
  16983. holderType.prototype = new Base();
  16984. }
  16985. holderType.prototype.valueOf = function sceValueOf() {
  16986. return this.$$unwrapTrustedValue();
  16987. };
  16988. holderType.prototype.toString = function sceToString() {
  16989. return this.$$unwrapTrustedValue().toString();
  16990. };
  16991. return holderType;
  16992. }
  16993. var trustedValueHolderBase = generateHolderType(),
  16994. byType = {};
  16995. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  16996. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  16997. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  16998. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  16999. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  17000. /**
  17001. * @ngdoc method
  17002. * @name $sceDelegate#trustAs
  17003. *
  17004. * @description
  17005. * Returns an object that is trusted by angular for use in specified strict
  17006. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  17007. * attribute interpolation, any dom event binding attribute interpolation
  17008. * such as for onclick, etc.) that uses the provided value.
  17009. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  17010. *
  17011. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  17012. * resourceUrl, html, js and css.
  17013. * @param {*} value The value that that should be considered trusted/safe.
  17014. * @returns {*} A value that can be used to stand in for the provided `value` in places
  17015. * where Angular expects a $sce.trustAs() return value.
  17016. */
  17017. function trustAs(type, trustedValue) {
  17018. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17019. if (!Constructor) {
  17020. throw $sceMinErr('icontext',
  17021. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  17022. type, trustedValue);
  17023. }
  17024. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  17025. return trustedValue;
  17026. }
  17027. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  17028. // mutable objects, we ensure here that the value passed in is actually a string.
  17029. if (typeof trustedValue !== 'string') {
  17030. throw $sceMinErr('itype',
  17031. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  17032. type);
  17033. }
  17034. return new Constructor(trustedValue);
  17035. }
  17036. /**
  17037. * @ngdoc method
  17038. * @name $sceDelegate#valueOf
  17039. *
  17040. * @description
  17041. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  17042. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  17043. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  17044. *
  17045. * If the passed parameter is not a value that had been returned by {@link
  17046. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  17047. *
  17048. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  17049. * call or anything else.
  17050. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  17051. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  17052. * `value` unchanged.
  17053. */
  17054. function valueOf(maybeTrusted) {
  17055. if (maybeTrusted instanceof trustedValueHolderBase) {
  17056. return maybeTrusted.$$unwrapTrustedValue();
  17057. } else {
  17058. return maybeTrusted;
  17059. }
  17060. }
  17061. /**
  17062. * @ngdoc method
  17063. * @name $sceDelegate#getTrusted
  17064. *
  17065. * @description
  17066. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  17067. * returns the originally supplied value if the queried context type is a supertype of the
  17068. * created type. If this condition isn't satisfied, throws an exception.
  17069. *
  17070. * <div class="alert alert-danger">
  17071. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  17072. * (XSS) vulnerability in your application.
  17073. * </div>
  17074. *
  17075. * @param {string} type The kind of context in which this value is to be used.
  17076. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  17077. * `$sceDelegate.trustAs`} call.
  17078. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  17079. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  17080. */
  17081. function getTrusted(type, maybeTrusted) {
  17082. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  17083. return maybeTrusted;
  17084. }
  17085. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17086. if (constructor && maybeTrusted instanceof constructor) {
  17087. return maybeTrusted.$$unwrapTrustedValue();
  17088. }
  17089. // If we get here, then we may only take one of two actions.
  17090. // 1. sanitize the value for the requested type, or
  17091. // 2. throw an exception.
  17092. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  17093. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  17094. return maybeTrusted;
  17095. } else {
  17096. throw $sceMinErr('insecurl',
  17097. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  17098. maybeTrusted.toString());
  17099. }
  17100. } else if (type === SCE_CONTEXTS.HTML) {
  17101. return htmlSanitizer(maybeTrusted);
  17102. }
  17103. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17104. }
  17105. return { trustAs: trustAs,
  17106. getTrusted: getTrusted,
  17107. valueOf: valueOf };
  17108. }];
  17109. }
  17110. /**
  17111. * @ngdoc provider
  17112. * @name $sceProvider
  17113. * @this
  17114. *
  17115. * @description
  17116. *
  17117. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  17118. * - enable/disable Strict Contextual Escaping (SCE) in a module
  17119. * - override the default implementation with a custom delegate
  17120. *
  17121. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  17122. */
  17123. /**
  17124. * @ngdoc service
  17125. * @name $sce
  17126. * @kind function
  17127. *
  17128. * @description
  17129. *
  17130. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  17131. *
  17132. * # Strict Contextual Escaping
  17133. *
  17134. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  17135. * contexts to result in a value that is marked as safe to use for that context. One example of
  17136. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  17137. * to these contexts as privileged or SCE contexts.
  17138. *
  17139. * As of version 1.2, Angular ships with SCE enabled by default.
  17140. *
  17141. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  17142. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  17143. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  17144. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  17145. * to the top of your HTML document.
  17146. *
  17147. * SCE assists in writing code in a way that (a) is secure by default and (b) makes auditing for
  17148. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  17149. *
  17150. * Here's an example of a binding in a privileged context:
  17151. *
  17152. * ```
  17153. * <input ng-model="userHtml" aria-label="User input">
  17154. * <div ng-bind-html="userHtml"></div>
  17155. * ```
  17156. *
  17157. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  17158. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  17159. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  17160. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  17161. * security vulnerabilities.)
  17162. *
  17163. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  17164. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  17165. *
  17166. * How would you ensure that every place that used these types of bindings was bound to a value that
  17167. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  17168. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  17169. * properties/fields and forgot to update the binding to the sanitized value?
  17170. *
  17171. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  17172. * determine that something explicitly says it's safe to use a value for binding in that
  17173. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  17174. * for those values that you can easily tell are safe - because they were received from your server,
  17175. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  17176. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  17177. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  17178. *
  17179. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  17180. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  17181. * obtain values that will be accepted by SCE / privileged contexts.
  17182. *
  17183. *
  17184. * ## How does it work?
  17185. *
  17186. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  17187. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  17188. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  17189. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  17190. *
  17191. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  17192. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  17193. * simplified):
  17194. *
  17195. * ```
  17196. * var ngBindHtmlDirective = ['$sce', function($sce) {
  17197. * return function(scope, element, attr) {
  17198. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  17199. * element.html(value || '');
  17200. * });
  17201. * };
  17202. * }];
  17203. * ```
  17204. *
  17205. * ## Impact on loading templates
  17206. *
  17207. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  17208. * `templateUrl`'s specified by {@link guide/directive directives}.
  17209. *
  17210. * By default, Angular only loads templates from the same domain and protocol as the application
  17211. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  17212. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  17213. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  17214. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  17215. *
  17216. * *Please note*:
  17217. * The browser's
  17218. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  17219. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  17220. * policy apply in addition to this and may further restrict whether the template is successfully
  17221. * loaded. This means that without the right CORS policy, loading templates from a different domain
  17222. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  17223. * browsers.
  17224. *
  17225. * ## This feels like too much overhead
  17226. *
  17227. * It's important to remember that SCE only applies to interpolation expressions.
  17228. *
  17229. * If your expressions are constant literals, they're automatically trusted and you don't need to
  17230. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  17231. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  17232. *
  17233. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  17234. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  17235. *
  17236. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  17237. * templates in `ng-include` from your application's domain without having to even know about SCE.
  17238. * It blocks loading templates from other domains or loading templates over http from an https
  17239. * served document. You can change these by setting your own custom {@link
  17240. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  17241. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  17242. *
  17243. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  17244. * application that's secure and can be audited to verify that with much more ease than bolting
  17245. * security onto an application later.
  17246. *
  17247. * <a name="contexts"></a>
  17248. * ## What trusted context types are supported?
  17249. *
  17250. * | Context | Notes |
  17251. * |---------------------|----------------|
  17252. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
  17253. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  17254. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
  17255. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG`, `VIDEO`, `AUDIO`, `SOURCE`, and `TRACK` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  17256. * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
  17257. *
  17258. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  17259. *
  17260. * Each element in these arrays must be one of the following:
  17261. *
  17262. * - **'self'**
  17263. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  17264. * domain** as the application document using the **same protocol**.
  17265. * - **String** (except the special value `'self'`)
  17266. * - The string is matched against the full *normalized / absolute URL* of the resource
  17267. * being tested (substring matches are not good enough.)
  17268. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  17269. * match themselves.
  17270. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  17271. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  17272. * in a whitelist.
  17273. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  17274. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  17275. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  17276. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  17277. * http://foo.example.com/templates/**).
  17278. * - **RegExp** (*see caveat below*)
  17279. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  17280. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  17281. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  17282. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  17283. * small number of cases. A `.` character in the regex used when matching the scheme or a
  17284. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  17285. * is highly recommended to use the string patterns and only fall back to regular expressions
  17286. * as a last resort.
  17287. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  17288. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  17289. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  17290. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  17291. * - If you are generating your JavaScript from some other templating engine (not
  17292. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  17293. * remember to escape your regular expression (and be aware that you might need more than
  17294. * one level of escaping depending on your templating engine and the way you interpolated
  17295. * the value.) Do make use of your platform's escaping mechanism as it might be good
  17296. * enough before coding your own. E.g. Ruby has
  17297. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  17298. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  17299. * Javascript lacks a similar built in function for escaping. Take a look at Google
  17300. * Closure library's [goog.string.regExpEscape(s)](
  17301. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  17302. *
  17303. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  17304. *
  17305. * ## Show me an example using SCE.
  17306. *
  17307. * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
  17308. * <file name="index.html">
  17309. * <div ng-controller="AppController as myCtrl">
  17310. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  17311. * <b>User comments</b><br>
  17312. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  17313. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  17314. * exploit.
  17315. * <div class="well">
  17316. * <div ng-repeat="userComment in myCtrl.userComments">
  17317. * <b>{{userComment.name}}</b>:
  17318. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  17319. * <br>
  17320. * </div>
  17321. * </div>
  17322. * </div>
  17323. * </file>
  17324. *
  17325. * <file name="script.js">
  17326. * angular.module('mySceApp', ['ngSanitize'])
  17327. * .controller('AppController', ['$http', '$templateCache', '$sce',
  17328. * function AppController($http, $templateCache, $sce) {
  17329. * var self = this;
  17330. * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {
  17331. * self.userComments = response.data;
  17332. * });
  17333. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  17334. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17335. * 'sanitization.&quot;">Hover over this text.</span>');
  17336. * }]);
  17337. * </file>
  17338. *
  17339. * <file name="test_data.json">
  17340. * [
  17341. * { "name": "Alice",
  17342. * "htmlComment":
  17343. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  17344. * },
  17345. * { "name": "Bob",
  17346. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  17347. * }
  17348. * ]
  17349. * </file>
  17350. *
  17351. * <file name="protractor.js" type="protractor">
  17352. * describe('SCE doc demo', function() {
  17353. * it('should sanitize untrusted values', function() {
  17354. * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
  17355. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  17356. * });
  17357. *
  17358. * it('should NOT sanitize explicitly trusted values', function() {
  17359. * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
  17360. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17361. * 'sanitization.&quot;">Hover over this text.</span>');
  17362. * });
  17363. * });
  17364. * </file>
  17365. * </example>
  17366. *
  17367. *
  17368. *
  17369. * ## Can I disable SCE completely?
  17370. *
  17371. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  17372. * for little coding overhead. It will be much harder to take an SCE disabled application and
  17373. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  17374. * for cases where you have a lot of existing code that was written before SCE was introduced and
  17375. * you're migrating them a module at a time.
  17376. *
  17377. * That said, here's how you can completely disable SCE:
  17378. *
  17379. * ```
  17380. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  17381. * // Completely disable SCE. For demonstration purposes only!
  17382. * // Do not use in new projects.
  17383. * $sceProvider.enabled(false);
  17384. * });
  17385. * ```
  17386. *
  17387. */
  17388. function $SceProvider() {
  17389. var enabled = true;
  17390. /**
  17391. * @ngdoc method
  17392. * @name $sceProvider#enabled
  17393. * @kind function
  17394. *
  17395. * @param {boolean=} value If provided, then enables/disables SCE.
  17396. * @return {boolean} true if SCE is enabled, false otherwise.
  17397. *
  17398. * @description
  17399. * Enables/disables SCE and returns the current value.
  17400. */
  17401. this.enabled = function(value) {
  17402. if (arguments.length) {
  17403. enabled = !!value;
  17404. }
  17405. return enabled;
  17406. };
  17407. /* Design notes on the default implementation for SCE.
  17408. *
  17409. * The API contract for the SCE delegate
  17410. * -------------------------------------
  17411. * The SCE delegate object must provide the following 3 methods:
  17412. *
  17413. * - trustAs(contextEnum, value)
  17414. * This method is used to tell the SCE service that the provided value is OK to use in the
  17415. * contexts specified by contextEnum. It must return an object that will be accepted by
  17416. * getTrusted() for a compatible contextEnum and return this value.
  17417. *
  17418. * - valueOf(value)
  17419. * For values that were not produced by trustAs(), return them as is. For values that were
  17420. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  17421. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  17422. * such a value.
  17423. *
  17424. * - getTrusted(contextEnum, value)
  17425. * This function should return the a value that is safe to use in the context specified by
  17426. * contextEnum or throw and exception otherwise.
  17427. *
  17428. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  17429. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  17430. * instance, an implementation could maintain a registry of all trusted objects by context. In
  17431. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  17432. * return the same object passed in if it was found in the registry under a compatible context or
  17433. * throw an exception otherwise. An implementation might only wrap values some of the time based
  17434. * on some criteria. getTrusted() might return a value and not throw an exception for special
  17435. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  17436. *
  17437. *
  17438. * A note on the inheritance model for SCE contexts
  17439. * ------------------------------------------------
  17440. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  17441. * is purely an implementation details.
  17442. *
  17443. * The contract is simply this:
  17444. *
  17445. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  17446. * will also succeed.
  17447. *
  17448. * Inheritance happens to capture this in a natural way. In some future, we
  17449. * may not use inheritance anymore. That is OK because no code outside of
  17450. * sce.js and sceSpecs.js would need to be aware of this detail.
  17451. */
  17452. this.$get = ['$parse', '$sceDelegate', function(
  17453. $parse, $sceDelegate) {
  17454. // Support: IE 9-11 only
  17455. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  17456. // the "expression(javascript expression)" syntax which is insecure.
  17457. if (enabled && msie < 8) {
  17458. throw $sceMinErr('iequirks',
  17459. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  17460. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  17461. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  17462. }
  17463. var sce = shallowCopy(SCE_CONTEXTS);
  17464. /**
  17465. * @ngdoc method
  17466. * @name $sce#isEnabled
  17467. * @kind function
  17468. *
  17469. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  17470. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  17471. *
  17472. * @description
  17473. * Returns a boolean indicating if SCE is enabled.
  17474. */
  17475. sce.isEnabled = function() {
  17476. return enabled;
  17477. };
  17478. sce.trustAs = $sceDelegate.trustAs;
  17479. sce.getTrusted = $sceDelegate.getTrusted;
  17480. sce.valueOf = $sceDelegate.valueOf;
  17481. if (!enabled) {
  17482. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  17483. sce.valueOf = identity;
  17484. }
  17485. /**
  17486. * @ngdoc method
  17487. * @name $sce#parseAs
  17488. *
  17489. * @description
  17490. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  17491. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  17492. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  17493. * *result*)}
  17494. *
  17495. * @param {string} type The kind of SCE context in which this result will be used.
  17496. * @param {string} expression String expression to compile.
  17497. * @returns {function(context, locals)} a function which represents the compiled expression:
  17498. *
  17499. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17500. * are evaluated against (typically a scope object).
  17501. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17502. * `context`.
  17503. */
  17504. sce.parseAs = function sceParseAs(type, expr) {
  17505. var parsed = $parse(expr);
  17506. if (parsed.literal && parsed.constant) {
  17507. return parsed;
  17508. } else {
  17509. return $parse(expr, function(value) {
  17510. return sce.getTrusted(type, value);
  17511. });
  17512. }
  17513. };
  17514. /**
  17515. * @ngdoc method
  17516. * @name $sce#trustAs
  17517. *
  17518. * @description
  17519. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  17520. * returns an object that is trusted by angular for use in specified strict contextual
  17521. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  17522. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  17523. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  17524. * escaping.
  17525. *
  17526. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  17527. * resourceUrl, html, js and css.
  17528. * @param {*} value The value that that should be considered trusted/safe.
  17529. * @returns {*} A value that can be used to stand in for the provided `value` in places
  17530. * where Angular expects a $sce.trustAs() return value.
  17531. */
  17532. /**
  17533. * @ngdoc method
  17534. * @name $sce#trustAsHtml
  17535. *
  17536. * @description
  17537. * Shorthand method. `$sce.trustAsHtml(value)` →
  17538. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  17539. *
  17540. * @param {*} value The value to trustAs.
  17541. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  17542. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  17543. * only accept expressions that are either literal constants or are the
  17544. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17545. */
  17546. /**
  17547. * @ngdoc method
  17548. * @name $sce#trustAsUrl
  17549. *
  17550. * @description
  17551. * Shorthand method. `$sce.trustAsUrl(value)` →
  17552. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  17553. *
  17554. * @param {*} value The value to trustAs.
  17555. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  17556. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  17557. * only accept expressions that are either literal constants or are the
  17558. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17559. */
  17560. /**
  17561. * @ngdoc method
  17562. * @name $sce#trustAsResourceUrl
  17563. *
  17564. * @description
  17565. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  17566. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  17567. *
  17568. * @param {*} value The value to trustAs.
  17569. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  17570. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  17571. * only accept expressions that are either literal constants or are the return
  17572. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17573. */
  17574. /**
  17575. * @ngdoc method
  17576. * @name $sce#trustAsJs
  17577. *
  17578. * @description
  17579. * Shorthand method. `$sce.trustAsJs(value)` →
  17580. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  17581. *
  17582. * @param {*} value The value to trustAs.
  17583. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  17584. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  17585. * only accept expressions that are either literal constants or are the
  17586. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17587. */
  17588. /**
  17589. * @ngdoc method
  17590. * @name $sce#getTrusted
  17591. *
  17592. * @description
  17593. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  17594. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  17595. * originally supplied value if the queried context type is a supertype of the created type.
  17596. * If this condition isn't satisfied, throws an exception.
  17597. *
  17598. * @param {string} type The kind of context in which this value is to be used.
  17599. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  17600. * call.
  17601. * @returns {*} The value the was originally provided to
  17602. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  17603. * Otherwise, throws an exception.
  17604. */
  17605. /**
  17606. * @ngdoc method
  17607. * @name $sce#getTrustedHtml
  17608. *
  17609. * @description
  17610. * Shorthand method. `$sce.getTrustedHtml(value)` →
  17611. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  17612. *
  17613. * @param {*} value The value to pass to `$sce.getTrusted`.
  17614. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  17615. */
  17616. /**
  17617. * @ngdoc method
  17618. * @name $sce#getTrustedCss
  17619. *
  17620. * @description
  17621. * Shorthand method. `$sce.getTrustedCss(value)` →
  17622. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  17623. *
  17624. * @param {*} value The value to pass to `$sce.getTrusted`.
  17625. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  17626. */
  17627. /**
  17628. * @ngdoc method
  17629. * @name $sce#getTrustedUrl
  17630. *
  17631. * @description
  17632. * Shorthand method. `$sce.getTrustedUrl(value)` →
  17633. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  17634. *
  17635. * @param {*} value The value to pass to `$sce.getTrusted`.
  17636. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  17637. */
  17638. /**
  17639. * @ngdoc method
  17640. * @name $sce#getTrustedResourceUrl
  17641. *
  17642. * @description
  17643. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  17644. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  17645. *
  17646. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  17647. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  17648. */
  17649. /**
  17650. * @ngdoc method
  17651. * @name $sce#getTrustedJs
  17652. *
  17653. * @description
  17654. * Shorthand method. `$sce.getTrustedJs(value)` →
  17655. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  17656. *
  17657. * @param {*} value The value to pass to `$sce.getTrusted`.
  17658. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  17659. */
  17660. /**
  17661. * @ngdoc method
  17662. * @name $sce#parseAsHtml
  17663. *
  17664. * @description
  17665. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  17666. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  17667. *
  17668. * @param {string} expression String expression to compile.
  17669. * @returns {function(context, locals)} a function which represents the compiled expression:
  17670. *
  17671. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17672. * are evaluated against (typically a scope object).
  17673. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17674. * `context`.
  17675. */
  17676. /**
  17677. * @ngdoc method
  17678. * @name $sce#parseAsCss
  17679. *
  17680. * @description
  17681. * Shorthand method. `$sce.parseAsCss(value)` →
  17682. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  17683. *
  17684. * @param {string} expression String expression to compile.
  17685. * @returns {function(context, locals)} a function which represents the compiled expression:
  17686. *
  17687. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17688. * are evaluated against (typically a scope object).
  17689. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17690. * `context`.
  17691. */
  17692. /**
  17693. * @ngdoc method
  17694. * @name $sce#parseAsUrl
  17695. *
  17696. * @description
  17697. * Shorthand method. `$sce.parseAsUrl(value)` →
  17698. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  17699. *
  17700. * @param {string} expression String expression to compile.
  17701. * @returns {function(context, locals)} a function which represents the compiled expression:
  17702. *
  17703. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17704. * are evaluated against (typically a scope object).
  17705. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17706. * `context`.
  17707. */
  17708. /**
  17709. * @ngdoc method
  17710. * @name $sce#parseAsResourceUrl
  17711. *
  17712. * @description
  17713. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  17714. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  17715. *
  17716. * @param {string} expression String expression to compile.
  17717. * @returns {function(context, locals)} a function which represents the compiled expression:
  17718. *
  17719. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17720. * are evaluated against (typically a scope object).
  17721. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17722. * `context`.
  17723. */
  17724. /**
  17725. * @ngdoc method
  17726. * @name $sce#parseAsJs
  17727. *
  17728. * @description
  17729. * Shorthand method. `$sce.parseAsJs(value)` →
  17730. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  17731. *
  17732. * @param {string} expression String expression to compile.
  17733. * @returns {function(context, locals)} a function which represents the compiled expression:
  17734. *
  17735. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17736. * are evaluated against (typically a scope object).
  17737. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17738. * `context`.
  17739. */
  17740. // Shorthand delegations.
  17741. var parse = sce.parseAs,
  17742. getTrusted = sce.getTrusted,
  17743. trustAs = sce.trustAs;
  17744. forEach(SCE_CONTEXTS, function(enumValue, name) {
  17745. var lName = lowercase(name);
  17746. sce[snakeToCamel('parse_as_' + lName)] = function(expr) {
  17747. return parse(enumValue, expr);
  17748. };
  17749. sce[snakeToCamel('get_trusted_' + lName)] = function(value) {
  17750. return getTrusted(enumValue, value);
  17751. };
  17752. sce[snakeToCamel('trust_as_' + lName)] = function(value) {
  17753. return trustAs(enumValue, value);
  17754. };
  17755. });
  17756. return sce;
  17757. }];
  17758. }
  17759. /* exported $SnifferProvider */
  17760. /**
  17761. * !!! This is an undocumented "private" service !!!
  17762. *
  17763. * @name $sniffer
  17764. * @requires $window
  17765. * @requires $document
  17766. * @this
  17767. *
  17768. * @property {boolean} history Does the browser support html5 history api ?
  17769. * @property {boolean} transitions Does the browser support CSS transition events ?
  17770. * @property {boolean} animations Does the browser support CSS animation events ?
  17771. *
  17772. * @description
  17773. * This is very simple implementation of testing browser's features.
  17774. */
  17775. function $SnifferProvider() {
  17776. this.$get = ['$window', '$document', function($window, $document) {
  17777. var eventSupport = {},
  17778. // Chrome Packaged Apps are not allowed to access `history.pushState`.
  17779. // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
  17780. // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
  17781. // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
  17782. // (see https://developer.chrome.com/apps/manifest/sandbox).
  17783. // (NW.js apps have access to Chrome APIs, but do support `history`.)
  17784. isNw = $window.nw && $window.nw.process,
  17785. isChromePackagedApp =
  17786. !isNw &&
  17787. $window.chrome &&
  17788. ($window.chrome.app && $window.chrome.app.runtime ||
  17789. !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
  17790. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  17791. android =
  17792. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  17793. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  17794. document = $document[0] || {},
  17795. bodyStyle = document.body && document.body.style,
  17796. transitions = false,
  17797. animations = false;
  17798. if (bodyStyle) {
  17799. // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x
  17800. // Mentioned browsers need a -webkit- prefix for transitions & animations.
  17801. transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);
  17802. animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);
  17803. }
  17804. return {
  17805. // Android has history.pushState, but it does not update location correctly
  17806. // so let's not use the history API at all.
  17807. // http://code.google.com/p/android/issues/detail?id=17471
  17808. // https://github.com/angular/angular.js/issues/904
  17809. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  17810. // so let's not use the history API also
  17811. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  17812. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  17813. hasEvent: function(event) {
  17814. // Support: IE 9-11 only
  17815. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  17816. // it. In particular the event is not fired when backspace or delete key are pressed or
  17817. // when cut operation is performed.
  17818. // IE10+ implements 'input' event but it erroneously fires under various situations,
  17819. // e.g. when placeholder changes, or a form is focused.
  17820. if (event === 'input' && msie) return false;
  17821. if (isUndefined(eventSupport[event])) {
  17822. var divElm = document.createElement('div');
  17823. eventSupport[event] = 'on' + event in divElm;
  17824. }
  17825. return eventSupport[event];
  17826. },
  17827. csp: csp(),
  17828. transitions: transitions,
  17829. animations: animations,
  17830. android: android
  17831. };
  17832. }];
  17833. }
  17834. var $templateRequestMinErr = minErr('$compile');
  17835. /**
  17836. * @ngdoc provider
  17837. * @name $templateRequestProvider
  17838. * @this
  17839. *
  17840. * @description
  17841. * Used to configure the options passed to the {@link $http} service when making a template request.
  17842. *
  17843. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  17844. * requesting a template.
  17845. */
  17846. function $TemplateRequestProvider() {
  17847. var httpOptions;
  17848. /**
  17849. * @ngdoc method
  17850. * @name $templateRequestProvider#httpOptions
  17851. * @description
  17852. * The options to be passed to the {@link $http} service when making the request.
  17853. * You can use this to override options such as the "Accept" header for template requests.
  17854. *
  17855. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  17856. * options if not overridden here.
  17857. *
  17858. * @param {string=} value new value for the {@link $http} options.
  17859. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  17860. */
  17861. this.httpOptions = function(val) {
  17862. if (val) {
  17863. httpOptions = val;
  17864. return this;
  17865. }
  17866. return httpOptions;
  17867. };
  17868. /**
  17869. * @ngdoc service
  17870. * @name $templateRequest
  17871. *
  17872. * @description
  17873. * The `$templateRequest` service runs security checks then downloads the provided template using
  17874. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  17875. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  17876. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  17877. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  17878. * when `tpl` is of type string and `$templateCache` has the matching entry.
  17879. *
  17880. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  17881. * can configure this via {@link $templateRequestProvider#httpOptions}.
  17882. *
  17883. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  17884. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  17885. *
  17886. * @return {Promise} a promise for the HTTP response data of the given URL.
  17887. *
  17888. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  17889. */
  17890. this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',
  17891. function($exceptionHandler, $templateCache, $http, $q, $sce) {
  17892. function handleRequestFn(tpl, ignoreRequestError) {
  17893. handleRequestFn.totalPendingRequests++;
  17894. // We consider the template cache holds only trusted templates, so
  17895. // there's no need to go through whitelisting again for keys that already
  17896. // are included in there. This also makes Angular accept any script
  17897. // directive, no matter its name. However, we still need to unwrap trusted
  17898. // types.
  17899. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  17900. tpl = $sce.getTrustedResourceUrl(tpl);
  17901. }
  17902. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  17903. if (isArray(transformResponse)) {
  17904. transformResponse = transformResponse.filter(function(transformer) {
  17905. return transformer !== defaultHttpResponseTransform;
  17906. });
  17907. } else if (transformResponse === defaultHttpResponseTransform) {
  17908. transformResponse = null;
  17909. }
  17910. return $http.get(tpl, extend({
  17911. cache: $templateCache,
  17912. transformResponse: transformResponse
  17913. }, httpOptions))
  17914. .finally(function() {
  17915. handleRequestFn.totalPendingRequests--;
  17916. })
  17917. .then(function(response) {
  17918. $templateCache.put(tpl, response.data);
  17919. return response.data;
  17920. }, handleError);
  17921. function handleError(resp) {
  17922. if (!ignoreRequestError) {
  17923. resp = $templateRequestMinErr('tpload',
  17924. 'Failed to load template: {0} (HTTP status: {1} {2})',
  17925. tpl, resp.status, resp.statusText);
  17926. $exceptionHandler(resp);
  17927. }
  17928. return $q.reject(resp);
  17929. }
  17930. }
  17931. handleRequestFn.totalPendingRequests = 0;
  17932. return handleRequestFn;
  17933. }
  17934. ];
  17935. }
  17936. /** @this */
  17937. function $$TestabilityProvider() {
  17938. this.$get = ['$rootScope', '$browser', '$location',
  17939. function($rootScope, $browser, $location) {
  17940. /**
  17941. * @name $testability
  17942. *
  17943. * @description
  17944. * The private $$testability service provides a collection of methods for use when debugging
  17945. * or by automated test and debugging tools.
  17946. */
  17947. var testability = {};
  17948. /**
  17949. * @name $$testability#findBindings
  17950. *
  17951. * @description
  17952. * Returns an array of elements that are bound (via ng-bind or {{}})
  17953. * to expressions matching the input.
  17954. *
  17955. * @param {Element} element The element root to search from.
  17956. * @param {string} expression The binding expression to match.
  17957. * @param {boolean} opt_exactMatch If true, only returns exact matches
  17958. * for the expression. Filters and whitespace are ignored.
  17959. */
  17960. testability.findBindings = function(element, expression, opt_exactMatch) {
  17961. var bindings = element.getElementsByClassName('ng-binding');
  17962. var matches = [];
  17963. forEach(bindings, function(binding) {
  17964. var dataBinding = angular.element(binding).data('$binding');
  17965. if (dataBinding) {
  17966. forEach(dataBinding, function(bindingName) {
  17967. if (opt_exactMatch) {
  17968. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  17969. if (matcher.test(bindingName)) {
  17970. matches.push(binding);
  17971. }
  17972. } else {
  17973. if (bindingName.indexOf(expression) !== -1) {
  17974. matches.push(binding);
  17975. }
  17976. }
  17977. });
  17978. }
  17979. });
  17980. return matches;
  17981. };
  17982. /**
  17983. * @name $$testability#findModels
  17984. *
  17985. * @description
  17986. * Returns an array of elements that are two-way found via ng-model to
  17987. * expressions matching the input.
  17988. *
  17989. * @param {Element} element The element root to search from.
  17990. * @param {string} expression The model expression to match.
  17991. * @param {boolean} opt_exactMatch If true, only returns exact matches
  17992. * for the expression.
  17993. */
  17994. testability.findModels = function(element, expression, opt_exactMatch) {
  17995. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  17996. for (var p = 0; p < prefixes.length; ++p) {
  17997. var attributeEquals = opt_exactMatch ? '=' : '*=';
  17998. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  17999. var elements = element.querySelectorAll(selector);
  18000. if (elements.length) {
  18001. return elements;
  18002. }
  18003. }
  18004. };
  18005. /**
  18006. * @name $$testability#getLocation
  18007. *
  18008. * @description
  18009. * Shortcut for getting the location in a browser agnostic way. Returns
  18010. * the path, search, and hash. (e.g. /path?a=b#hash)
  18011. */
  18012. testability.getLocation = function() {
  18013. return $location.url();
  18014. };
  18015. /**
  18016. * @name $$testability#setLocation
  18017. *
  18018. * @description
  18019. * Shortcut for navigating to a location without doing a full page reload.
  18020. *
  18021. * @param {string} url The location url (path, search and hash,
  18022. * e.g. /path?a=b#hash) to go to.
  18023. */
  18024. testability.setLocation = function(url) {
  18025. if (url !== $location.url()) {
  18026. $location.url(url);
  18027. $rootScope.$digest();
  18028. }
  18029. };
  18030. /**
  18031. * @name $$testability#whenStable
  18032. *
  18033. * @description
  18034. * Calls the callback when $timeout and $http requests are completed.
  18035. *
  18036. * @param {function} callback
  18037. */
  18038. testability.whenStable = function(callback) {
  18039. $browser.notifyWhenNoOutstandingRequests(callback);
  18040. };
  18041. return testability;
  18042. }];
  18043. }
  18044. /** @this */
  18045. function $TimeoutProvider() {
  18046. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  18047. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  18048. var deferreds = {};
  18049. /**
  18050. * @ngdoc service
  18051. * @name $timeout
  18052. *
  18053. * @description
  18054. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  18055. * block and delegates any exceptions to
  18056. * {@link ng.$exceptionHandler $exceptionHandler} service.
  18057. *
  18058. * The return value of calling `$timeout` is a promise, which will be resolved when
  18059. * the delay has passed and the timeout function, if provided, is executed.
  18060. *
  18061. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  18062. *
  18063. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  18064. * synchronously flush the queue of deferred functions.
  18065. *
  18066. * If you only want a promise that will be resolved after some specified delay
  18067. * then you can call `$timeout` without the `fn` function.
  18068. *
  18069. * @param {function()=} fn A function, whose execution should be delayed.
  18070. * @param {number=} [delay=0] Delay in milliseconds.
  18071. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  18072. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  18073. * @param {...*=} Pass additional parameters to the executed function.
  18074. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  18075. * will be resolved with the return value of the `fn` function.
  18076. *
  18077. */
  18078. function timeout(fn, delay, invokeApply) {
  18079. if (!isFunction(fn)) {
  18080. invokeApply = delay;
  18081. delay = fn;
  18082. fn = noop;
  18083. }
  18084. var args = sliceArgs(arguments, 3),
  18085. skipApply = (isDefined(invokeApply) && !invokeApply),
  18086. deferred = (skipApply ? $$q : $q).defer(),
  18087. promise = deferred.promise,
  18088. timeoutId;
  18089. timeoutId = $browser.defer(function() {
  18090. try {
  18091. deferred.resolve(fn.apply(null, args));
  18092. } catch (e) {
  18093. deferred.reject(e);
  18094. $exceptionHandler(e);
  18095. } finally {
  18096. delete deferreds[promise.$$timeoutId];
  18097. }
  18098. if (!skipApply) $rootScope.$apply();
  18099. }, delay);
  18100. promise.$$timeoutId = timeoutId;
  18101. deferreds[timeoutId] = deferred;
  18102. return promise;
  18103. }
  18104. /**
  18105. * @ngdoc method
  18106. * @name $timeout#cancel
  18107. *
  18108. * @description
  18109. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  18110. * resolved with a rejection.
  18111. *
  18112. * @param {Promise=} promise Promise returned by the `$timeout` function.
  18113. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  18114. * canceled.
  18115. */
  18116. timeout.cancel = function(promise) {
  18117. if (promise && promise.$$timeoutId in deferreds) {
  18118. // Timeout cancels should not report an unhandled promise.
  18119. deferreds[promise.$$timeoutId].promise.catch(noop);
  18120. deferreds[promise.$$timeoutId].reject('canceled');
  18121. delete deferreds[promise.$$timeoutId];
  18122. return $browser.defer.cancel(promise.$$timeoutId);
  18123. }
  18124. return false;
  18125. };
  18126. return timeout;
  18127. }];
  18128. }
  18129. // NOTE: The usage of window and document instead of $window and $document here is
  18130. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  18131. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  18132. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  18133. // doesn't know about mocked locations and resolves URLs to the real document - which is
  18134. // exactly the behavior needed here. There is little value is mocking these out for this
  18135. // service.
  18136. var urlParsingNode = window.document.createElement('a');
  18137. var originUrl = urlResolve(window.location.href);
  18138. /**
  18139. *
  18140. * Implementation Notes for non-IE browsers
  18141. * ----------------------------------------
  18142. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  18143. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  18144. * URL will be resolved into an absolute URL in the context of the application document.
  18145. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  18146. * properties are all populated to reflect the normalized URL. This approach has wide
  18147. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  18148. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18149. *
  18150. * Implementation Notes for IE
  18151. * ---------------------------
  18152. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  18153. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  18154. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  18155. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  18156. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  18157. * properties such as protocol, hostname, port, etc.
  18158. *
  18159. * References:
  18160. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  18161. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18162. * http://url.spec.whatwg.org/#urlutils
  18163. * https://github.com/angular/angular.js/pull/2902
  18164. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  18165. *
  18166. * @kind function
  18167. * @param {string} url The URL to be parsed.
  18168. * @description Normalizes and parses a URL.
  18169. * @returns {object} Returns the normalized URL as a dictionary.
  18170. *
  18171. * | member name | Description |
  18172. * |---------------|----------------|
  18173. * | href | A normalized version of the provided URL if it was not an absolute URL |
  18174. * | protocol | The protocol including the trailing colon |
  18175. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  18176. * | search | The search params, minus the question mark |
  18177. * | hash | The hash string, minus the hash symbol
  18178. * | hostname | The hostname
  18179. * | port | The port, without ":"
  18180. * | pathname | The pathname, beginning with "/"
  18181. *
  18182. */
  18183. function urlResolve(url) {
  18184. var href = url;
  18185. // Support: IE 9-11 only
  18186. if (msie) {
  18187. // Normalize before parse. Refer Implementation Notes on why this is
  18188. // done in two steps on IE.
  18189. urlParsingNode.setAttribute('href', href);
  18190. href = urlParsingNode.href;
  18191. }
  18192. urlParsingNode.setAttribute('href', href);
  18193. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  18194. return {
  18195. href: urlParsingNode.href,
  18196. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  18197. host: urlParsingNode.host,
  18198. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  18199. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  18200. hostname: urlParsingNode.hostname,
  18201. port: urlParsingNode.port,
  18202. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  18203. ? urlParsingNode.pathname
  18204. : '/' + urlParsingNode.pathname
  18205. };
  18206. }
  18207. /**
  18208. * Parse a request URL and determine whether this is a same-origin request as the application document.
  18209. *
  18210. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  18211. * or a parsed URL object.
  18212. * @returns {boolean} Whether the request is for the same origin as the application document.
  18213. */
  18214. function urlIsSameOrigin(requestUrl) {
  18215. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  18216. return (parsed.protocol === originUrl.protocol &&
  18217. parsed.host === originUrl.host);
  18218. }
  18219. /**
  18220. * @ngdoc service
  18221. * @name $window
  18222. * @this
  18223. *
  18224. * @description
  18225. * A reference to the browser's `window` object. While `window`
  18226. * is globally available in JavaScript, it causes testability problems, because
  18227. * it is a global variable. In angular we always refer to it through the
  18228. * `$window` service, so it may be overridden, removed or mocked for testing.
  18229. *
  18230. * Expressions, like the one defined for the `ngClick` directive in the example
  18231. * below, are evaluated with respect to the current scope. Therefore, there is
  18232. * no risk of inadvertently coding in a dependency on a global value in such an
  18233. * expression.
  18234. *
  18235. * @example
  18236. <example module="windowExample" name="window-service">
  18237. <file name="index.html">
  18238. <script>
  18239. angular.module('windowExample', [])
  18240. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  18241. $scope.greeting = 'Hello, World!';
  18242. $scope.doGreeting = function(greeting) {
  18243. $window.alert(greeting);
  18244. };
  18245. }]);
  18246. </script>
  18247. <div ng-controller="ExampleController">
  18248. <input type="text" ng-model="greeting" aria-label="greeting" />
  18249. <button ng-click="doGreeting(greeting)">ALERT</button>
  18250. </div>
  18251. </file>
  18252. <file name="protractor.js" type="protractor">
  18253. it('should display the greeting in the input box', function() {
  18254. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  18255. // If we click the button it will block the test runner
  18256. // element(':button').click();
  18257. });
  18258. </file>
  18259. </example>
  18260. */
  18261. function $WindowProvider() {
  18262. this.$get = valueFn(window);
  18263. }
  18264. /**
  18265. * @name $$cookieReader
  18266. * @requires $document
  18267. *
  18268. * @description
  18269. * This is a private service for reading cookies used by $http and ngCookies
  18270. *
  18271. * @return {Object} a key/value map of the current cookies
  18272. */
  18273. function $$CookieReader($document) {
  18274. var rawDocument = $document[0] || {};
  18275. var lastCookies = {};
  18276. var lastCookieString = '';
  18277. function safeGetCookie(rawDocument) {
  18278. try {
  18279. return rawDocument.cookie || '';
  18280. } catch (e) {
  18281. return '';
  18282. }
  18283. }
  18284. function safeDecodeURIComponent(str) {
  18285. try {
  18286. return decodeURIComponent(str);
  18287. } catch (e) {
  18288. return str;
  18289. }
  18290. }
  18291. return function() {
  18292. var cookieArray, cookie, i, index, name;
  18293. var currentCookieString = safeGetCookie(rawDocument);
  18294. if (currentCookieString !== lastCookieString) {
  18295. lastCookieString = currentCookieString;
  18296. cookieArray = lastCookieString.split('; ');
  18297. lastCookies = {};
  18298. for (i = 0; i < cookieArray.length; i++) {
  18299. cookie = cookieArray[i];
  18300. index = cookie.indexOf('=');
  18301. if (index > 0) { //ignore nameless cookies
  18302. name = safeDecodeURIComponent(cookie.substring(0, index));
  18303. // the first value that is seen for a cookie is the most
  18304. // specific one. values for the same cookie name that
  18305. // follow are for less specific paths.
  18306. if (isUndefined(lastCookies[name])) {
  18307. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  18308. }
  18309. }
  18310. }
  18311. }
  18312. return lastCookies;
  18313. };
  18314. }
  18315. $$CookieReader.$inject = ['$document'];
  18316. /** @this */
  18317. function $$CookieReaderProvider() {
  18318. this.$get = $$CookieReader;
  18319. }
  18320. /* global currencyFilter: true,
  18321. dateFilter: true,
  18322. filterFilter: true,
  18323. jsonFilter: true,
  18324. limitToFilter: true,
  18325. lowercaseFilter: true,
  18326. numberFilter: true,
  18327. orderByFilter: true,
  18328. uppercaseFilter: true,
  18329. */
  18330. /**
  18331. * @ngdoc provider
  18332. * @name $filterProvider
  18333. * @description
  18334. *
  18335. * Filters are just functions which transform input to an output. However filters need to be
  18336. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  18337. * annotated with dependencies and is responsible for creating a filter function.
  18338. *
  18339. * <div class="alert alert-warning">
  18340. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18341. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18342. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18343. * (`myapp_subsection_filterx`).
  18344. * </div>
  18345. *
  18346. * ```js
  18347. * // Filter registration
  18348. * function MyModule($provide, $filterProvider) {
  18349. * // create a service to demonstrate injection (not always needed)
  18350. * $provide.value('greet', function(name){
  18351. * return 'Hello ' + name + '!';
  18352. * });
  18353. *
  18354. * // register a filter factory which uses the
  18355. * // greet service to demonstrate DI.
  18356. * $filterProvider.register('greet', function(greet){
  18357. * // return the filter function which uses the greet service
  18358. * // to generate salutation
  18359. * return function(text) {
  18360. * // filters need to be forgiving so check input validity
  18361. * return text && greet(text) || text;
  18362. * };
  18363. * });
  18364. * }
  18365. * ```
  18366. *
  18367. * The filter function is registered with the `$injector` under the filter name suffix with
  18368. * `Filter`.
  18369. *
  18370. * ```js
  18371. * it('should be the same instance', inject(
  18372. * function($filterProvider) {
  18373. * $filterProvider.register('reverse', function(){
  18374. * return ...;
  18375. * });
  18376. * },
  18377. * function($filter, reverseFilter) {
  18378. * expect($filter('reverse')).toBe(reverseFilter);
  18379. * });
  18380. * ```
  18381. *
  18382. *
  18383. * For more information about how angular filters work, and how to create your own filters, see
  18384. * {@link guide/filter Filters} in the Angular Developer Guide.
  18385. */
  18386. /**
  18387. * @ngdoc service
  18388. * @name $filter
  18389. * @kind function
  18390. * @description
  18391. * Filters are used for formatting data displayed to the user.
  18392. *
  18393. * They can be used in view templates, controllers or services.Angular comes
  18394. * with a collection of [built-in filters](api/ng/filter), but it is easy to
  18395. * define your own as well.
  18396. *
  18397. * The general syntax in templates is as follows:
  18398. *
  18399. * ```html
  18400. * {{ expression [| filter_name[:parameter_value] ... ] }}
  18401. * ```
  18402. *
  18403. * @param {String} name Name of the filter function to retrieve
  18404. * @return {Function} the filter function
  18405. * @example
  18406. <example name="$filter" module="filterExample">
  18407. <file name="index.html">
  18408. <div ng-controller="MainCtrl">
  18409. <h3>{{ originalText }}</h3>
  18410. <h3>{{ filteredText }}</h3>
  18411. </div>
  18412. </file>
  18413. <file name="script.js">
  18414. angular.module('filterExample', [])
  18415. .controller('MainCtrl', function($scope, $filter) {
  18416. $scope.originalText = 'hello';
  18417. $scope.filteredText = $filter('uppercase')($scope.originalText);
  18418. });
  18419. </file>
  18420. </example>
  18421. */
  18422. $FilterProvider.$inject = ['$provide'];
  18423. /** @this */
  18424. function $FilterProvider($provide) {
  18425. var suffix = 'Filter';
  18426. /**
  18427. * @ngdoc method
  18428. * @name $filterProvider#register
  18429. * @param {string|Object} name Name of the filter function, or an object map of filters where
  18430. * the keys are the filter names and the values are the filter factories.
  18431. *
  18432. * <div class="alert alert-warning">
  18433. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18434. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18435. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18436. * (`myapp_subsection_filterx`).
  18437. * </div>
  18438. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  18439. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  18440. * of the registered filter instances.
  18441. */
  18442. function register(name, factory) {
  18443. if (isObject(name)) {
  18444. var filters = {};
  18445. forEach(name, function(filter, key) {
  18446. filters[key] = register(key, filter);
  18447. });
  18448. return filters;
  18449. } else {
  18450. return $provide.factory(name + suffix, factory);
  18451. }
  18452. }
  18453. this.register = register;
  18454. this.$get = ['$injector', function($injector) {
  18455. return function(name) {
  18456. return $injector.get(name + suffix);
  18457. };
  18458. }];
  18459. ////////////////////////////////////////
  18460. /* global
  18461. currencyFilter: false,
  18462. dateFilter: false,
  18463. filterFilter: false,
  18464. jsonFilter: false,
  18465. limitToFilter: false,
  18466. lowercaseFilter: false,
  18467. numberFilter: false,
  18468. orderByFilter: false,
  18469. uppercaseFilter: false
  18470. */
  18471. register('currency', currencyFilter);
  18472. register('date', dateFilter);
  18473. register('filter', filterFilter);
  18474. register('json', jsonFilter);
  18475. register('limitTo', limitToFilter);
  18476. register('lowercase', lowercaseFilter);
  18477. register('number', numberFilter);
  18478. register('orderBy', orderByFilter);
  18479. register('uppercase', uppercaseFilter);
  18480. }
  18481. /**
  18482. * @ngdoc filter
  18483. * @name filter
  18484. * @kind function
  18485. *
  18486. * @description
  18487. * Selects a subset of items from `array` and returns it as a new array.
  18488. *
  18489. * @param {Array} array The source array.
  18490. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  18491. * `array`.
  18492. *
  18493. * Can be one of:
  18494. *
  18495. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  18496. * objects with string properties in `array` that match this string will be returned. This also
  18497. * applies to nested object properties.
  18498. * The predicate can be negated by prefixing the string with `!`.
  18499. *
  18500. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  18501. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  18502. * which have property `name` containing "M" and property `phone` containing "1". A special
  18503. * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
  18504. * against any property of the object or its nested object properties. That's equivalent to the
  18505. * simple substring match with a `string` as described above. The special property name can be
  18506. * overwritten, using the `anyPropertyKey` parameter.
  18507. * The predicate can be negated by prefixing the string with `!`.
  18508. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  18509. * not containing "M".
  18510. *
  18511. * Note that a named property will match properties on the same level only, while the special
  18512. * `$` property will match properties on the same level or deeper. E.g. an array item like
  18513. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  18514. * **will** be matched by `{$: 'John'}`.
  18515. *
  18516. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  18517. * The function is called for each element of the array, with the element, its index, and
  18518. * the entire array itself as arguments.
  18519. *
  18520. * The final result is an array of those elements that the predicate returned true for.
  18521. *
  18522. * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in
  18523. * determining if the expected value (from the filter expression) and actual value (from
  18524. * the object in the array) should be considered a match.
  18525. *
  18526. * Can be one of:
  18527. *
  18528. * - `function(actual, expected)`:
  18529. * The function will be given the object value and the predicate value to compare and
  18530. * should return true if both values should be considered equal.
  18531. *
  18532. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  18533. * This is essentially strict comparison of expected and actual.
  18534. *
  18535. * - `false`: A short hand for a function which will look for a substring match in a case
  18536. * insensitive way. Primitive values are converted to strings. Objects are not compared against
  18537. * primitives, unless they have a custom `toString` method (e.g. `Date` objects).
  18538. *
  18539. *
  18540. * Defaults to `false`.
  18541. *
  18542. * @param {string} [anyPropertyKey] The special property name that matches against any property.
  18543. * By default `$`.
  18544. *
  18545. * @example
  18546. <example name="filter-filter">
  18547. <file name="index.html">
  18548. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  18549. {name:'Mary', phone:'800-BIG-MARY'},
  18550. {name:'Mike', phone:'555-4321'},
  18551. {name:'Adam', phone:'555-5678'},
  18552. {name:'Julie', phone:'555-8765'},
  18553. {name:'Juliette', phone:'555-5678'}]"></div>
  18554. <label>Search: <input ng-model="searchText"></label>
  18555. <table id="searchTextResults">
  18556. <tr><th>Name</th><th>Phone</th></tr>
  18557. <tr ng-repeat="friend in friends | filter:searchText">
  18558. <td>{{friend.name}}</td>
  18559. <td>{{friend.phone}}</td>
  18560. </tr>
  18561. </table>
  18562. <hr>
  18563. <label>Any: <input ng-model="search.$"></label> <br>
  18564. <label>Name only <input ng-model="search.name"></label><br>
  18565. <label>Phone only <input ng-model="search.phone"></label><br>
  18566. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  18567. <table id="searchObjResults">
  18568. <tr><th>Name</th><th>Phone</th></tr>
  18569. <tr ng-repeat="friendObj in friends | filter:search:strict">
  18570. <td>{{friendObj.name}}</td>
  18571. <td>{{friendObj.phone}}</td>
  18572. </tr>
  18573. </table>
  18574. </file>
  18575. <file name="protractor.js" type="protractor">
  18576. var expectFriendNames = function(expectedNames, key) {
  18577. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  18578. arr.forEach(function(wd, i) {
  18579. expect(wd.getText()).toMatch(expectedNames[i]);
  18580. });
  18581. });
  18582. };
  18583. it('should search across all fields when filtering with a string', function() {
  18584. var searchText = element(by.model('searchText'));
  18585. searchText.clear();
  18586. searchText.sendKeys('m');
  18587. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  18588. searchText.clear();
  18589. searchText.sendKeys('76');
  18590. expectFriendNames(['John', 'Julie'], 'friend');
  18591. });
  18592. it('should search in specific fields when filtering with a predicate object', function() {
  18593. var searchAny = element(by.model('search.$'));
  18594. searchAny.clear();
  18595. searchAny.sendKeys('i');
  18596. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  18597. });
  18598. it('should use a equal comparison when comparator is true', function() {
  18599. var searchName = element(by.model('search.name'));
  18600. var strict = element(by.model('strict'));
  18601. searchName.clear();
  18602. searchName.sendKeys('Julie');
  18603. strict.click();
  18604. expectFriendNames(['Julie'], 'friendObj');
  18605. });
  18606. </file>
  18607. </example>
  18608. */
  18609. function filterFilter() {
  18610. return function(array, expression, comparator, anyPropertyKey) {
  18611. if (!isArrayLike(array)) {
  18612. if (array == null) {
  18613. return array;
  18614. } else {
  18615. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  18616. }
  18617. }
  18618. anyPropertyKey = anyPropertyKey || '$';
  18619. var expressionType = getTypeForFilter(expression);
  18620. var predicateFn;
  18621. var matchAgainstAnyProp;
  18622. switch (expressionType) {
  18623. case 'function':
  18624. predicateFn = expression;
  18625. break;
  18626. case 'boolean':
  18627. case 'null':
  18628. case 'number':
  18629. case 'string':
  18630. matchAgainstAnyProp = true;
  18631. // falls through
  18632. case 'object':
  18633. predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18634. break;
  18635. default:
  18636. return array;
  18637. }
  18638. return Array.prototype.filter.call(array, predicateFn);
  18639. };
  18640. }
  18641. // Helper functions for `filterFilter`
  18642. function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
  18643. var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
  18644. var predicateFn;
  18645. if (comparator === true) {
  18646. comparator = equals;
  18647. } else if (!isFunction(comparator)) {
  18648. comparator = function(actual, expected) {
  18649. if (isUndefined(actual)) {
  18650. // No substring matching against `undefined`
  18651. return false;
  18652. }
  18653. if ((actual === null) || (expected === null)) {
  18654. // No substring matching against `null`; only match against `null`
  18655. return actual === expected;
  18656. }
  18657. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  18658. // Should not compare primitives against objects, unless they have custom `toString` method
  18659. return false;
  18660. }
  18661. actual = lowercase('' + actual);
  18662. expected = lowercase('' + expected);
  18663. return actual.indexOf(expected) !== -1;
  18664. };
  18665. }
  18666. predicateFn = function(item) {
  18667. if (shouldMatchPrimitives && !isObject(item)) {
  18668. return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
  18669. }
  18670. return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18671. };
  18672. return predicateFn;
  18673. }
  18674. function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
  18675. var actualType = getTypeForFilter(actual);
  18676. var expectedType = getTypeForFilter(expected);
  18677. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  18678. return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
  18679. } else if (isArray(actual)) {
  18680. // In case `actual` is an array, consider it a match
  18681. // if ANY of it's items matches `expected`
  18682. return actual.some(function(item) {
  18683. return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
  18684. });
  18685. }
  18686. switch (actualType) {
  18687. case 'object':
  18688. var key;
  18689. if (matchAgainstAnyProp) {
  18690. for (key in actual) {
  18691. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
  18692. return true;
  18693. }
  18694. }
  18695. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
  18696. } else if (expectedType === 'object') {
  18697. for (key in expected) {
  18698. var expectedVal = expected[key];
  18699. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  18700. continue;
  18701. }
  18702. var matchAnyProperty = key === anyPropertyKey;
  18703. var actualVal = matchAnyProperty ? actual : actual[key];
  18704. if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
  18705. return false;
  18706. }
  18707. }
  18708. return true;
  18709. } else {
  18710. return comparator(actual, expected);
  18711. }
  18712. case 'function':
  18713. return false;
  18714. default:
  18715. return comparator(actual, expected);
  18716. }
  18717. }
  18718. // Used for easily differentiating between `null` and actual `object`
  18719. function getTypeForFilter(val) {
  18720. return (val === null) ? 'null' : typeof val;
  18721. }
  18722. var MAX_DIGITS = 22;
  18723. var DECIMAL_SEP = '.';
  18724. var ZERO_CHAR = '0';
  18725. /**
  18726. * @ngdoc filter
  18727. * @name currency
  18728. * @kind function
  18729. *
  18730. * @description
  18731. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  18732. * symbol for current locale is used.
  18733. *
  18734. * @param {number} amount Input to filter.
  18735. * @param {string=} symbol Currency symbol or identifier to be displayed.
  18736. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  18737. * @returns {string} Formatted number.
  18738. *
  18739. *
  18740. * @example
  18741. <example module="currencyExample" name="currency-filter">
  18742. <file name="index.html">
  18743. <script>
  18744. angular.module('currencyExample', [])
  18745. .controller('ExampleController', ['$scope', function($scope) {
  18746. $scope.amount = 1234.56;
  18747. }]);
  18748. </script>
  18749. <div ng-controller="ExampleController">
  18750. <input type="number" ng-model="amount" aria-label="amount"> <br>
  18751. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  18752. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
  18753. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  18754. </div>
  18755. </file>
  18756. <file name="protractor.js" type="protractor">
  18757. it('should init with 1234.56', function() {
  18758. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  18759. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  18760. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  18761. });
  18762. it('should update', function() {
  18763. if (browser.params.browser === 'safari') {
  18764. // Safari does not understand the minus key. See
  18765. // https://github.com/angular/protractor/issues/481
  18766. return;
  18767. }
  18768. element(by.model('amount')).clear();
  18769. element(by.model('amount')).sendKeys('-1234');
  18770. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  18771. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  18772. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  18773. });
  18774. </file>
  18775. </example>
  18776. */
  18777. currencyFilter.$inject = ['$locale'];
  18778. function currencyFilter($locale) {
  18779. var formats = $locale.NUMBER_FORMATS;
  18780. return function(amount, currencySymbol, fractionSize) {
  18781. if (isUndefined(currencySymbol)) {
  18782. currencySymbol = formats.CURRENCY_SYM;
  18783. }
  18784. if (isUndefined(fractionSize)) {
  18785. fractionSize = formats.PATTERNS[1].maxFrac;
  18786. }
  18787. // if null or undefined pass it through
  18788. return (amount == null)
  18789. ? amount
  18790. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  18791. replace(/\u00A4/g, currencySymbol);
  18792. };
  18793. }
  18794. /**
  18795. * @ngdoc filter
  18796. * @name number
  18797. * @kind function
  18798. *
  18799. * @description
  18800. * Formats a number as text.
  18801. *
  18802. * If the input is null or undefined, it will just be returned.
  18803. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  18804. * If the input is not a number an empty string is returned.
  18805. *
  18806. *
  18807. * @param {number|string} number Number to format.
  18808. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  18809. * If this is not provided then the fraction size is computed from the current locale's number
  18810. * formatting pattern. In the case of the default locale, it will be 3.
  18811. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  18812. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  18813. * include "," group separators after each third digit).
  18814. *
  18815. * @example
  18816. <example module="numberFilterExample" name="number-filter">
  18817. <file name="index.html">
  18818. <script>
  18819. angular.module('numberFilterExample', [])
  18820. .controller('ExampleController', ['$scope', function($scope) {
  18821. $scope.val = 1234.56789;
  18822. }]);
  18823. </script>
  18824. <div ng-controller="ExampleController">
  18825. <label>Enter number: <input ng-model='val'></label><br>
  18826. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  18827. No fractions: <span>{{val | number:0}}</span><br>
  18828. Negative number: <span>{{-val | number:4}}</span>
  18829. </div>
  18830. </file>
  18831. <file name="protractor.js" type="protractor">
  18832. it('should format numbers', function() {
  18833. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  18834. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  18835. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  18836. });
  18837. it('should update', function() {
  18838. element(by.model('val')).clear();
  18839. element(by.model('val')).sendKeys('3374.333');
  18840. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  18841. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  18842. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  18843. });
  18844. </file>
  18845. </example>
  18846. */
  18847. numberFilter.$inject = ['$locale'];
  18848. function numberFilter($locale) {
  18849. var formats = $locale.NUMBER_FORMATS;
  18850. return function(number, fractionSize) {
  18851. // if null or undefined pass it through
  18852. return (number == null)
  18853. ? number
  18854. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  18855. fractionSize);
  18856. };
  18857. }
  18858. /**
  18859. * Parse a number (as a string) into three components that can be used
  18860. * for formatting the number.
  18861. *
  18862. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  18863. *
  18864. * @param {string} numStr The number to parse
  18865. * @return {object} An object describing this number, containing the following keys:
  18866. * - d : an array of digits containing leading zeros as necessary
  18867. * - i : the number of the digits in `d` that are to the left of the decimal point
  18868. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  18869. *
  18870. */
  18871. function parse(numStr) {
  18872. var exponent = 0, digits, numberOfIntegerDigits;
  18873. var i, j, zeros;
  18874. // Decimal point?
  18875. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  18876. numStr = numStr.replace(DECIMAL_SEP, '');
  18877. }
  18878. // Exponential form?
  18879. if ((i = numStr.search(/e/i)) > 0) {
  18880. // Work out the exponent.
  18881. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  18882. numberOfIntegerDigits += +numStr.slice(i + 1);
  18883. numStr = numStr.substring(0, i);
  18884. } else if (numberOfIntegerDigits < 0) {
  18885. // There was no decimal point or exponent so it is an integer.
  18886. numberOfIntegerDigits = numStr.length;
  18887. }
  18888. // Count the number of leading zeros.
  18889. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
  18890. if (i === (zeros = numStr.length)) {
  18891. // The digits are all zero.
  18892. digits = [0];
  18893. numberOfIntegerDigits = 1;
  18894. } else {
  18895. // Count the number of trailing zeros
  18896. zeros--;
  18897. while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
  18898. // Trailing zeros are insignificant so ignore them
  18899. numberOfIntegerDigits -= i;
  18900. digits = [];
  18901. // Convert string to array of digits without leading/trailing zeros.
  18902. for (j = 0; i <= zeros; i++, j++) {
  18903. digits[j] = +numStr.charAt(i);
  18904. }
  18905. }
  18906. // If the number overflows the maximum allowed digits then use an exponent.
  18907. if (numberOfIntegerDigits > MAX_DIGITS) {
  18908. digits = digits.splice(0, MAX_DIGITS - 1);
  18909. exponent = numberOfIntegerDigits - 1;
  18910. numberOfIntegerDigits = 1;
  18911. }
  18912. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  18913. }
  18914. /**
  18915. * Round the parsed number to the specified number of decimal places
  18916. * This function changed the parsedNumber in-place
  18917. */
  18918. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  18919. var digits = parsedNumber.d;
  18920. var fractionLen = digits.length - parsedNumber.i;
  18921. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  18922. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  18923. // The index of the digit to where rounding is to occur
  18924. var roundAt = fractionSize + parsedNumber.i;
  18925. var digit = digits[roundAt];
  18926. if (roundAt > 0) {
  18927. // Drop fractional digits beyond `roundAt`
  18928. digits.splice(Math.max(parsedNumber.i, roundAt));
  18929. // Set non-fractional digits beyond `roundAt` to 0
  18930. for (var j = roundAt; j < digits.length; j++) {
  18931. digits[j] = 0;
  18932. }
  18933. } else {
  18934. // We rounded to zero so reset the parsedNumber
  18935. fractionLen = Math.max(0, fractionLen);
  18936. parsedNumber.i = 1;
  18937. digits.length = Math.max(1, roundAt = fractionSize + 1);
  18938. digits[0] = 0;
  18939. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  18940. }
  18941. if (digit >= 5) {
  18942. if (roundAt - 1 < 0) {
  18943. for (var k = 0; k > roundAt; k--) {
  18944. digits.unshift(0);
  18945. parsedNumber.i++;
  18946. }
  18947. digits.unshift(1);
  18948. parsedNumber.i++;
  18949. } else {
  18950. digits[roundAt - 1]++;
  18951. }
  18952. }
  18953. // Pad out with zeros to get the required fraction length
  18954. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  18955. // Do any carrying, e.g. a digit was rounded up to 10
  18956. var carry = digits.reduceRight(function(carry, d, i, digits) {
  18957. d = d + carry;
  18958. digits[i] = d % 10;
  18959. return Math.floor(d / 10);
  18960. }, 0);
  18961. if (carry) {
  18962. digits.unshift(carry);
  18963. parsedNumber.i++;
  18964. }
  18965. }
  18966. /**
  18967. * Format a number into a string
  18968. * @param {number} number The number to format
  18969. * @param {{
  18970. * minFrac, // the minimum number of digits required in the fraction part of the number
  18971. * maxFrac, // the maximum number of digits required in the fraction part of the number
  18972. * gSize, // number of digits in each group of separated digits
  18973. * lgSize, // number of digits in the last group of digits before the decimal separator
  18974. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  18975. * posPre, // the string to go in front of a positive number
  18976. * negSuf, // the string to go after a negative number (e.g. `)`)
  18977. * posSuf // the string to go after a positive number
  18978. * }} pattern
  18979. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  18980. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  18981. * @param {[type]} fractionSize The size of the fractional part of the number
  18982. * @return {string} The number formatted as a string
  18983. */
  18984. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  18985. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  18986. var isInfinity = !isFinite(number);
  18987. var isZero = false;
  18988. var numStr = Math.abs(number) + '',
  18989. formattedText = '',
  18990. parsedNumber;
  18991. if (isInfinity) {
  18992. formattedText = '\u221e';
  18993. } else {
  18994. parsedNumber = parse(numStr);
  18995. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  18996. var digits = parsedNumber.d;
  18997. var integerLen = parsedNumber.i;
  18998. var exponent = parsedNumber.e;
  18999. var decimals = [];
  19000. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  19001. // pad zeros for small numbers
  19002. while (integerLen < 0) {
  19003. digits.unshift(0);
  19004. integerLen++;
  19005. }
  19006. // extract decimals digits
  19007. if (integerLen > 0) {
  19008. decimals = digits.splice(integerLen, digits.length);
  19009. } else {
  19010. decimals = digits;
  19011. digits = [0];
  19012. }
  19013. // format the integer digits with grouping separators
  19014. var groups = [];
  19015. if (digits.length >= pattern.lgSize) {
  19016. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  19017. }
  19018. while (digits.length > pattern.gSize) {
  19019. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  19020. }
  19021. if (digits.length) {
  19022. groups.unshift(digits.join(''));
  19023. }
  19024. formattedText = groups.join(groupSep);
  19025. // append the decimal digits
  19026. if (decimals.length) {
  19027. formattedText += decimalSep + decimals.join('');
  19028. }
  19029. if (exponent) {
  19030. formattedText += 'e+' + exponent;
  19031. }
  19032. }
  19033. if (number < 0 && !isZero) {
  19034. return pattern.negPre + formattedText + pattern.negSuf;
  19035. } else {
  19036. return pattern.posPre + formattedText + pattern.posSuf;
  19037. }
  19038. }
  19039. function padNumber(num, digits, trim, negWrap) {
  19040. var neg = '';
  19041. if (num < 0 || (negWrap && num <= 0)) {
  19042. if (negWrap) {
  19043. num = -num + 1;
  19044. } else {
  19045. num = -num;
  19046. neg = '-';
  19047. }
  19048. }
  19049. num = '' + num;
  19050. while (num.length < digits) num = ZERO_CHAR + num;
  19051. if (trim) {
  19052. num = num.substr(num.length - digits);
  19053. }
  19054. return neg + num;
  19055. }
  19056. function dateGetter(name, size, offset, trim, negWrap) {
  19057. offset = offset || 0;
  19058. return function(date) {
  19059. var value = date['get' + name]();
  19060. if (offset > 0 || value > -offset) {
  19061. value += offset;
  19062. }
  19063. if (value === 0 && offset === -12) value = 12;
  19064. return padNumber(value, size, trim, negWrap);
  19065. };
  19066. }
  19067. function dateStrGetter(name, shortForm, standAlone) {
  19068. return function(date, formats) {
  19069. var value = date['get' + name]();
  19070. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  19071. var get = uppercase(propPrefix + name);
  19072. return formats[get][value];
  19073. };
  19074. }
  19075. function timeZoneGetter(date, formats, offset) {
  19076. var zone = -1 * offset;
  19077. var paddedZone = (zone >= 0) ? '+' : '';
  19078. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  19079. padNumber(Math.abs(zone % 60), 2);
  19080. return paddedZone;
  19081. }
  19082. function getFirstThursdayOfYear(year) {
  19083. // 0 = index of January
  19084. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  19085. // 4 = index of Thursday (+1 to account for 1st = 5)
  19086. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  19087. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  19088. }
  19089. function getThursdayThisWeek(datetime) {
  19090. return new Date(datetime.getFullYear(), datetime.getMonth(),
  19091. // 4 = index of Thursday
  19092. datetime.getDate() + (4 - datetime.getDay()));
  19093. }
  19094. function weekGetter(size) {
  19095. return function(date) {
  19096. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  19097. thisThurs = getThursdayThisWeek(date);
  19098. var diff = +thisThurs - +firstThurs,
  19099. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  19100. return padNumber(result, size);
  19101. };
  19102. }
  19103. function ampmGetter(date, formats) {
  19104. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  19105. }
  19106. function eraGetter(date, formats) {
  19107. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  19108. }
  19109. function longEraGetter(date, formats) {
  19110. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  19111. }
  19112. var DATE_FORMATS = {
  19113. yyyy: dateGetter('FullYear', 4, 0, false, true),
  19114. yy: dateGetter('FullYear', 2, 0, true, true),
  19115. y: dateGetter('FullYear', 1, 0, false, true),
  19116. MMMM: dateStrGetter('Month'),
  19117. MMM: dateStrGetter('Month', true),
  19118. MM: dateGetter('Month', 2, 1),
  19119. M: dateGetter('Month', 1, 1),
  19120. LLLL: dateStrGetter('Month', false, true),
  19121. dd: dateGetter('Date', 2),
  19122. d: dateGetter('Date', 1),
  19123. HH: dateGetter('Hours', 2),
  19124. H: dateGetter('Hours', 1),
  19125. hh: dateGetter('Hours', 2, -12),
  19126. h: dateGetter('Hours', 1, -12),
  19127. mm: dateGetter('Minutes', 2),
  19128. m: dateGetter('Minutes', 1),
  19129. ss: dateGetter('Seconds', 2),
  19130. s: dateGetter('Seconds', 1),
  19131. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  19132. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  19133. sss: dateGetter('Milliseconds', 3),
  19134. EEEE: dateStrGetter('Day'),
  19135. EEE: dateStrGetter('Day', true),
  19136. a: ampmGetter,
  19137. Z: timeZoneGetter,
  19138. ww: weekGetter(2),
  19139. w: weekGetter(1),
  19140. G: eraGetter,
  19141. GG: eraGetter,
  19142. GGG: eraGetter,
  19143. GGGG: longEraGetter
  19144. };
  19145. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  19146. NUMBER_STRING = /^-?\d+$/;
  19147. /**
  19148. * @ngdoc filter
  19149. * @name date
  19150. * @kind function
  19151. *
  19152. * @description
  19153. * Formats `date` to a string based on the requested `format`.
  19154. *
  19155. * `format` string can be composed of the following elements:
  19156. *
  19157. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  19158. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  19159. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  19160. * * `'MMMM'`: Month in year (January-December)
  19161. * * `'MMM'`: Month in year (Jan-Dec)
  19162. * * `'MM'`: Month in year, padded (01-12)
  19163. * * `'M'`: Month in year (1-12)
  19164. * * `'LLLL'`: Stand-alone month in year (January-December)
  19165. * * `'dd'`: Day in month, padded (01-31)
  19166. * * `'d'`: Day in month (1-31)
  19167. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  19168. * * `'EEE'`: Day in Week, (Sun-Sat)
  19169. * * `'HH'`: Hour in day, padded (00-23)
  19170. * * `'H'`: Hour in day (0-23)
  19171. * * `'hh'`: Hour in AM/PM, padded (01-12)
  19172. * * `'h'`: Hour in AM/PM, (1-12)
  19173. * * `'mm'`: Minute in hour, padded (00-59)
  19174. * * `'m'`: Minute in hour (0-59)
  19175. * * `'ss'`: Second in minute, padded (00-59)
  19176. * * `'s'`: Second in minute (0-59)
  19177. * * `'sss'`: Millisecond in second, padded (000-999)
  19178. * * `'a'`: AM/PM marker
  19179. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  19180. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  19181. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  19182. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  19183. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  19184. *
  19185. * `format` string can also be one of the following predefined
  19186. * {@link guide/i18n localizable formats}:
  19187. *
  19188. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  19189. * (e.g. Sep 3, 2010 12:05:08 PM)
  19190. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  19191. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  19192. * (e.g. Friday, September 3, 2010)
  19193. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  19194. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  19195. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  19196. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  19197. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  19198. *
  19199. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  19200. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  19201. * (e.g. `"h 'o''clock'"`).
  19202. *
  19203. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  19204. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  19205. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  19206. * specified in the string input, the time is considered to be in the local timezone.
  19207. * @param {string=} format Formatting rules (see Description). If not specified,
  19208. * `mediumDate` is used.
  19209. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  19210. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  19211. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  19212. * If not specified, the timezone of the browser will be used.
  19213. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  19214. *
  19215. * @example
  19216. <example name="filter-date">
  19217. <file name="index.html">
  19218. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  19219. <span>{{1288323623006 | date:'medium'}}</span><br>
  19220. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  19221. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  19222. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  19223. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  19224. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  19225. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  19226. </file>
  19227. <file name="protractor.js" type="protractor">
  19228. it('should format date', function() {
  19229. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  19230. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  19231. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  19232. toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
  19233. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  19234. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  19235. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  19236. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  19237. });
  19238. </file>
  19239. </example>
  19240. */
  19241. dateFilter.$inject = ['$locale'];
  19242. function dateFilter($locale) {
  19243. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  19244. // 1 2 3 4 5 6 7 8 9 10 11
  19245. function jsonStringToDate(string) {
  19246. var match;
  19247. if ((match = string.match(R_ISO8601_STR))) {
  19248. var date = new Date(0),
  19249. tzHour = 0,
  19250. tzMin = 0,
  19251. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  19252. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  19253. if (match[9]) {
  19254. tzHour = toInt(match[9] + match[10]);
  19255. tzMin = toInt(match[9] + match[11]);
  19256. }
  19257. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  19258. var h = toInt(match[4] || 0) - tzHour;
  19259. var m = toInt(match[5] || 0) - tzMin;
  19260. var s = toInt(match[6] || 0);
  19261. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  19262. timeSetter.call(date, h, m, s, ms);
  19263. return date;
  19264. }
  19265. return string;
  19266. }
  19267. return function(date, format, timezone) {
  19268. var text = '',
  19269. parts = [],
  19270. fn, match;
  19271. format = format || 'mediumDate';
  19272. format = $locale.DATETIME_FORMATS[format] || format;
  19273. if (isString(date)) {
  19274. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  19275. }
  19276. if (isNumber(date)) {
  19277. date = new Date(date);
  19278. }
  19279. if (!isDate(date) || !isFinite(date.getTime())) {
  19280. return date;
  19281. }
  19282. while (format) {
  19283. match = DATE_FORMATS_SPLIT.exec(format);
  19284. if (match) {
  19285. parts = concat(parts, match, 1);
  19286. format = parts.pop();
  19287. } else {
  19288. parts.push(format);
  19289. format = null;
  19290. }
  19291. }
  19292. var dateTimezoneOffset = date.getTimezoneOffset();
  19293. if (timezone) {
  19294. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  19295. date = convertTimezoneToLocal(date, timezone, true);
  19296. }
  19297. forEach(parts, function(value) {
  19298. fn = DATE_FORMATS[value];
  19299. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  19300. : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
  19301. });
  19302. return text;
  19303. };
  19304. }
  19305. /**
  19306. * @ngdoc filter
  19307. * @name json
  19308. * @kind function
  19309. *
  19310. * @description
  19311. * Allows you to convert a JavaScript object into JSON string.
  19312. *
  19313. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  19314. * the binding is automatically converted to JSON.
  19315. *
  19316. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  19317. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  19318. * @returns {string} JSON string.
  19319. *
  19320. *
  19321. * @example
  19322. <example name="filter-json">
  19323. <file name="index.html">
  19324. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  19325. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  19326. </file>
  19327. <file name="protractor.js" type="protractor">
  19328. it('should jsonify filtered objects', function() {
  19329. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
  19330. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
  19331. });
  19332. </file>
  19333. </example>
  19334. *
  19335. */
  19336. function jsonFilter() {
  19337. return function(object, spacing) {
  19338. if (isUndefined(spacing)) {
  19339. spacing = 2;
  19340. }
  19341. return toJson(object, spacing);
  19342. };
  19343. }
  19344. /**
  19345. * @ngdoc filter
  19346. * @name lowercase
  19347. * @kind function
  19348. * @description
  19349. * Converts string to lowercase.
  19350. * @see angular.lowercase
  19351. */
  19352. var lowercaseFilter = valueFn(lowercase);
  19353. /**
  19354. * @ngdoc filter
  19355. * @name uppercase
  19356. * @kind function
  19357. * @description
  19358. * Converts string to uppercase.
  19359. * @see angular.uppercase
  19360. */
  19361. var uppercaseFilter = valueFn(uppercase);
  19362. /**
  19363. * @ngdoc filter
  19364. * @name limitTo
  19365. * @kind function
  19366. *
  19367. * @description
  19368. * Creates a new array or string containing only a specified number of elements. The elements are
  19369. * taken from either the beginning or the end of the source array, string or number, as specified by
  19370. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  19371. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  19372. * it is converted to a string.
  19373. *
  19374. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  19375. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  19376. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  19377. * If the number is negative, `limit` number of items from the end of the source array/string
  19378. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  19379. * the input will be returned unchanged.
  19380. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  19381. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  19382. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  19383. * less than `limit` elements.
  19384. *
  19385. * @example
  19386. <example module="limitToExample" name="limit-to-filter">
  19387. <file name="index.html">
  19388. <script>
  19389. angular.module('limitToExample', [])
  19390. .controller('ExampleController', ['$scope', function($scope) {
  19391. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  19392. $scope.letters = "abcdefghi";
  19393. $scope.longNumber = 2345432342;
  19394. $scope.numLimit = 3;
  19395. $scope.letterLimit = 3;
  19396. $scope.longNumberLimit = 3;
  19397. }]);
  19398. </script>
  19399. <div ng-controller="ExampleController">
  19400. <label>
  19401. Limit {{numbers}} to:
  19402. <input type="number" step="1" ng-model="numLimit">
  19403. </label>
  19404. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  19405. <label>
  19406. Limit {{letters}} to:
  19407. <input type="number" step="1" ng-model="letterLimit">
  19408. </label>
  19409. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  19410. <label>
  19411. Limit {{longNumber}} to:
  19412. <input type="number" step="1" ng-model="longNumberLimit">
  19413. </label>
  19414. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  19415. </div>
  19416. </file>
  19417. <file name="protractor.js" type="protractor">
  19418. var numLimitInput = element(by.model('numLimit'));
  19419. var letterLimitInput = element(by.model('letterLimit'));
  19420. var longNumberLimitInput = element(by.model('longNumberLimit'));
  19421. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  19422. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  19423. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  19424. it('should limit the number array to first three items', function() {
  19425. expect(numLimitInput.getAttribute('value')).toBe('3');
  19426. expect(letterLimitInput.getAttribute('value')).toBe('3');
  19427. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  19428. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  19429. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  19430. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  19431. });
  19432. // There is a bug in safari and protractor that doesn't like the minus key
  19433. // it('should update the output when -3 is entered', function() {
  19434. // numLimitInput.clear();
  19435. // numLimitInput.sendKeys('-3');
  19436. // letterLimitInput.clear();
  19437. // letterLimitInput.sendKeys('-3');
  19438. // longNumberLimitInput.clear();
  19439. // longNumberLimitInput.sendKeys('-3');
  19440. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  19441. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  19442. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  19443. // });
  19444. it('should not exceed the maximum size of input array', function() {
  19445. numLimitInput.clear();
  19446. numLimitInput.sendKeys('100');
  19447. letterLimitInput.clear();
  19448. letterLimitInput.sendKeys('100');
  19449. longNumberLimitInput.clear();
  19450. longNumberLimitInput.sendKeys('100');
  19451. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  19452. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  19453. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  19454. });
  19455. </file>
  19456. </example>
  19457. */
  19458. function limitToFilter() {
  19459. return function(input, limit, begin) {
  19460. if (Math.abs(Number(limit)) === Infinity) {
  19461. limit = Number(limit);
  19462. } else {
  19463. limit = toInt(limit);
  19464. }
  19465. if (isNumberNaN(limit)) return input;
  19466. if (isNumber(input)) input = input.toString();
  19467. if (!isArrayLike(input)) return input;
  19468. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  19469. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  19470. if (limit >= 0) {
  19471. return sliceFn(input, begin, begin + limit);
  19472. } else {
  19473. if (begin === 0) {
  19474. return sliceFn(input, limit, input.length);
  19475. } else {
  19476. return sliceFn(input, Math.max(0, begin + limit), begin);
  19477. }
  19478. }
  19479. };
  19480. }
  19481. function sliceFn(input, begin, end) {
  19482. if (isString(input)) return input.slice(begin, end);
  19483. return slice.call(input, begin, end);
  19484. }
  19485. /**
  19486. * @ngdoc filter
  19487. * @name orderBy
  19488. * @kind function
  19489. *
  19490. * @description
  19491. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  19492. * function based on the values computed using the `expression` predicate.
  19493. *
  19494. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  19495. * `[{id: 'bar'}, {id: 'foo'}]`.
  19496. *
  19497. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  19498. * String, etc).
  19499. *
  19500. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  19501. * for the preceding one. The `expression` is evaluated against each item and the output is used
  19502. * for comparing with other items.
  19503. *
  19504. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  19505. * ascending order.
  19506. *
  19507. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  19508. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  19509. * strings alphabetically).
  19510. *
  19511. * ### Under the hood
  19512. *
  19513. * Ordering the specified `collection` happens in two phases:
  19514. *
  19515. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  19516. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  19517. * through a predicate that extracts the value of the `label` property, would be transformed to:
  19518. * ```
  19519. * {
  19520. * value: 'foo',
  19521. * type: 'string',
  19522. * index: ...
  19523. * }
  19524. * ```
  19525. * 2. The comparator function is used to sort the items, based on the derived values, types and
  19526. * indices.
  19527. *
  19528. * If you use a custom comparator, it will be called with pairs of objects of the form
  19529. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  19530. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  19531. * second, or `1` otherwise.
  19532. *
  19533. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  19534. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  19535. * dummy predicate that returns the item's index as `value`.
  19536. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  19537. *
  19538. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  19539. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  19540. * it to the comparator. The following rules govern the conversion:
  19541. *
  19542. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  19543. * used instead.<br />
  19544. * (If the object has a `valueOf()` method that returns another object, then the returned object
  19545. * will be used in subsequent steps.)
  19546. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  19547. * returns a primitive, its return value will be used instead.<br />
  19548. * (If the object has a `toString()` method that returns another object, then the returned object
  19549. * will be used in subsequent steps.)
  19550. * 3. No conversion; the object itself is used.
  19551. *
  19552. * ### The default comparator
  19553. *
  19554. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  19555. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  19556. * using their index in the original collection, and sorts values of different types by type.
  19557. *
  19558. * More specifically, it follows these steps to determine the relative order of items:
  19559. *
  19560. * 1. If the compared values are of different types, compare the types themselves alphabetically.
  19561. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  19562. * locale-insensitive way.
  19563. * 3. If both values are objects, compare their indices instead.
  19564. * 4. Otherwise, return:
  19565. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  19566. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  19567. * - `1`, otherwise.
  19568. *
  19569. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  19570. * saved as numbers and not strings.
  19571. * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e.
  19572. * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to
  19573. * other values.
  19574. *
  19575. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  19576. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  19577. * predicates) to be used by the comparator to determine the order of elements.
  19578. *
  19579. * Can be one of:
  19580. *
  19581. * - `Function`: A getter function. This function will be called with each item as argument and
  19582. * the return value will be used for sorting.
  19583. * - `string`: An Angular expression. This expression will be evaluated against each item and the
  19584. * result will be used for sorting. For example, use `'label'` to sort by a property called
  19585. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  19586. * property.<br />
  19587. * (The result of a constant expression is interpreted as a property name to be used for
  19588. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  19589. * property called `special name`.)<br />
  19590. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  19591. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  19592. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  19593. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  19594. * relative order of two items, the next predicate is used as a tie-breaker.
  19595. *
  19596. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  19597. *
  19598. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  19599. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  19600. * value pairs. If omitted, the built-in comparator will be used.
  19601. *
  19602. * @returns {Array} - The sorted array.
  19603. *
  19604. *
  19605. * @example
  19606. * ### Ordering a table with `ngRepeat`
  19607. *
  19608. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  19609. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  19610. * it defaults to the built-in comparator.
  19611. *
  19612. <example name="orderBy-static" module="orderByExample1">
  19613. <file name="index.html">
  19614. <div ng-controller="ExampleController">
  19615. <table class="friends">
  19616. <tr>
  19617. <th>Name</th>
  19618. <th>Phone Number</th>
  19619. <th>Age</th>
  19620. </tr>
  19621. <tr ng-repeat="friend in friends | orderBy:'-age'">
  19622. <td>{{friend.name}}</td>
  19623. <td>{{friend.phone}}</td>
  19624. <td>{{friend.age}}</td>
  19625. </tr>
  19626. </table>
  19627. </div>
  19628. </file>
  19629. <file name="script.js">
  19630. angular.module('orderByExample1', [])
  19631. .controller('ExampleController', ['$scope', function($scope) {
  19632. $scope.friends = [
  19633. {name: 'John', phone: '555-1212', age: 10},
  19634. {name: 'Mary', phone: '555-9876', age: 19},
  19635. {name: 'Mike', phone: '555-4321', age: 21},
  19636. {name: 'Adam', phone: '555-5678', age: 35},
  19637. {name: 'Julie', phone: '555-8765', age: 29}
  19638. ];
  19639. }]);
  19640. </file>
  19641. <file name="style.css">
  19642. .friends {
  19643. border-collapse: collapse;
  19644. }
  19645. .friends th {
  19646. border-bottom: 1px solid;
  19647. }
  19648. .friends td, .friends th {
  19649. border-left: 1px solid;
  19650. padding: 5px 10px;
  19651. }
  19652. .friends td:first-child, .friends th:first-child {
  19653. border-left: none;
  19654. }
  19655. </file>
  19656. <file name="protractor.js" type="protractor">
  19657. // Element locators
  19658. var names = element.all(by.repeater('friends').column('friend.name'));
  19659. it('should sort friends by age in reverse order', function() {
  19660. expect(names.get(0).getText()).toBe('Adam');
  19661. expect(names.get(1).getText()).toBe('Julie');
  19662. expect(names.get(2).getText()).toBe('Mike');
  19663. expect(names.get(3).getText()).toBe('Mary');
  19664. expect(names.get(4).getText()).toBe('John');
  19665. });
  19666. </file>
  19667. </example>
  19668. * <hr />
  19669. *
  19670. * @example
  19671. * ### Changing parameters dynamically
  19672. *
  19673. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  19674. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  19675. *
  19676. <example name="orderBy-dynamic" module="orderByExample2">
  19677. <file name="index.html">
  19678. <div ng-controller="ExampleController">
  19679. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19680. <hr/>
  19681. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  19682. <hr/>
  19683. <table class="friends">
  19684. <tr>
  19685. <th>
  19686. <button ng-click="sortBy('name')">Name</button>
  19687. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19688. </th>
  19689. <th>
  19690. <button ng-click="sortBy('phone')">Phone Number</button>
  19691. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19692. </th>
  19693. <th>
  19694. <button ng-click="sortBy('age')">Age</button>
  19695. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19696. </th>
  19697. </tr>
  19698. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  19699. <td>{{friend.name}}</td>
  19700. <td>{{friend.phone}}</td>
  19701. <td>{{friend.age}}</td>
  19702. </tr>
  19703. </table>
  19704. </div>
  19705. </file>
  19706. <file name="script.js">
  19707. angular.module('orderByExample2', [])
  19708. .controller('ExampleController', ['$scope', function($scope) {
  19709. var friends = [
  19710. {name: 'John', phone: '555-1212', age: 10},
  19711. {name: 'Mary', phone: '555-9876', age: 19},
  19712. {name: 'Mike', phone: '555-4321', age: 21},
  19713. {name: 'Adam', phone: '555-5678', age: 35},
  19714. {name: 'Julie', phone: '555-8765', age: 29}
  19715. ];
  19716. $scope.propertyName = 'age';
  19717. $scope.reverse = true;
  19718. $scope.friends = friends;
  19719. $scope.sortBy = function(propertyName) {
  19720. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  19721. $scope.propertyName = propertyName;
  19722. };
  19723. }]);
  19724. </file>
  19725. <file name="style.css">
  19726. .friends {
  19727. border-collapse: collapse;
  19728. }
  19729. .friends th {
  19730. border-bottom: 1px solid;
  19731. }
  19732. .friends td, .friends th {
  19733. border-left: 1px solid;
  19734. padding: 5px 10px;
  19735. }
  19736. .friends td:first-child, .friends th:first-child {
  19737. border-left: none;
  19738. }
  19739. .sortorder:after {
  19740. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19741. }
  19742. .sortorder.reverse:after {
  19743. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19744. }
  19745. </file>
  19746. <file name="protractor.js" type="protractor">
  19747. // Element locators
  19748. var unsortButton = element(by.partialButtonText('unsorted'));
  19749. var nameHeader = element(by.partialButtonText('Name'));
  19750. var phoneHeader = element(by.partialButtonText('Phone'));
  19751. var ageHeader = element(by.partialButtonText('Age'));
  19752. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19753. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19754. it('should sort friends by some property, when clicking on the column header', function() {
  19755. expect(firstName.getText()).toBe('Adam');
  19756. expect(lastName.getText()).toBe('John');
  19757. phoneHeader.click();
  19758. expect(firstName.getText()).toBe('John');
  19759. expect(lastName.getText()).toBe('Mary');
  19760. nameHeader.click();
  19761. expect(firstName.getText()).toBe('Adam');
  19762. expect(lastName.getText()).toBe('Mike');
  19763. ageHeader.click();
  19764. expect(firstName.getText()).toBe('John');
  19765. expect(lastName.getText()).toBe('Adam');
  19766. });
  19767. it('should sort friends in reverse order, when clicking on the same column', function() {
  19768. expect(firstName.getText()).toBe('Adam');
  19769. expect(lastName.getText()).toBe('John');
  19770. ageHeader.click();
  19771. expect(firstName.getText()).toBe('John');
  19772. expect(lastName.getText()).toBe('Adam');
  19773. ageHeader.click();
  19774. expect(firstName.getText()).toBe('Adam');
  19775. expect(lastName.getText()).toBe('John');
  19776. });
  19777. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19778. expect(firstName.getText()).toBe('Adam');
  19779. expect(lastName.getText()).toBe('John');
  19780. unsortButton.click();
  19781. expect(firstName.getText()).toBe('John');
  19782. expect(lastName.getText()).toBe('Julie');
  19783. });
  19784. </file>
  19785. </example>
  19786. * <hr />
  19787. *
  19788. * @example
  19789. * ### Using `orderBy` inside a controller
  19790. *
  19791. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  19792. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  19793. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  19794. *
  19795. <example name="orderBy-call-manually" module="orderByExample3">
  19796. <file name="index.html">
  19797. <div ng-controller="ExampleController">
  19798. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19799. <hr/>
  19800. <button ng-click="sortBy(null)">Set to unsorted</button>
  19801. <hr/>
  19802. <table class="friends">
  19803. <tr>
  19804. <th>
  19805. <button ng-click="sortBy('name')">Name</button>
  19806. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19807. </th>
  19808. <th>
  19809. <button ng-click="sortBy('phone')">Phone Number</button>
  19810. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19811. </th>
  19812. <th>
  19813. <button ng-click="sortBy('age')">Age</button>
  19814. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19815. </th>
  19816. </tr>
  19817. <tr ng-repeat="friend in friends">
  19818. <td>{{friend.name}}</td>
  19819. <td>{{friend.phone}}</td>
  19820. <td>{{friend.age}}</td>
  19821. </tr>
  19822. </table>
  19823. </div>
  19824. </file>
  19825. <file name="script.js">
  19826. angular.module('orderByExample3', [])
  19827. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  19828. var friends = [
  19829. {name: 'John', phone: '555-1212', age: 10},
  19830. {name: 'Mary', phone: '555-9876', age: 19},
  19831. {name: 'Mike', phone: '555-4321', age: 21},
  19832. {name: 'Adam', phone: '555-5678', age: 35},
  19833. {name: 'Julie', phone: '555-8765', age: 29}
  19834. ];
  19835. $scope.propertyName = 'age';
  19836. $scope.reverse = true;
  19837. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19838. $scope.sortBy = function(propertyName) {
  19839. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  19840. ? !$scope.reverse : false;
  19841. $scope.propertyName = propertyName;
  19842. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19843. };
  19844. }]);
  19845. </file>
  19846. <file name="style.css">
  19847. .friends {
  19848. border-collapse: collapse;
  19849. }
  19850. .friends th {
  19851. border-bottom: 1px solid;
  19852. }
  19853. .friends td, .friends th {
  19854. border-left: 1px solid;
  19855. padding: 5px 10px;
  19856. }
  19857. .friends td:first-child, .friends th:first-child {
  19858. border-left: none;
  19859. }
  19860. .sortorder:after {
  19861. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19862. }
  19863. .sortorder.reverse:after {
  19864. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19865. }
  19866. </file>
  19867. <file name="protractor.js" type="protractor">
  19868. // Element locators
  19869. var unsortButton = element(by.partialButtonText('unsorted'));
  19870. var nameHeader = element(by.partialButtonText('Name'));
  19871. var phoneHeader = element(by.partialButtonText('Phone'));
  19872. var ageHeader = element(by.partialButtonText('Age'));
  19873. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19874. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19875. it('should sort friends by some property, when clicking on the column header', function() {
  19876. expect(firstName.getText()).toBe('Adam');
  19877. expect(lastName.getText()).toBe('John');
  19878. phoneHeader.click();
  19879. expect(firstName.getText()).toBe('John');
  19880. expect(lastName.getText()).toBe('Mary');
  19881. nameHeader.click();
  19882. expect(firstName.getText()).toBe('Adam');
  19883. expect(lastName.getText()).toBe('Mike');
  19884. ageHeader.click();
  19885. expect(firstName.getText()).toBe('John');
  19886. expect(lastName.getText()).toBe('Adam');
  19887. });
  19888. it('should sort friends in reverse order, when clicking on the same column', function() {
  19889. expect(firstName.getText()).toBe('Adam');
  19890. expect(lastName.getText()).toBe('John');
  19891. ageHeader.click();
  19892. expect(firstName.getText()).toBe('John');
  19893. expect(lastName.getText()).toBe('Adam');
  19894. ageHeader.click();
  19895. expect(firstName.getText()).toBe('Adam');
  19896. expect(lastName.getText()).toBe('John');
  19897. });
  19898. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19899. expect(firstName.getText()).toBe('Adam');
  19900. expect(lastName.getText()).toBe('John');
  19901. unsortButton.click();
  19902. expect(firstName.getText()).toBe('John');
  19903. expect(lastName.getText()).toBe('Julie');
  19904. });
  19905. </file>
  19906. </example>
  19907. * <hr />
  19908. *
  19909. * @example
  19910. * ### Using a custom comparator
  19911. *
  19912. * If you have very specific requirements about the way items are sorted, you can pass your own
  19913. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  19914. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  19915. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  19916. *
  19917. <example name="orderBy-custom-comparator" module="orderByExample4">
  19918. <file name="index.html">
  19919. <div ng-controller="ExampleController">
  19920. <div class="friends-container custom-comparator">
  19921. <h3>Locale-sensitive Comparator</h3>
  19922. <table class="friends">
  19923. <tr>
  19924. <th>Name</th>
  19925. <th>Favorite Letter</th>
  19926. </tr>
  19927. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  19928. <td>{{friend.name}}</td>
  19929. <td>{{friend.favoriteLetter}}</td>
  19930. </tr>
  19931. </table>
  19932. </div>
  19933. <div class="friends-container default-comparator">
  19934. <h3>Default Comparator</h3>
  19935. <table class="friends">
  19936. <tr>
  19937. <th>Name</th>
  19938. <th>Favorite Letter</th>
  19939. </tr>
  19940. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  19941. <td>{{friend.name}}</td>
  19942. <td>{{friend.favoriteLetter}}</td>
  19943. </tr>
  19944. </table>
  19945. </div>
  19946. </div>
  19947. </file>
  19948. <file name="script.js">
  19949. angular.module('orderByExample4', [])
  19950. .controller('ExampleController', ['$scope', function($scope) {
  19951. $scope.friends = [
  19952. {name: 'John', favoriteLetter: 'Ä'},
  19953. {name: 'Mary', favoriteLetter: 'Ü'},
  19954. {name: 'Mike', favoriteLetter: 'Ö'},
  19955. {name: 'Adam', favoriteLetter: 'H'},
  19956. {name: 'Julie', favoriteLetter: 'Z'}
  19957. ];
  19958. $scope.localeSensitiveComparator = function(v1, v2) {
  19959. // If we don't get strings, just compare by index
  19960. if (v1.type !== 'string' || v2.type !== 'string') {
  19961. return (v1.index < v2.index) ? -1 : 1;
  19962. }
  19963. // Compare strings alphabetically, taking locale into account
  19964. return v1.value.localeCompare(v2.value);
  19965. };
  19966. }]);
  19967. </file>
  19968. <file name="style.css">
  19969. .friends-container {
  19970. display: inline-block;
  19971. margin: 0 30px;
  19972. }
  19973. .friends {
  19974. border-collapse: collapse;
  19975. }
  19976. .friends th {
  19977. border-bottom: 1px solid;
  19978. }
  19979. .friends td, .friends th {
  19980. border-left: 1px solid;
  19981. padding: 5px 10px;
  19982. }
  19983. .friends td:first-child, .friends th:first-child {
  19984. border-left: none;
  19985. }
  19986. </file>
  19987. <file name="protractor.js" type="protractor">
  19988. // Element locators
  19989. var container = element(by.css('.custom-comparator'));
  19990. var names = container.all(by.repeater('friends').column('friend.name'));
  19991. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  19992. expect(names.get(0).getText()).toBe('John');
  19993. expect(names.get(1).getText()).toBe('Adam');
  19994. expect(names.get(2).getText()).toBe('Mike');
  19995. expect(names.get(3).getText()).toBe('Mary');
  19996. expect(names.get(4).getText()).toBe('Julie');
  19997. });
  19998. </file>
  19999. </example>
  20000. *
  20001. */
  20002. orderByFilter.$inject = ['$parse'];
  20003. function orderByFilter($parse) {
  20004. return function(array, sortPredicate, reverseOrder, compareFn) {
  20005. if (array == null) return array;
  20006. if (!isArrayLike(array)) {
  20007. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  20008. }
  20009. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  20010. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  20011. var predicates = processPredicates(sortPredicate);
  20012. var descending = reverseOrder ? -1 : 1;
  20013. // Define the `compare()` function. Use a default comparator if none is specified.
  20014. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  20015. // The next three lines are a version of a Swartzian Transform idiom from Perl
  20016. // (sometimes called the Decorate-Sort-Undecorate idiom)
  20017. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  20018. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  20019. compareValues.sort(doComparison);
  20020. array = compareValues.map(function(item) { return item.value; });
  20021. return array;
  20022. function getComparisonObject(value, index) {
  20023. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  20024. // This will be used to keep the sort stable when none of the input predicates can
  20025. // distinguish between two elements.
  20026. return {
  20027. value: value,
  20028. tieBreaker: {value: index, type: 'number', index: index},
  20029. predicateValues: predicates.map(function(predicate) {
  20030. return getPredicateValue(predicate.get(value), index);
  20031. })
  20032. };
  20033. }
  20034. function doComparison(v1, v2) {
  20035. for (var i = 0, ii = predicates.length; i < ii; i++) {
  20036. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  20037. if (result) {
  20038. return result * predicates[i].descending * descending;
  20039. }
  20040. }
  20041. return compare(v1.tieBreaker, v2.tieBreaker) * descending;
  20042. }
  20043. };
  20044. function processPredicates(sortPredicates) {
  20045. return sortPredicates.map(function(predicate) {
  20046. var descending = 1, get = identity;
  20047. if (isFunction(predicate)) {
  20048. get = predicate;
  20049. } else if (isString(predicate)) {
  20050. if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
  20051. descending = predicate.charAt(0) === '-' ? -1 : 1;
  20052. predicate = predicate.substring(1);
  20053. }
  20054. if (predicate !== '') {
  20055. get = $parse(predicate);
  20056. if (get.constant) {
  20057. var key = get();
  20058. get = function(value) { return value[key]; };
  20059. }
  20060. }
  20061. }
  20062. return {get: get, descending: descending};
  20063. });
  20064. }
  20065. function isPrimitive(value) {
  20066. switch (typeof value) {
  20067. case 'number': /* falls through */
  20068. case 'boolean': /* falls through */
  20069. case 'string':
  20070. return true;
  20071. default:
  20072. return false;
  20073. }
  20074. }
  20075. function objectValue(value) {
  20076. // If `valueOf` is a valid function use that
  20077. if (isFunction(value.valueOf)) {
  20078. value = value.valueOf();
  20079. if (isPrimitive(value)) return value;
  20080. }
  20081. // If `toString` is a valid function and not the one from `Object.prototype` use that
  20082. if (hasCustomToString(value)) {
  20083. value = value.toString();
  20084. if (isPrimitive(value)) return value;
  20085. }
  20086. return value;
  20087. }
  20088. function getPredicateValue(value, index) {
  20089. var type = typeof value;
  20090. if (value === null) {
  20091. type = 'string';
  20092. value = 'null';
  20093. } else if (type === 'object') {
  20094. value = objectValue(value);
  20095. }
  20096. return {value: value, type: type, index: index};
  20097. }
  20098. function defaultCompare(v1, v2) {
  20099. var result = 0;
  20100. var type1 = v1.type;
  20101. var type2 = v2.type;
  20102. if (type1 === type2) {
  20103. var value1 = v1.value;
  20104. var value2 = v2.value;
  20105. if (type1 === 'string') {
  20106. // Compare strings case-insensitively
  20107. value1 = value1.toLowerCase();
  20108. value2 = value2.toLowerCase();
  20109. } else if (type1 === 'object') {
  20110. // For basic objects, use the position of the object
  20111. // in the collection instead of the value
  20112. if (isObject(value1)) value1 = v1.index;
  20113. if (isObject(value2)) value2 = v2.index;
  20114. }
  20115. if (value1 !== value2) {
  20116. result = value1 < value2 ? -1 : 1;
  20117. }
  20118. } else {
  20119. result = type1 < type2 ? -1 : 1;
  20120. }
  20121. return result;
  20122. }
  20123. }
  20124. function ngDirective(directive) {
  20125. if (isFunction(directive)) {
  20126. directive = {
  20127. link: directive
  20128. };
  20129. }
  20130. directive.restrict = directive.restrict || 'AC';
  20131. return valueFn(directive);
  20132. }
  20133. /**
  20134. * @ngdoc directive
  20135. * @name a
  20136. * @restrict E
  20137. *
  20138. * @description
  20139. * Modifies the default behavior of the html a tag so that the default action is prevented when
  20140. * the href attribute is empty.
  20141. *
  20142. * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
  20143. */
  20144. var htmlAnchorDirective = valueFn({
  20145. restrict: 'E',
  20146. compile: function(element, attr) {
  20147. if (!attr.href && !attr.xlinkHref) {
  20148. return function(scope, element) {
  20149. // If the linked element is not an anchor tag anymore, do nothing
  20150. if (element[0].nodeName.toLowerCase() !== 'a') return;
  20151. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  20152. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  20153. 'xlink:href' : 'href';
  20154. element.on('click', function(event) {
  20155. // if we have no href url, then don't navigate anywhere.
  20156. if (!element.attr(href)) {
  20157. event.preventDefault();
  20158. }
  20159. });
  20160. };
  20161. }
  20162. }
  20163. });
  20164. /**
  20165. * @ngdoc directive
  20166. * @name ngHref
  20167. * @restrict A
  20168. * @priority 99
  20169. *
  20170. * @description
  20171. * Using Angular markup like `{{hash}}` in an href attribute will
  20172. * make the link go to the wrong URL if the user clicks it before
  20173. * Angular has a chance to replace the `{{hash}}` markup with its
  20174. * value. Until Angular replaces the markup the link will be broken
  20175. * and will most likely return a 404 error. The `ngHref` directive
  20176. * solves this problem.
  20177. *
  20178. * The wrong way to write it:
  20179. * ```html
  20180. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20181. * ```
  20182. *
  20183. * The correct way to write it:
  20184. * ```html
  20185. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20186. * ```
  20187. *
  20188. * @element A
  20189. * @param {template} ngHref any string which can contain `{{}}` markup.
  20190. *
  20191. * @example
  20192. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  20193. * in links and their different behaviors:
  20194. <example name="ng-href">
  20195. <file name="index.html">
  20196. <input ng-model="value" /><br />
  20197. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  20198. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  20199. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  20200. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  20201. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  20202. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  20203. </file>
  20204. <file name="protractor.js" type="protractor">
  20205. it('should execute ng-click but not reload when href without value', function() {
  20206. element(by.id('link-1')).click();
  20207. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  20208. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  20209. });
  20210. it('should execute ng-click but not reload when href empty string', function() {
  20211. element(by.id('link-2')).click();
  20212. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  20213. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  20214. });
  20215. it('should execute ng-click and change url when ng-href specified', function() {
  20216. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  20217. element(by.id('link-3')).click();
  20218. // At this point, we navigate away from an Angular page, so we need
  20219. // to use browser.driver to get the base webdriver.
  20220. browser.wait(function() {
  20221. return browser.driver.getCurrentUrl().then(function(url) {
  20222. return url.match(/\/123$/);
  20223. });
  20224. }, 5000, 'page should navigate to /123');
  20225. });
  20226. it('should execute ng-click but not reload when href empty string and name specified', function() {
  20227. element(by.id('link-4')).click();
  20228. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  20229. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  20230. });
  20231. it('should execute ng-click but not reload when no href but name specified', function() {
  20232. element(by.id('link-5')).click();
  20233. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  20234. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  20235. });
  20236. it('should only change url when only ng-href', function() {
  20237. element(by.model('value')).clear();
  20238. element(by.model('value')).sendKeys('6');
  20239. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  20240. element(by.id('link-6')).click();
  20241. // At this point, we navigate away from an Angular page, so we need
  20242. // to use browser.driver to get the base webdriver.
  20243. browser.wait(function() {
  20244. return browser.driver.getCurrentUrl().then(function(url) {
  20245. return url.match(/\/6$/);
  20246. });
  20247. }, 5000, 'page should navigate to /6');
  20248. });
  20249. </file>
  20250. </example>
  20251. */
  20252. /**
  20253. * @ngdoc directive
  20254. * @name ngSrc
  20255. * @restrict A
  20256. * @priority 99
  20257. *
  20258. * @description
  20259. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  20260. * work right: The browser will fetch from the URL with the literal
  20261. * text `{{hash}}` until Angular replaces the expression inside
  20262. * `{{hash}}`. The `ngSrc` directive solves this problem.
  20263. *
  20264. * The buggy way to write it:
  20265. * ```html
  20266. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  20267. * ```
  20268. *
  20269. * The correct way to write it:
  20270. * ```html
  20271. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  20272. * ```
  20273. *
  20274. * @element IMG
  20275. * @param {template} ngSrc any string which can contain `{{}}` markup.
  20276. */
  20277. /**
  20278. * @ngdoc directive
  20279. * @name ngSrcset
  20280. * @restrict A
  20281. * @priority 99
  20282. *
  20283. * @description
  20284. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  20285. * work right: The browser will fetch from the URL with the literal
  20286. * text `{{hash}}` until Angular replaces the expression inside
  20287. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  20288. *
  20289. * The buggy way to write it:
  20290. * ```html
  20291. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  20292. * ```
  20293. *
  20294. * The correct way to write it:
  20295. * ```html
  20296. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  20297. * ```
  20298. *
  20299. * @element IMG
  20300. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  20301. */
  20302. /**
  20303. * @ngdoc directive
  20304. * @name ngDisabled
  20305. * @restrict A
  20306. * @priority 100
  20307. *
  20308. * @description
  20309. *
  20310. * This directive sets the `disabled` attribute on the element (typically a form control,
  20311. * e.g. `input`, `button`, `select` etc.) if the
  20312. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  20313. *
  20314. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  20315. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20316. *
  20317. * @example
  20318. <example name="ng-disabled">
  20319. <file name="index.html">
  20320. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  20321. <button ng-model="button" ng-disabled="checked">Button</button>
  20322. </file>
  20323. <file name="protractor.js" type="protractor">
  20324. it('should toggle button', function() {
  20325. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  20326. element(by.model('checked')).click();
  20327. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  20328. });
  20329. </file>
  20330. </example>
  20331. *
  20332. * @element INPUT
  20333. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  20334. * then the `disabled` attribute will be set on the element
  20335. */
  20336. /**
  20337. * @ngdoc directive
  20338. * @name ngChecked
  20339. * @restrict A
  20340. * @priority 100
  20341. *
  20342. * @description
  20343. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  20344. *
  20345. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  20346. * as this can lead to unexpected behavior.
  20347. *
  20348. * A special directive is necessary because we cannot use interpolation inside the `checked`
  20349. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20350. *
  20351. * @example
  20352. <example name="ng-checked">
  20353. <file name="index.html">
  20354. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  20355. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  20356. </file>
  20357. <file name="protractor.js" type="protractor">
  20358. it('should check both checkBoxes', function() {
  20359. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  20360. element(by.model('master')).click();
  20361. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  20362. });
  20363. </file>
  20364. </example>
  20365. *
  20366. * @element INPUT
  20367. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  20368. * then the `checked` attribute will be set on the element
  20369. */
  20370. /**
  20371. * @ngdoc directive
  20372. * @name ngReadonly
  20373. * @restrict A
  20374. * @priority 100
  20375. *
  20376. * @description
  20377. *
  20378. * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  20379. * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
  20380. * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
  20381. *
  20382. * A special directive is necessary because we cannot use interpolation inside the `readonly`
  20383. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20384. *
  20385. * @example
  20386. <example name="ng-readonly">
  20387. <file name="index.html">
  20388. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  20389. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  20390. </file>
  20391. <file name="protractor.js" type="protractor">
  20392. it('should toggle readonly attr', function() {
  20393. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  20394. element(by.model('checked')).click();
  20395. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  20396. });
  20397. </file>
  20398. </example>
  20399. *
  20400. * @element INPUT
  20401. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  20402. * then special attribute "readonly" will be set on the element
  20403. */
  20404. /**
  20405. * @ngdoc directive
  20406. * @name ngSelected
  20407. * @restrict A
  20408. * @priority 100
  20409. *
  20410. * @description
  20411. *
  20412. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  20413. *
  20414. * A special directive is necessary because we cannot use interpolation inside the `selected`
  20415. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20416. *
  20417. * <div class="alert alert-warning">
  20418. * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
  20419. * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
  20420. * should not use `ngSelected` on the options, as `ngModel` will set the select value and
  20421. * selected options.
  20422. * </div>
  20423. *
  20424. * @example
  20425. <example name="ng-selected">
  20426. <file name="index.html">
  20427. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  20428. <select aria-label="ngSelected demo">
  20429. <option>Hello!</option>
  20430. <option id="greet" ng-selected="selected">Greetings!</option>
  20431. </select>
  20432. </file>
  20433. <file name="protractor.js" type="protractor">
  20434. it('should select Greetings!', function() {
  20435. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  20436. element(by.model('selected')).click();
  20437. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  20438. });
  20439. </file>
  20440. </example>
  20441. *
  20442. * @element OPTION
  20443. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  20444. * then special attribute "selected" will be set on the element
  20445. */
  20446. /**
  20447. * @ngdoc directive
  20448. * @name ngOpen
  20449. * @restrict A
  20450. * @priority 100
  20451. *
  20452. * @description
  20453. *
  20454. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  20455. *
  20456. * A special directive is necessary because we cannot use interpolation inside the `open`
  20457. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20458. *
  20459. * ## A note about browser compatibility
  20460. *
  20461. * Edge, Firefox, and Internet Explorer do not support the `details` element, it is
  20462. * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
  20463. *
  20464. * @example
  20465. <example name="ng-open">
  20466. <file name="index.html">
  20467. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  20468. <details id="details" ng-open="open">
  20469. <summary>Show/Hide me</summary>
  20470. </details>
  20471. </file>
  20472. <file name="protractor.js" type="protractor">
  20473. it('should toggle open', function() {
  20474. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  20475. element(by.model('open')).click();
  20476. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  20477. });
  20478. </file>
  20479. </example>
  20480. *
  20481. * @element DETAILS
  20482. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  20483. * then special attribute "open" will be set on the element
  20484. */
  20485. var ngAttributeAliasDirectives = {};
  20486. // boolean attrs are evaluated
  20487. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  20488. // binding to multiple is not supported
  20489. if (propName === 'multiple') return;
  20490. function defaultLinkFn(scope, element, attr) {
  20491. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  20492. attr.$set(attrName, !!value);
  20493. });
  20494. }
  20495. var normalized = directiveNormalize('ng-' + attrName);
  20496. var linkFn = defaultLinkFn;
  20497. if (propName === 'checked') {
  20498. linkFn = function(scope, element, attr) {
  20499. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  20500. if (attr.ngModel !== attr[normalized]) {
  20501. defaultLinkFn(scope, element, attr);
  20502. }
  20503. };
  20504. }
  20505. ngAttributeAliasDirectives[normalized] = function() {
  20506. return {
  20507. restrict: 'A',
  20508. priority: 100,
  20509. link: linkFn
  20510. };
  20511. };
  20512. });
  20513. // aliased input attrs are evaluated
  20514. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  20515. ngAttributeAliasDirectives[ngAttr] = function() {
  20516. return {
  20517. priority: 100,
  20518. link: function(scope, element, attr) {
  20519. //special case ngPattern when a literal regular expression value
  20520. //is used as the expression (this way we don't have to watch anything).
  20521. if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
  20522. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  20523. if (match) {
  20524. attr.$set('ngPattern', new RegExp(match[1], match[2]));
  20525. return;
  20526. }
  20527. }
  20528. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  20529. attr.$set(ngAttr, value);
  20530. });
  20531. }
  20532. };
  20533. };
  20534. });
  20535. // ng-src, ng-srcset, ng-href are interpolated
  20536. forEach(['src', 'srcset', 'href'], function(attrName) {
  20537. var normalized = directiveNormalize('ng-' + attrName);
  20538. ngAttributeAliasDirectives[normalized] = function() {
  20539. return {
  20540. priority: 99, // it needs to run after the attributes are interpolated
  20541. link: function(scope, element, attr) {
  20542. var propName = attrName,
  20543. name = attrName;
  20544. if (attrName === 'href' &&
  20545. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  20546. name = 'xlinkHref';
  20547. attr.$attr[name] = 'xlink:href';
  20548. propName = null;
  20549. }
  20550. attr.$observe(normalized, function(value) {
  20551. if (!value) {
  20552. if (attrName === 'href') {
  20553. attr.$set(name, null);
  20554. }
  20555. return;
  20556. }
  20557. attr.$set(name, value);
  20558. // Support: IE 9-11 only
  20559. // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  20560. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  20561. // to set the property as well to achieve the desired effect.
  20562. // We use attr[attrName] value since $set can sanitize the url.
  20563. if (msie && propName) element.prop(propName, attr[name]);
  20564. });
  20565. }
  20566. };
  20567. };
  20568. });
  20569. /* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS
  20570. */
  20571. var nullFormCtrl = {
  20572. $addControl: noop,
  20573. $$renameControl: nullFormRenameControl,
  20574. $removeControl: noop,
  20575. $setValidity: noop,
  20576. $setDirty: noop,
  20577. $setPristine: noop,
  20578. $setSubmitted: noop
  20579. },
  20580. PENDING_CLASS = 'ng-pending',
  20581. SUBMITTED_CLASS = 'ng-submitted';
  20582. function nullFormRenameControl(control, name) {
  20583. control.$name = name;
  20584. }
  20585. /**
  20586. * @ngdoc type
  20587. * @name form.FormController
  20588. *
  20589. * @property {boolean} $pristine True if user has not interacted with the form yet.
  20590. * @property {boolean} $dirty True if user has already interacted with the form.
  20591. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  20592. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  20593. * @property {boolean} $pending True if at least one containing control or form is pending.
  20594. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  20595. *
  20596. * @property {Object} $error Is an object hash, containing references to controls or
  20597. * forms with failing validators, where:
  20598. *
  20599. * - keys are validation tokens (error names),
  20600. * - values are arrays of controls or forms that have a failing validator for given error name.
  20601. *
  20602. * Built-in validation tokens:
  20603. *
  20604. * - `email`
  20605. * - `max`
  20606. * - `maxlength`
  20607. * - `min`
  20608. * - `minlength`
  20609. * - `number`
  20610. * - `pattern`
  20611. * - `required`
  20612. * - `url`
  20613. * - `date`
  20614. * - `datetimelocal`
  20615. * - `time`
  20616. * - `week`
  20617. * - `month`
  20618. *
  20619. * @description
  20620. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  20621. * such as being valid/invalid or dirty/pristine.
  20622. *
  20623. * Each {@link ng.directive:form form} directive creates an instance
  20624. * of `FormController`.
  20625. *
  20626. */
  20627. //asks for $scope to fool the BC controller module
  20628. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  20629. function FormController($element, $attrs, $scope, $animate, $interpolate) {
  20630. this.$$controls = [];
  20631. // init state
  20632. this.$error = {};
  20633. this.$$success = {};
  20634. this.$pending = undefined;
  20635. this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);
  20636. this.$dirty = false;
  20637. this.$pristine = true;
  20638. this.$valid = true;
  20639. this.$invalid = false;
  20640. this.$submitted = false;
  20641. this.$$parentForm = nullFormCtrl;
  20642. this.$$element = $element;
  20643. this.$$animate = $animate;
  20644. setupValidity(this);
  20645. }
  20646. FormController.prototype = {
  20647. /**
  20648. * @ngdoc method
  20649. * @name form.FormController#$rollbackViewValue
  20650. *
  20651. * @description
  20652. * Rollback all form controls pending updates to the `$modelValue`.
  20653. *
  20654. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20655. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  20656. * a form that uses `ng-model-options` to pend updates.
  20657. */
  20658. $rollbackViewValue: function() {
  20659. forEach(this.$$controls, function(control) {
  20660. control.$rollbackViewValue();
  20661. });
  20662. },
  20663. /**
  20664. * @ngdoc method
  20665. * @name form.FormController#$commitViewValue
  20666. *
  20667. * @description
  20668. * Commit all form controls pending updates to the `$modelValue`.
  20669. *
  20670. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20671. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  20672. * usually handles calling this in response to input events.
  20673. */
  20674. $commitViewValue: function() {
  20675. forEach(this.$$controls, function(control) {
  20676. control.$commitViewValue();
  20677. });
  20678. },
  20679. /**
  20680. * @ngdoc method
  20681. * @name form.FormController#$addControl
  20682. * @param {object} control control object, either a {@link form.FormController} or an
  20683. * {@link ngModel.NgModelController}
  20684. *
  20685. * @description
  20686. * Register a control with the form. Input elements using ngModelController do this automatically
  20687. * when they are linked.
  20688. *
  20689. * Note that the current state of the control will not be reflected on the new parent form. This
  20690. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  20691. * state.
  20692. *
  20693. * However, if the method is used programmatically, for example by adding dynamically created controls,
  20694. * or controls that have been previously removed without destroying their corresponding DOM element,
  20695. * it's the developers responsibility to make sure the current state propagates to the parent form.
  20696. *
  20697. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  20698. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  20699. */
  20700. $addControl: function(control) {
  20701. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  20702. // and not added to the scope. Now we throw an error.
  20703. assertNotHasOwnProperty(control.$name, 'input');
  20704. this.$$controls.push(control);
  20705. if (control.$name) {
  20706. this[control.$name] = control;
  20707. }
  20708. control.$$parentForm = this;
  20709. },
  20710. // Private API: rename a form control
  20711. $$renameControl: function(control, newName) {
  20712. var oldName = control.$name;
  20713. if (this[oldName] === control) {
  20714. delete this[oldName];
  20715. }
  20716. this[newName] = control;
  20717. control.$name = newName;
  20718. },
  20719. /**
  20720. * @ngdoc method
  20721. * @name form.FormController#$removeControl
  20722. * @param {object} control control object, either a {@link form.FormController} or an
  20723. * {@link ngModel.NgModelController}
  20724. *
  20725. * @description
  20726. * Deregister a control from the form.
  20727. *
  20728. * Input elements using ngModelController do this automatically when they are destroyed.
  20729. *
  20730. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  20731. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  20732. * different from case to case. For example, removing the only `$dirty` control from a form may or
  20733. * may not mean that the form is still `$dirty`.
  20734. */
  20735. $removeControl: function(control) {
  20736. if (control.$name && this[control.$name] === control) {
  20737. delete this[control.$name];
  20738. }
  20739. forEach(this.$pending, function(value, name) {
  20740. // eslint-disable-next-line no-invalid-this
  20741. this.$setValidity(name, null, control);
  20742. }, this);
  20743. forEach(this.$error, function(value, name) {
  20744. // eslint-disable-next-line no-invalid-this
  20745. this.$setValidity(name, null, control);
  20746. }, this);
  20747. forEach(this.$$success, function(value, name) {
  20748. // eslint-disable-next-line no-invalid-this
  20749. this.$setValidity(name, null, control);
  20750. }, this);
  20751. arrayRemove(this.$$controls, control);
  20752. control.$$parentForm = nullFormCtrl;
  20753. },
  20754. /**
  20755. * @ngdoc method
  20756. * @name form.FormController#$setDirty
  20757. *
  20758. * @description
  20759. * Sets the form to a dirty state.
  20760. *
  20761. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  20762. * state (ng-dirty class). This method will also propagate to parent forms.
  20763. */
  20764. $setDirty: function() {
  20765. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  20766. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  20767. this.$dirty = true;
  20768. this.$pristine = false;
  20769. this.$$parentForm.$setDirty();
  20770. },
  20771. /**
  20772. * @ngdoc method
  20773. * @name form.FormController#$setPristine
  20774. *
  20775. * @description
  20776. * Sets the form to its pristine state.
  20777. *
  20778. * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
  20779. * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
  20780. * state to false.
  20781. *
  20782. * This method will also propagate to all the controls contained in this form.
  20783. *
  20784. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  20785. * saving or resetting it.
  20786. */
  20787. $setPristine: function() {
  20788. this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  20789. this.$dirty = false;
  20790. this.$pristine = true;
  20791. this.$submitted = false;
  20792. forEach(this.$$controls, function(control) {
  20793. control.$setPristine();
  20794. });
  20795. },
  20796. /**
  20797. * @ngdoc method
  20798. * @name form.FormController#$setUntouched
  20799. *
  20800. * @description
  20801. * Sets the form to its untouched state.
  20802. *
  20803. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  20804. * untouched state (ng-untouched class).
  20805. *
  20806. * Setting a form controls back to their untouched state is often useful when setting the form
  20807. * back to its pristine state.
  20808. */
  20809. $setUntouched: function() {
  20810. forEach(this.$$controls, function(control) {
  20811. control.$setUntouched();
  20812. });
  20813. },
  20814. /**
  20815. * @ngdoc method
  20816. * @name form.FormController#$setSubmitted
  20817. *
  20818. * @description
  20819. * Sets the form to its submitted state.
  20820. */
  20821. $setSubmitted: function() {
  20822. this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);
  20823. this.$submitted = true;
  20824. this.$$parentForm.$setSubmitted();
  20825. }
  20826. };
  20827. /**
  20828. * @ngdoc method
  20829. * @name form.FormController#$setValidity
  20830. *
  20831. * @description
  20832. * Sets the validity of a form control.
  20833. *
  20834. * This method will also propagate to parent forms.
  20835. */
  20836. addSetValidityMethod({
  20837. clazz: FormController,
  20838. set: function(object, property, controller) {
  20839. var list = object[property];
  20840. if (!list) {
  20841. object[property] = [controller];
  20842. } else {
  20843. var index = list.indexOf(controller);
  20844. if (index === -1) {
  20845. list.push(controller);
  20846. }
  20847. }
  20848. },
  20849. unset: function(object, property, controller) {
  20850. var list = object[property];
  20851. if (!list) {
  20852. return;
  20853. }
  20854. arrayRemove(list, controller);
  20855. if (list.length === 0) {
  20856. delete object[property];
  20857. }
  20858. }
  20859. });
  20860. /**
  20861. * @ngdoc directive
  20862. * @name ngForm
  20863. * @restrict EAC
  20864. *
  20865. * @description
  20866. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  20867. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  20868. * sub-group of controls needs to be determined.
  20869. *
  20870. * Note: the purpose of `ngForm` is to group controls,
  20871. * but not to be a replacement for the `<form>` tag with all of its capabilities
  20872. * (e.g. posting to the server, ...).
  20873. *
  20874. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  20875. * related scope, under this name.
  20876. *
  20877. */
  20878. /**
  20879. * @ngdoc directive
  20880. * @name form
  20881. * @restrict E
  20882. *
  20883. * @description
  20884. * Directive that instantiates
  20885. * {@link form.FormController FormController}.
  20886. *
  20887. * If the `name` attribute is specified, the form controller is published onto the current scope under
  20888. * this name.
  20889. *
  20890. * # Alias: {@link ng.directive:ngForm `ngForm`}
  20891. *
  20892. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  20893. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  20894. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  20895. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  20896. * of controls needs to be determined.
  20897. *
  20898. * # CSS classes
  20899. * - `ng-valid` is set if the form is valid.
  20900. * - `ng-invalid` is set if the form is invalid.
  20901. * - `ng-pending` is set if the form is pending.
  20902. * - `ng-pristine` is set if the form is pristine.
  20903. * - `ng-dirty` is set if the form is dirty.
  20904. * - `ng-submitted` is set if the form was submitted.
  20905. *
  20906. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  20907. *
  20908. *
  20909. * # Submitting a form and preventing the default action
  20910. *
  20911. * Since the role of forms in client-side Angular applications is different than in classical
  20912. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  20913. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  20914. * to handle the form submission in an application-specific way.
  20915. *
  20916. * For this reason, Angular prevents the default action (form submission to the server) unless the
  20917. * `<form>` element has an `action` attribute specified.
  20918. *
  20919. * You can use one of the following two ways to specify what javascript method should be called when
  20920. * a form is submitted:
  20921. *
  20922. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  20923. * - {@link ng.directive:ngClick ngClick} directive on the first
  20924. * button or input field of type submit (input[type=submit])
  20925. *
  20926. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  20927. * or {@link ng.directive:ngClick ngClick} directives.
  20928. * This is because of the following form submission rules in the HTML specification:
  20929. *
  20930. * - If a form has only one input field then hitting enter in this field triggers form submit
  20931. * (`ngSubmit`)
  20932. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  20933. * doesn't trigger submit
  20934. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  20935. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  20936. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  20937. *
  20938. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  20939. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  20940. * to have access to the updated model.
  20941. *
  20942. * ## Animation Hooks
  20943. *
  20944. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  20945. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  20946. * other validations that are performed within the form. Animations in ngForm are similar to how
  20947. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  20948. * as JS animations.
  20949. *
  20950. * The following example shows a simple way to utilize CSS transitions to style a form element
  20951. * that has been rendered as invalid after it has been validated:
  20952. *
  20953. * <pre>
  20954. * //be sure to include ngAnimate as a module to hook into more
  20955. * //advanced animations
  20956. * .my-form {
  20957. * transition:0.5s linear all;
  20958. * background: white;
  20959. * }
  20960. * .my-form.ng-invalid {
  20961. * background: red;
  20962. * color:white;
  20963. * }
  20964. * </pre>
  20965. *
  20966. * @example
  20967. <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  20968. <file name="index.html">
  20969. <script>
  20970. angular.module('formExample', [])
  20971. .controller('FormController', ['$scope', function($scope) {
  20972. $scope.userType = 'guest';
  20973. }]);
  20974. </script>
  20975. <style>
  20976. .my-form {
  20977. transition:all linear 0.5s;
  20978. background: transparent;
  20979. }
  20980. .my-form.ng-invalid {
  20981. background: red;
  20982. }
  20983. </style>
  20984. <form name="myForm" ng-controller="FormController" class="my-form">
  20985. userType: <input name="input" ng-model="userType" required>
  20986. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  20987. <code>userType = {{userType}}</code><br>
  20988. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  20989. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  20990. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  20991. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  20992. </form>
  20993. </file>
  20994. <file name="protractor.js" type="protractor">
  20995. it('should initialize to model', function() {
  20996. var userType = element(by.binding('userType'));
  20997. var valid = element(by.binding('myForm.input.$valid'));
  20998. expect(userType.getText()).toContain('guest');
  20999. expect(valid.getText()).toContain('true');
  21000. });
  21001. it('should be invalid if empty', function() {
  21002. var userType = element(by.binding('userType'));
  21003. var valid = element(by.binding('myForm.input.$valid'));
  21004. var userInput = element(by.model('userType'));
  21005. userInput.clear();
  21006. userInput.sendKeys('');
  21007. expect(userType.getText()).toEqual('userType =');
  21008. expect(valid.getText()).toContain('false');
  21009. });
  21010. </file>
  21011. </example>
  21012. *
  21013. * @param {string=} name Name of the form. If specified, the form controller will be published into
  21014. * related scope, under this name.
  21015. */
  21016. var formDirectiveFactory = function(isNgForm) {
  21017. return ['$timeout', '$parse', function($timeout, $parse) {
  21018. var formDirective = {
  21019. name: 'form',
  21020. restrict: isNgForm ? 'EAC' : 'E',
  21021. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  21022. controller: FormController,
  21023. compile: function ngFormCompile(formElement, attr) {
  21024. // Setup initial state of the control
  21025. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  21026. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  21027. return {
  21028. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  21029. var controller = ctrls[0];
  21030. // if `action` attr is not present on the form, prevent the default action (submission)
  21031. if (!('action' in attr)) {
  21032. // we can't use jq events because if a form is destroyed during submission the default
  21033. // action is not prevented. see #1238
  21034. //
  21035. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  21036. // page reload if the form was destroyed by submission of the form via a click handler
  21037. // on a button in the form. Looks like an IE9 specific bug.
  21038. var handleFormSubmission = function(event) {
  21039. scope.$apply(function() {
  21040. controller.$commitViewValue();
  21041. controller.$setSubmitted();
  21042. });
  21043. event.preventDefault();
  21044. };
  21045. formElement[0].addEventListener('submit', handleFormSubmission);
  21046. // unregister the preventDefault listener so that we don't not leak memory but in a
  21047. // way that will achieve the prevention of the default action.
  21048. formElement.on('$destroy', function() {
  21049. $timeout(function() {
  21050. formElement[0].removeEventListener('submit', handleFormSubmission);
  21051. }, 0, false);
  21052. });
  21053. }
  21054. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  21055. parentFormCtrl.$addControl(controller);
  21056. var setter = nameAttr ? getSetter(controller.$name) : noop;
  21057. if (nameAttr) {
  21058. setter(scope, controller);
  21059. attr.$observe(nameAttr, function(newValue) {
  21060. if (controller.$name === newValue) return;
  21061. setter(scope, undefined);
  21062. controller.$$parentForm.$$renameControl(controller, newValue);
  21063. setter = getSetter(controller.$name);
  21064. setter(scope, controller);
  21065. });
  21066. }
  21067. formElement.on('$destroy', function() {
  21068. controller.$$parentForm.$removeControl(controller);
  21069. setter(scope, undefined);
  21070. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  21071. });
  21072. }
  21073. };
  21074. }
  21075. };
  21076. return formDirective;
  21077. function getSetter(expression) {
  21078. if (expression === '') {
  21079. //create an assignable expression, so forms with an empty name can be renamed later
  21080. return $parse('this[""]').assign;
  21081. }
  21082. return $parse(expression).assign || noop;
  21083. }
  21084. }];
  21085. };
  21086. var formDirective = formDirectiveFactory();
  21087. var ngFormDirective = formDirectiveFactory(true);
  21088. // helper methods
  21089. function setupValidity(instance) {
  21090. instance.$$classCache = {};
  21091. instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));
  21092. }
  21093. function addSetValidityMethod(context) {
  21094. var clazz = context.clazz,
  21095. set = context.set,
  21096. unset = context.unset;
  21097. clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {
  21098. if (isUndefined(state)) {
  21099. createAndSet(this, '$pending', validationErrorKey, controller);
  21100. } else {
  21101. unsetAndCleanup(this, '$pending', validationErrorKey, controller);
  21102. }
  21103. if (!isBoolean(state)) {
  21104. unset(this.$error, validationErrorKey, controller);
  21105. unset(this.$$success, validationErrorKey, controller);
  21106. } else {
  21107. if (state) {
  21108. unset(this.$error, validationErrorKey, controller);
  21109. set(this.$$success, validationErrorKey, controller);
  21110. } else {
  21111. set(this.$error, validationErrorKey, controller);
  21112. unset(this.$$success, validationErrorKey, controller);
  21113. }
  21114. }
  21115. if (this.$pending) {
  21116. cachedToggleClass(this, PENDING_CLASS, true);
  21117. this.$valid = this.$invalid = undefined;
  21118. toggleValidationCss(this, '', null);
  21119. } else {
  21120. cachedToggleClass(this, PENDING_CLASS, false);
  21121. this.$valid = isObjectEmpty(this.$error);
  21122. this.$invalid = !this.$valid;
  21123. toggleValidationCss(this, '', this.$valid);
  21124. }
  21125. // re-read the state as the set/unset methods could have
  21126. // combined state in this.$error[validationError] (used for forms),
  21127. // where setting/unsetting only increments/decrements the value,
  21128. // and does not replace it.
  21129. var combinedState;
  21130. if (this.$pending && this.$pending[validationErrorKey]) {
  21131. combinedState = undefined;
  21132. } else if (this.$error[validationErrorKey]) {
  21133. combinedState = false;
  21134. } else if (this.$$success[validationErrorKey]) {
  21135. combinedState = true;
  21136. } else {
  21137. combinedState = null;
  21138. }
  21139. toggleValidationCss(this, validationErrorKey, combinedState);
  21140. this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);
  21141. };
  21142. function createAndSet(ctrl, name, value, controller) {
  21143. if (!ctrl[name]) {
  21144. ctrl[name] = {};
  21145. }
  21146. set(ctrl[name], value, controller);
  21147. }
  21148. function unsetAndCleanup(ctrl, name, value, controller) {
  21149. if (ctrl[name]) {
  21150. unset(ctrl[name], value, controller);
  21151. }
  21152. if (isObjectEmpty(ctrl[name])) {
  21153. ctrl[name] = undefined;
  21154. }
  21155. }
  21156. function cachedToggleClass(ctrl, className, switchValue) {
  21157. if (switchValue && !ctrl.$$classCache[className]) {
  21158. ctrl.$$animate.addClass(ctrl.$$element, className);
  21159. ctrl.$$classCache[className] = true;
  21160. } else if (!switchValue && ctrl.$$classCache[className]) {
  21161. ctrl.$$animate.removeClass(ctrl.$$element, className);
  21162. ctrl.$$classCache[className] = false;
  21163. }
  21164. }
  21165. function toggleValidationCss(ctrl, validationErrorKey, isValid) {
  21166. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  21167. cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);
  21168. cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);
  21169. }
  21170. }
  21171. function isObjectEmpty(obj) {
  21172. if (obj) {
  21173. for (var prop in obj) {
  21174. if (obj.hasOwnProperty(prop)) {
  21175. return false;
  21176. }
  21177. }
  21178. }
  21179. return true;
  21180. }
  21181. /* global
  21182. VALID_CLASS: false,
  21183. INVALID_CLASS: false,
  21184. PRISTINE_CLASS: false,
  21185. DIRTY_CLASS: false,
  21186. ngModelMinErr: false
  21187. */
  21188. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  21189. 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)$/;
  21190. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  21191. // Note: We are being more lenient, because browsers are too.
  21192. // 1. Scheme
  21193. // 2. Slashes
  21194. // 3. Username
  21195. // 4. Password
  21196. // 5. Hostname
  21197. // 6. Port
  21198. // 7. Path
  21199. // 8. Query
  21200. // 9. Fragment
  21201. // 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
  21202. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  21203. // eslint-disable-next-line max-len
  21204. 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])?)*$/;
  21205. var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  21206. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  21207. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21208. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  21209. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  21210. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21211. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  21212. var PARTIAL_VALIDATION_TYPES = createMap();
  21213. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  21214. PARTIAL_VALIDATION_TYPES[type] = true;
  21215. });
  21216. var inputType = {
  21217. /**
  21218. * @ngdoc input
  21219. * @name input[text]
  21220. *
  21221. * @description
  21222. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  21223. *
  21224. *
  21225. * @param {string} ngModel Assignable angular expression to data-bind to.
  21226. * @param {string=} name Property name of the form under which the control is published.
  21227. * @param {string=} required Adds `required` validation error key if the value is not entered.
  21228. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21229. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21230. * `required` when you want to data-bind to the `required` attribute.
  21231. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21232. * minlength.
  21233. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21234. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21235. * any length.
  21236. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21237. * that contains the regular expression body that will be converted to a regular expression
  21238. * as in the ngPattern directive.
  21239. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21240. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21241. * If the expression evaluates to a RegExp object, then this is used directly.
  21242. * If the expression evaluates to a string, then it will be converted to a RegExp
  21243. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21244. * `new RegExp('^abc$')`.<br />
  21245. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21246. * start at the index of the last search's match, thus not taking the whole input value into
  21247. * account.
  21248. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21249. * interaction with the input element.
  21250. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21251. * This parameter is ignored for input[type=password] controls, which will never trim the
  21252. * input.
  21253. *
  21254. * @example
  21255. <example name="text-input-directive" module="textInputExample">
  21256. <file name="index.html">
  21257. <script>
  21258. angular.module('textInputExample', [])
  21259. .controller('ExampleController', ['$scope', function($scope) {
  21260. $scope.example = {
  21261. text: 'guest',
  21262. word: /^\s*\w*\s*$/
  21263. };
  21264. }]);
  21265. </script>
  21266. <form name="myForm" ng-controller="ExampleController">
  21267. <label>Single word:
  21268. <input type="text" name="input" ng-model="example.text"
  21269. ng-pattern="example.word" required ng-trim="false">
  21270. </label>
  21271. <div role="alert">
  21272. <span class="error" ng-show="myForm.input.$error.required">
  21273. Required!</span>
  21274. <span class="error" ng-show="myForm.input.$error.pattern">
  21275. Single word only!</span>
  21276. </div>
  21277. <code>text = {{example.text}}</code><br/>
  21278. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  21279. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  21280. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  21281. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  21282. </form>
  21283. </file>
  21284. <file name="protractor.js" type="protractor">
  21285. var text = element(by.binding('example.text'));
  21286. var valid = element(by.binding('myForm.input.$valid'));
  21287. var input = element(by.model('example.text'));
  21288. it('should initialize to model', function() {
  21289. expect(text.getText()).toContain('guest');
  21290. expect(valid.getText()).toContain('true');
  21291. });
  21292. it('should be invalid if empty', function() {
  21293. input.clear();
  21294. input.sendKeys('');
  21295. expect(text.getText()).toEqual('text =');
  21296. expect(valid.getText()).toContain('false');
  21297. });
  21298. it('should be invalid if multi word', function() {
  21299. input.clear();
  21300. input.sendKeys('hello world');
  21301. expect(valid.getText()).toContain('false');
  21302. });
  21303. </file>
  21304. </example>
  21305. */
  21306. 'text': textInputType,
  21307. /**
  21308. * @ngdoc input
  21309. * @name input[date]
  21310. *
  21311. * @description
  21312. * Input with date validation and transformation. In browsers that do not yet support
  21313. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  21314. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  21315. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  21316. * expected input format via a placeholder or label.
  21317. *
  21318. * The model must always be a Date object, otherwise Angular will throw an error.
  21319. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21320. *
  21321. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21322. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21323. *
  21324. * @param {string} ngModel Assignable angular expression to data-bind to.
  21325. * @param {string=} name Property name of the form under which the control is published.
  21326. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  21327. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21328. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  21329. * constraint validation.
  21330. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  21331. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21332. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  21333. * constraint validation.
  21334. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  21335. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21336. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  21337. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21338. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21339. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21340. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21341. * `required` when you want to data-bind to the `required` attribute.
  21342. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21343. * interaction with the input element.
  21344. *
  21345. * @example
  21346. <example name="date-input-directive" module="dateInputExample">
  21347. <file name="index.html">
  21348. <script>
  21349. angular.module('dateInputExample', [])
  21350. .controller('DateController', ['$scope', function($scope) {
  21351. $scope.example = {
  21352. value: new Date(2013, 9, 22)
  21353. };
  21354. }]);
  21355. </script>
  21356. <form name="myForm" ng-controller="DateController as dateCtrl">
  21357. <label for="exampleInput">Pick a date in 2013:</label>
  21358. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  21359. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  21360. <div role="alert">
  21361. <span class="error" ng-show="myForm.input.$error.required">
  21362. Required!</span>
  21363. <span class="error" ng-show="myForm.input.$error.date">
  21364. Not a valid date!</span>
  21365. </div>
  21366. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  21367. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21368. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21369. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21370. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21371. </form>
  21372. </file>
  21373. <file name="protractor.js" type="protractor">
  21374. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  21375. var valid = element(by.binding('myForm.input.$valid'));
  21376. // currently protractor/webdriver does not support
  21377. // sending keys to all known HTML5 input controls
  21378. // for various browsers (see https://github.com/angular/protractor/issues/562).
  21379. function setInput(val) {
  21380. // set the value of the element and force validation.
  21381. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21382. "ipt.value = '" + val + "';" +
  21383. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21384. browser.executeScript(scr);
  21385. }
  21386. it('should initialize to model', function() {
  21387. expect(value.getText()).toContain('2013-10-22');
  21388. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21389. });
  21390. it('should be invalid if empty', function() {
  21391. setInput('');
  21392. expect(value.getText()).toEqual('value =');
  21393. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21394. });
  21395. it('should be invalid if over max', function() {
  21396. setInput('2015-01-01');
  21397. expect(value.getText()).toContain('');
  21398. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21399. });
  21400. </file>
  21401. </example>
  21402. */
  21403. 'date': createDateInputType('date', DATE_REGEXP,
  21404. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  21405. 'yyyy-MM-dd'),
  21406. /**
  21407. * @ngdoc input
  21408. * @name input[datetime-local]
  21409. *
  21410. * @description
  21411. * Input with datetime validation and transformation. In browsers that do not yet support
  21412. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21413. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  21414. *
  21415. * The model must always be a Date object, otherwise Angular will throw an error.
  21416. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21417. *
  21418. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21419. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21420. *
  21421. * @param {string} ngModel Assignable angular expression to data-bind to.
  21422. * @param {string=} name Property name of the form under which the control is published.
  21423. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21424. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21425. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21426. * Note that `min` will also add native HTML5 constraint validation.
  21427. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21428. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21429. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21430. * Note that `max` will also add native HTML5 constraint validation.
  21431. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  21432. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21433. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  21434. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21435. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21436. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21437. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21438. * `required` when you want to data-bind to the `required` attribute.
  21439. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21440. * interaction with the input element.
  21441. *
  21442. * @example
  21443. <example name="datetimelocal-input-directive" module="dateExample">
  21444. <file name="index.html">
  21445. <script>
  21446. angular.module('dateExample', [])
  21447. .controller('DateController', ['$scope', function($scope) {
  21448. $scope.example = {
  21449. value: new Date(2010, 11, 28, 14, 57)
  21450. };
  21451. }]);
  21452. </script>
  21453. <form name="myForm" ng-controller="DateController as dateCtrl">
  21454. <label for="exampleInput">Pick a date between in 2013:</label>
  21455. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  21456. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  21457. <div role="alert">
  21458. <span class="error" ng-show="myForm.input.$error.required">
  21459. Required!</span>
  21460. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  21461. Not a valid date!</span>
  21462. </div>
  21463. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  21464. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21465. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21466. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21467. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21468. </form>
  21469. </file>
  21470. <file name="protractor.js" type="protractor">
  21471. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  21472. var valid = element(by.binding('myForm.input.$valid'));
  21473. // currently protractor/webdriver does not support
  21474. // sending keys to all known HTML5 input controls
  21475. // for various browsers (https://github.com/angular/protractor/issues/562).
  21476. function setInput(val) {
  21477. // set the value of the element and force validation.
  21478. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21479. "ipt.value = '" + val + "';" +
  21480. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21481. browser.executeScript(scr);
  21482. }
  21483. it('should initialize to model', function() {
  21484. expect(value.getText()).toContain('2010-12-28T14:57:00');
  21485. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21486. });
  21487. it('should be invalid if empty', function() {
  21488. setInput('');
  21489. expect(value.getText()).toEqual('value =');
  21490. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21491. });
  21492. it('should be invalid if over max', function() {
  21493. setInput('2015-01-01T23:59:00');
  21494. expect(value.getText()).toContain('');
  21495. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21496. });
  21497. </file>
  21498. </example>
  21499. */
  21500. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  21501. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  21502. 'yyyy-MM-ddTHH:mm:ss.sss'),
  21503. /**
  21504. * @ngdoc input
  21505. * @name input[time]
  21506. *
  21507. * @description
  21508. * Input with time validation and transformation. In browsers that do not yet support
  21509. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21510. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  21511. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  21512. *
  21513. * The model must always be a Date object, otherwise Angular will throw an error.
  21514. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21515. *
  21516. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21517. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21518. *
  21519. * @param {string} ngModel Assignable angular expression to data-bind to.
  21520. * @param {string=} name Property name of the form under which the control is published.
  21521. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21522. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21523. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  21524. * native HTML5 constraint validation.
  21525. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21526. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21527. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  21528. * native HTML5 constraint validation.
  21529. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  21530. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21531. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  21532. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21533. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21534. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21535. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21536. * `required` when you want to data-bind to the `required` attribute.
  21537. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21538. * interaction with the input element.
  21539. *
  21540. * @example
  21541. <example name="time-input-directive" module="timeExample">
  21542. <file name="index.html">
  21543. <script>
  21544. angular.module('timeExample', [])
  21545. .controller('DateController', ['$scope', function($scope) {
  21546. $scope.example = {
  21547. value: new Date(1970, 0, 1, 14, 57, 0)
  21548. };
  21549. }]);
  21550. </script>
  21551. <form name="myForm" ng-controller="DateController as dateCtrl">
  21552. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  21553. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  21554. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  21555. <div role="alert">
  21556. <span class="error" ng-show="myForm.input.$error.required">
  21557. Required!</span>
  21558. <span class="error" ng-show="myForm.input.$error.time">
  21559. Not a valid date!</span>
  21560. </div>
  21561. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  21562. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21563. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21564. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21565. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21566. </form>
  21567. </file>
  21568. <file name="protractor.js" type="protractor">
  21569. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  21570. var valid = element(by.binding('myForm.input.$valid'));
  21571. // currently protractor/webdriver does not support
  21572. // sending keys to all known HTML5 input controls
  21573. // for various browsers (https://github.com/angular/protractor/issues/562).
  21574. function setInput(val) {
  21575. // set the value of the element and force validation.
  21576. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21577. "ipt.value = '" + val + "';" +
  21578. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21579. browser.executeScript(scr);
  21580. }
  21581. it('should initialize to model', function() {
  21582. expect(value.getText()).toContain('14:57:00');
  21583. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21584. });
  21585. it('should be invalid if empty', function() {
  21586. setInput('');
  21587. expect(value.getText()).toEqual('value =');
  21588. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21589. });
  21590. it('should be invalid if over max', function() {
  21591. setInput('23:59:00');
  21592. expect(value.getText()).toContain('');
  21593. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21594. });
  21595. </file>
  21596. </example>
  21597. */
  21598. 'time': createDateInputType('time', TIME_REGEXP,
  21599. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  21600. 'HH:mm:ss.sss'),
  21601. /**
  21602. * @ngdoc input
  21603. * @name input[week]
  21604. *
  21605. * @description
  21606. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  21607. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21608. * week format (yyyy-W##), for example: `2013-W02`.
  21609. *
  21610. * The model must always be a Date object, otherwise Angular will throw an error.
  21611. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21612. *
  21613. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21614. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21615. *
  21616. * @param {string} ngModel Assignable angular expression to data-bind to.
  21617. * @param {string=} name Property name of the form under which the control is published.
  21618. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21619. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21620. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  21621. * native HTML5 constraint validation.
  21622. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21623. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21624. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  21625. * native HTML5 constraint validation.
  21626. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21627. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21628. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21629. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21630. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21631. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21632. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21633. * `required` when you want to data-bind to the `required` attribute.
  21634. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21635. * interaction with the input element.
  21636. *
  21637. * @example
  21638. <example name="week-input-directive" module="weekExample">
  21639. <file name="index.html">
  21640. <script>
  21641. angular.module('weekExample', [])
  21642. .controller('DateController', ['$scope', function($scope) {
  21643. $scope.example = {
  21644. value: new Date(2013, 0, 3)
  21645. };
  21646. }]);
  21647. </script>
  21648. <form name="myForm" ng-controller="DateController as dateCtrl">
  21649. <label>Pick a date between in 2013:
  21650. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  21651. placeholder="YYYY-W##" min="2012-W32"
  21652. max="2013-W52" required />
  21653. </label>
  21654. <div role="alert">
  21655. <span class="error" ng-show="myForm.input.$error.required">
  21656. Required!</span>
  21657. <span class="error" ng-show="myForm.input.$error.week">
  21658. Not a valid date!</span>
  21659. </div>
  21660. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  21661. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21662. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21663. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21664. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21665. </form>
  21666. </file>
  21667. <file name="protractor.js" type="protractor">
  21668. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  21669. var valid = element(by.binding('myForm.input.$valid'));
  21670. // currently protractor/webdriver does not support
  21671. // sending keys to all known HTML5 input controls
  21672. // for various browsers (https://github.com/angular/protractor/issues/562).
  21673. function setInput(val) {
  21674. // set the value of the element and force validation.
  21675. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21676. "ipt.value = '" + val + "';" +
  21677. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21678. browser.executeScript(scr);
  21679. }
  21680. it('should initialize to model', function() {
  21681. expect(value.getText()).toContain('2013-W01');
  21682. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21683. });
  21684. it('should be invalid if empty', function() {
  21685. setInput('');
  21686. expect(value.getText()).toEqual('value =');
  21687. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21688. });
  21689. it('should be invalid if over max', function() {
  21690. setInput('2015-W01');
  21691. expect(value.getText()).toContain('');
  21692. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21693. });
  21694. </file>
  21695. </example>
  21696. */
  21697. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  21698. /**
  21699. * @ngdoc input
  21700. * @name input[month]
  21701. *
  21702. * @description
  21703. * Input with month validation and transformation. In browsers that do not yet support
  21704. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21705. * month format (yyyy-MM), for example: `2009-01`.
  21706. *
  21707. * The model must always be a Date object, otherwise Angular will throw an error.
  21708. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21709. * If the model is not set to the first of the month, the next view to model update will set it
  21710. * to the first of the month.
  21711. *
  21712. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21713. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21714. *
  21715. * @param {string} ngModel Assignable angular expression to data-bind to.
  21716. * @param {string=} name Property name of the form under which the control is published.
  21717. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21718. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21719. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  21720. * native HTML5 constraint validation.
  21721. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21722. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21723. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  21724. * native HTML5 constraint validation.
  21725. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21726. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21727. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21728. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21729. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21730. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21731. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21732. * `required` when you want to data-bind to the `required` attribute.
  21733. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21734. * interaction with the input element.
  21735. *
  21736. * @example
  21737. <example name="month-input-directive" module="monthExample">
  21738. <file name="index.html">
  21739. <script>
  21740. angular.module('monthExample', [])
  21741. .controller('DateController', ['$scope', function($scope) {
  21742. $scope.example = {
  21743. value: new Date(2013, 9, 1)
  21744. };
  21745. }]);
  21746. </script>
  21747. <form name="myForm" ng-controller="DateController as dateCtrl">
  21748. <label for="exampleInput">Pick a month in 2013:</label>
  21749. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  21750. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  21751. <div role="alert">
  21752. <span class="error" ng-show="myForm.input.$error.required">
  21753. Required!</span>
  21754. <span class="error" ng-show="myForm.input.$error.month">
  21755. Not a valid month!</span>
  21756. </div>
  21757. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  21758. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21759. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21760. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21761. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21762. </form>
  21763. </file>
  21764. <file name="protractor.js" type="protractor">
  21765. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  21766. var valid = element(by.binding('myForm.input.$valid'));
  21767. // currently protractor/webdriver does not support
  21768. // sending keys to all known HTML5 input controls
  21769. // for various browsers (https://github.com/angular/protractor/issues/562).
  21770. function setInput(val) {
  21771. // set the value of the element and force validation.
  21772. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21773. "ipt.value = '" + val + "';" +
  21774. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21775. browser.executeScript(scr);
  21776. }
  21777. it('should initialize to model', function() {
  21778. expect(value.getText()).toContain('2013-10');
  21779. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21780. });
  21781. it('should be invalid if empty', function() {
  21782. setInput('');
  21783. expect(value.getText()).toEqual('value =');
  21784. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21785. });
  21786. it('should be invalid if over max', function() {
  21787. setInput('2015-01');
  21788. expect(value.getText()).toContain('');
  21789. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21790. });
  21791. </file>
  21792. </example>
  21793. */
  21794. 'month': createDateInputType('month', MONTH_REGEXP,
  21795. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  21796. 'yyyy-MM'),
  21797. /**
  21798. * @ngdoc input
  21799. * @name input[number]
  21800. *
  21801. * @description
  21802. * Text input with number validation and transformation. Sets the `number` validation
  21803. * error if not a valid number.
  21804. *
  21805. * <div class="alert alert-warning">
  21806. * The model must always be of type `number` otherwise Angular will throw an error.
  21807. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  21808. * error docs for more information and an example of how to convert your model if necessary.
  21809. * </div>
  21810. *
  21811. * ## Issues with HTML5 constraint validation
  21812. *
  21813. * In browsers that follow the
  21814. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  21815. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  21816. * If a non-number is entered in the input, the browser will report the value as an empty string,
  21817. * which means the view / model values in `ngModel` and subsequently the scope value
  21818. * will also be an empty string.
  21819. *
  21820. *
  21821. * @param {string} ngModel Assignable angular expression to data-bind to.
  21822. * @param {string=} name Property name of the form under which the control is published.
  21823. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21824. * Can be interpolated.
  21825. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21826. * Can be interpolated.
  21827. * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
  21828. * but does not trigger HTML5 native validation. Takes an expression.
  21829. * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
  21830. * but does not trigger HTML5 native validation. Takes an expression.
  21831. * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
  21832. * Can be interpolated.
  21833. * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,
  21834. * but does not trigger HTML5 native validation. Takes an expression.
  21835. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21836. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21837. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21838. * `required` when you want to data-bind to the `required` attribute.
  21839. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21840. * minlength.
  21841. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21842. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21843. * any length.
  21844. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21845. * that contains the regular expression body that will be converted to a regular expression
  21846. * as in the ngPattern directive.
  21847. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21848. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21849. * If the expression evaluates to a RegExp object, then this is used directly.
  21850. * If the expression evaluates to a string, then it will be converted to a RegExp
  21851. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21852. * `new RegExp('^abc$')`.<br />
  21853. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21854. * start at the index of the last search's match, thus not taking the whole input value into
  21855. * account.
  21856. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21857. * interaction with the input element.
  21858. *
  21859. * @example
  21860. <example name="number-input-directive" module="numberExample">
  21861. <file name="index.html">
  21862. <script>
  21863. angular.module('numberExample', [])
  21864. .controller('ExampleController', ['$scope', function($scope) {
  21865. $scope.example = {
  21866. value: 12
  21867. };
  21868. }]);
  21869. </script>
  21870. <form name="myForm" ng-controller="ExampleController">
  21871. <label>Number:
  21872. <input type="number" name="input" ng-model="example.value"
  21873. min="0" max="99" required>
  21874. </label>
  21875. <div role="alert">
  21876. <span class="error" ng-show="myForm.input.$error.required">
  21877. Required!</span>
  21878. <span class="error" ng-show="myForm.input.$error.number">
  21879. Not valid number!</span>
  21880. </div>
  21881. <tt>value = {{example.value}}</tt><br/>
  21882. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21883. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21884. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21885. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21886. </form>
  21887. </file>
  21888. <file name="protractor.js" type="protractor">
  21889. var value = element(by.binding('example.value'));
  21890. var valid = element(by.binding('myForm.input.$valid'));
  21891. var input = element(by.model('example.value'));
  21892. it('should initialize to model', function() {
  21893. expect(value.getText()).toContain('12');
  21894. expect(valid.getText()).toContain('true');
  21895. });
  21896. it('should be invalid if empty', function() {
  21897. input.clear();
  21898. input.sendKeys('');
  21899. expect(value.getText()).toEqual('value =');
  21900. expect(valid.getText()).toContain('false');
  21901. });
  21902. it('should be invalid if over max', function() {
  21903. input.clear();
  21904. input.sendKeys('123');
  21905. expect(value.getText()).toEqual('value =');
  21906. expect(valid.getText()).toContain('false');
  21907. });
  21908. </file>
  21909. </example>
  21910. */
  21911. 'number': numberInputType,
  21912. /**
  21913. * @ngdoc input
  21914. * @name input[url]
  21915. *
  21916. * @description
  21917. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  21918. * valid URL.
  21919. *
  21920. * <div class="alert alert-warning">
  21921. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  21922. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  21923. * the built-in validators (see the {@link guide/forms Forms guide})
  21924. * </div>
  21925. *
  21926. * @param {string} ngModel Assignable angular expression to data-bind to.
  21927. * @param {string=} name Property name of the form under which the control is published.
  21928. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21929. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21930. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21931. * `required` when you want to data-bind to the `required` attribute.
  21932. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21933. * minlength.
  21934. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21935. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21936. * any length.
  21937. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21938. * that contains the regular expression body that will be converted to a regular expression
  21939. * as in the ngPattern directive.
  21940. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21941. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21942. * If the expression evaluates to a RegExp object, then this is used directly.
  21943. * If the expression evaluates to a string, then it will be converted to a RegExp
  21944. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21945. * `new RegExp('^abc$')`.<br />
  21946. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21947. * start at the index of the last search's match, thus not taking the whole input value into
  21948. * account.
  21949. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21950. * interaction with the input element.
  21951. *
  21952. * @example
  21953. <example name="url-input-directive" module="urlExample">
  21954. <file name="index.html">
  21955. <script>
  21956. angular.module('urlExample', [])
  21957. .controller('ExampleController', ['$scope', function($scope) {
  21958. $scope.url = {
  21959. text: 'http://google.com'
  21960. };
  21961. }]);
  21962. </script>
  21963. <form name="myForm" ng-controller="ExampleController">
  21964. <label>URL:
  21965. <input type="url" name="input" ng-model="url.text" required>
  21966. <label>
  21967. <div role="alert">
  21968. <span class="error" ng-show="myForm.input.$error.required">
  21969. Required!</span>
  21970. <span class="error" ng-show="myForm.input.$error.url">
  21971. Not valid url!</span>
  21972. </div>
  21973. <tt>text = {{url.text}}</tt><br/>
  21974. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21975. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21976. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21977. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21978. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  21979. </form>
  21980. </file>
  21981. <file name="protractor.js" type="protractor">
  21982. var text = element(by.binding('url.text'));
  21983. var valid = element(by.binding('myForm.input.$valid'));
  21984. var input = element(by.model('url.text'));
  21985. it('should initialize to model', function() {
  21986. expect(text.getText()).toContain('http://google.com');
  21987. expect(valid.getText()).toContain('true');
  21988. });
  21989. it('should be invalid if empty', function() {
  21990. input.clear();
  21991. input.sendKeys('');
  21992. expect(text.getText()).toEqual('text =');
  21993. expect(valid.getText()).toContain('false');
  21994. });
  21995. it('should be invalid if not url', function() {
  21996. input.clear();
  21997. input.sendKeys('box');
  21998. expect(valid.getText()).toContain('false');
  21999. });
  22000. </file>
  22001. </example>
  22002. */
  22003. 'url': urlInputType,
  22004. /**
  22005. * @ngdoc input
  22006. * @name input[email]
  22007. *
  22008. * @description
  22009. * Text input with email validation. Sets the `email` validation error key if not a valid email
  22010. * address.
  22011. *
  22012. * <div class="alert alert-warning">
  22013. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  22014. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  22015. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  22016. * </div>
  22017. *
  22018. * @param {string} ngModel Assignable angular expression to data-bind to.
  22019. * @param {string=} name Property name of the form under which the control is published.
  22020. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22021. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22022. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22023. * `required` when you want to data-bind to the `required` attribute.
  22024. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22025. * minlength.
  22026. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22027. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22028. * any length.
  22029. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22030. * that contains the regular expression body that will be converted to a regular expression
  22031. * as in the ngPattern directive.
  22032. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22033. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22034. * If the expression evaluates to a RegExp object, then this is used directly.
  22035. * If the expression evaluates to a string, then it will be converted to a RegExp
  22036. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22037. * `new RegExp('^abc$')`.<br />
  22038. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22039. * start at the index of the last search's match, thus not taking the whole input value into
  22040. * account.
  22041. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22042. * interaction with the input element.
  22043. *
  22044. * @example
  22045. <example name="email-input-directive" module="emailExample">
  22046. <file name="index.html">
  22047. <script>
  22048. angular.module('emailExample', [])
  22049. .controller('ExampleController', ['$scope', function($scope) {
  22050. $scope.email = {
  22051. text: 'me@example.com'
  22052. };
  22053. }]);
  22054. </script>
  22055. <form name="myForm" ng-controller="ExampleController">
  22056. <label>Email:
  22057. <input type="email" name="input" ng-model="email.text" required>
  22058. </label>
  22059. <div role="alert">
  22060. <span class="error" ng-show="myForm.input.$error.required">
  22061. Required!</span>
  22062. <span class="error" ng-show="myForm.input.$error.email">
  22063. Not valid email!</span>
  22064. </div>
  22065. <tt>text = {{email.text}}</tt><br/>
  22066. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22067. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22068. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22069. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22070. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  22071. </form>
  22072. </file>
  22073. <file name="protractor.js" type="protractor">
  22074. var text = element(by.binding('email.text'));
  22075. var valid = element(by.binding('myForm.input.$valid'));
  22076. var input = element(by.model('email.text'));
  22077. it('should initialize to model', function() {
  22078. expect(text.getText()).toContain('me@example.com');
  22079. expect(valid.getText()).toContain('true');
  22080. });
  22081. it('should be invalid if empty', function() {
  22082. input.clear();
  22083. input.sendKeys('');
  22084. expect(text.getText()).toEqual('text =');
  22085. expect(valid.getText()).toContain('false');
  22086. });
  22087. it('should be invalid if not email', function() {
  22088. input.clear();
  22089. input.sendKeys('xxx');
  22090. expect(valid.getText()).toContain('false');
  22091. });
  22092. </file>
  22093. </example>
  22094. */
  22095. 'email': emailInputType,
  22096. /**
  22097. * @ngdoc input
  22098. * @name input[radio]
  22099. *
  22100. * @description
  22101. * HTML radio button.
  22102. *
  22103. * @param {string} ngModel Assignable angular expression to data-bind to.
  22104. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  22105. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  22106. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  22107. * @param {string=} name Property name of the form under which the control is published.
  22108. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22109. * interaction with the input element.
  22110. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  22111. * is selected. Should be used instead of the `value` attribute if you need
  22112. * a non-string `ngModel` (`boolean`, `array`, ...).
  22113. *
  22114. * @example
  22115. <example name="radio-input-directive" module="radioExample">
  22116. <file name="index.html">
  22117. <script>
  22118. angular.module('radioExample', [])
  22119. .controller('ExampleController', ['$scope', function($scope) {
  22120. $scope.color = {
  22121. name: 'blue'
  22122. };
  22123. $scope.specialValue = {
  22124. "id": "12345",
  22125. "value": "green"
  22126. };
  22127. }]);
  22128. </script>
  22129. <form name="myForm" ng-controller="ExampleController">
  22130. <label>
  22131. <input type="radio" ng-model="color.name" value="red">
  22132. Red
  22133. </label><br/>
  22134. <label>
  22135. <input type="radio" ng-model="color.name" ng-value="specialValue">
  22136. Green
  22137. </label><br/>
  22138. <label>
  22139. <input type="radio" ng-model="color.name" value="blue">
  22140. Blue
  22141. </label><br/>
  22142. <tt>color = {{color.name | json}}</tt><br/>
  22143. </form>
  22144. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  22145. </file>
  22146. <file name="protractor.js" type="protractor">
  22147. it('should change state', function() {
  22148. var inputs = element.all(by.model('color.name'));
  22149. var color = element(by.binding('color.name'));
  22150. expect(color.getText()).toContain('blue');
  22151. inputs.get(0).click();
  22152. expect(color.getText()).toContain('red');
  22153. inputs.get(1).click();
  22154. expect(color.getText()).toContain('green');
  22155. });
  22156. </file>
  22157. </example>
  22158. */
  22159. 'radio': radioInputType,
  22160. /**
  22161. * @ngdoc input
  22162. * @name input[range]
  22163. *
  22164. * @description
  22165. * Native range input with validation and transformation.
  22166. *
  22167. * The model for the range input must always be a `Number`.
  22168. *
  22169. * IE9 and other browsers that do not support the `range` type fall back
  22170. * to a text input without any default values for `min`, `max` and `step`. Model binding,
  22171. * validation and number parsing are nevertheless supported.
  22172. *
  22173. * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
  22174. * in a way that never allows the input to hold an invalid value. That means:
  22175. * - any non-numerical value is set to `(max + min) / 2`.
  22176. * - any numerical value that is less than the current min val, or greater than the current max val
  22177. * is set to the min / max val respectively.
  22178. * - additionally, the current `step` is respected, so the nearest value that satisfies a step
  22179. * is used.
  22180. *
  22181. * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
  22182. * for more info.
  22183. *
  22184. * This has the following consequences for Angular:
  22185. *
  22186. * Since the element value should always reflect the current model value, a range input
  22187. * will set the bound ngModel expression to the value that the browser has set for the
  22188. * input element. For example, in the following input `<input type="range" ng-model="model.value">`,
  22189. * if the application sets `model.value = null`, the browser will set the input to `'50'`.
  22190. * Angular will then set the model to `50`, to prevent input and model value being out of sync.
  22191. *
  22192. * That means the model for range will immediately be set to `50` after `ngModel` has been
  22193. * initialized. It also means a range input can never have the required error.
  22194. *
  22195. * This does not only affect changes to the model value, but also to the values of the `min`,
  22196. * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
  22197. * the input value, Angular will also update the model value.
  22198. *
  22199. * Automatic value adjustment also means that a range input element can never have the `required`,
  22200. * `min`, or `max` errors.
  22201. *
  22202. * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
  22203. * when the step value changes dynamically - they do not adjust the element value correctly, but
  22204. * instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step`
  22205. * error on the input, and set the model to `undefined`.
  22206. *
  22207. * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
  22208. * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
  22209. * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
  22210. *
  22211. * @param {string} ngModel Assignable angular expression to data-bind to.
  22212. * @param {string=} name Property name of the form under which the control is published.
  22213. * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
  22214. * than `min`. Can be interpolated.
  22215. * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
  22216. * Can be interpolated.
  22217. * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
  22218. * Can be interpolated.
  22219. * @param {string=} ngChange Angular expression to be executed when the ngModel value changes due
  22220. * to user interaction with the input element.
  22221. * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
  22222. * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
  22223. * Checkout {@link ng.directive:ngChecked ngChecked} for usage.
  22224. *
  22225. * @example
  22226. <example name="range-input-directive" module="rangeExample">
  22227. <file name="index.html">
  22228. <script>
  22229. angular.module('rangeExample', [])
  22230. .controller('ExampleController', ['$scope', function($scope) {
  22231. $scope.value = 75;
  22232. $scope.min = 10;
  22233. $scope.max = 90;
  22234. }]);
  22235. </script>
  22236. <form name="myForm" ng-controller="ExampleController">
  22237. Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
  22238. <hr>
  22239. Model as number: <input type="number" ng-model="value"><br>
  22240. Min: <input type="number" ng-model="min"><br>
  22241. Max: <input type="number" ng-model="max"><br>
  22242. value = <code>{{value}}</code><br/>
  22243. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22244. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22245. </form>
  22246. </file>
  22247. </example>
  22248. * ## Range Input with ngMin & ngMax attributes
  22249. * @example
  22250. <example name="range-input-directive-ng" module="rangeExample">
  22251. <file name="index.html">
  22252. <script>
  22253. angular.module('rangeExample', [])
  22254. .controller('ExampleController', ['$scope', function($scope) {
  22255. $scope.value = 75;
  22256. $scope.min = 10;
  22257. $scope.max = 90;
  22258. }]);
  22259. </script>
  22260. <form name="myForm" ng-controller="ExampleController">
  22261. Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
  22262. <hr>
  22263. Model as number: <input type="number" ng-model="value"><br>
  22264. Min: <input type="number" ng-model="min"><br>
  22265. Max: <input type="number" ng-model="max"><br>
  22266. value = <code>{{value}}</code><br/>
  22267. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22268. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22269. </form>
  22270. </file>
  22271. </example>
  22272. */
  22273. 'range': rangeInputType,
  22274. /**
  22275. * @ngdoc input
  22276. * @name input[checkbox]
  22277. *
  22278. * @description
  22279. * HTML checkbox.
  22280. *
  22281. * @param {string} ngModel Assignable angular expression to data-bind to.
  22282. * @param {string=} name Property name of the form under which the control is published.
  22283. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  22284. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  22285. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22286. * interaction with the input element.
  22287. *
  22288. * @example
  22289. <example name="checkbox-input-directive" module="checkboxExample">
  22290. <file name="index.html">
  22291. <script>
  22292. angular.module('checkboxExample', [])
  22293. .controller('ExampleController', ['$scope', function($scope) {
  22294. $scope.checkboxModel = {
  22295. value1 : true,
  22296. value2 : 'YES'
  22297. };
  22298. }]);
  22299. </script>
  22300. <form name="myForm" ng-controller="ExampleController">
  22301. <label>Value1:
  22302. <input type="checkbox" ng-model="checkboxModel.value1">
  22303. </label><br/>
  22304. <label>Value2:
  22305. <input type="checkbox" ng-model="checkboxModel.value2"
  22306. ng-true-value="'YES'" ng-false-value="'NO'">
  22307. </label><br/>
  22308. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  22309. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  22310. </form>
  22311. </file>
  22312. <file name="protractor.js" type="protractor">
  22313. it('should change state', function() {
  22314. var value1 = element(by.binding('checkboxModel.value1'));
  22315. var value2 = element(by.binding('checkboxModel.value2'));
  22316. expect(value1.getText()).toContain('true');
  22317. expect(value2.getText()).toContain('YES');
  22318. element(by.model('checkboxModel.value1')).click();
  22319. element(by.model('checkboxModel.value2')).click();
  22320. expect(value1.getText()).toContain('false');
  22321. expect(value2.getText()).toContain('NO');
  22322. });
  22323. </file>
  22324. </example>
  22325. */
  22326. 'checkbox': checkboxInputType,
  22327. 'hidden': noop,
  22328. 'button': noop,
  22329. 'submit': noop,
  22330. 'reset': noop,
  22331. 'file': noop
  22332. };
  22333. function stringBasedInputType(ctrl) {
  22334. ctrl.$formatters.push(function(value) {
  22335. return ctrl.$isEmpty(value) ? value : value.toString();
  22336. });
  22337. }
  22338. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22339. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22340. stringBasedInputType(ctrl);
  22341. }
  22342. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22343. var type = lowercase(element[0].type);
  22344. // In composition mode, users are still inputting intermediate text buffer,
  22345. // hold the listener until composition is done.
  22346. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  22347. if (!$sniffer.android) {
  22348. var composing = false;
  22349. element.on('compositionstart', function() {
  22350. composing = true;
  22351. });
  22352. element.on('compositionend', function() {
  22353. composing = false;
  22354. listener();
  22355. });
  22356. }
  22357. var timeout;
  22358. var listener = function(ev) {
  22359. if (timeout) {
  22360. $browser.defer.cancel(timeout);
  22361. timeout = null;
  22362. }
  22363. if (composing) return;
  22364. var value = element.val(),
  22365. event = ev && ev.type;
  22366. // By default we will trim the value
  22367. // If the attribute ng-trim exists we will avoid trimming
  22368. // If input type is 'password', the value is never trimmed
  22369. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  22370. value = trim(value);
  22371. }
  22372. // If a control is suffering from bad input (due to native validators), browsers discard its
  22373. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  22374. // control's value is the same empty value twice in a row.
  22375. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  22376. ctrl.$setViewValue(value, event);
  22377. }
  22378. };
  22379. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  22380. // input event on backspace, delete or cut
  22381. if ($sniffer.hasEvent('input')) {
  22382. element.on('input', listener);
  22383. } else {
  22384. var deferListener = function(ev, input, origValue) {
  22385. if (!timeout) {
  22386. timeout = $browser.defer(function() {
  22387. timeout = null;
  22388. if (!input || input.value !== origValue) {
  22389. listener(ev);
  22390. }
  22391. });
  22392. }
  22393. };
  22394. element.on('keydown', /** @this */ function(event) {
  22395. var key = event.keyCode;
  22396. // ignore
  22397. // command modifiers arrows
  22398. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  22399. deferListener(event, this, this.value);
  22400. });
  22401. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  22402. if ($sniffer.hasEvent('paste')) {
  22403. element.on('paste cut', deferListener);
  22404. }
  22405. }
  22406. // if user paste into input using mouse on older browser
  22407. // or form autocomplete on newer browser, we need "change" event to catch it
  22408. element.on('change', listener);
  22409. // Some native input types (date-family) have the ability to change validity without
  22410. // firing any input/change events.
  22411. // For these event types, when native validators are present and the browser supports the type,
  22412. // check for validity changes on various DOM events.
  22413. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  22414. element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
  22415. if (!timeout) {
  22416. var validity = this[VALIDITY_STATE_PROPERTY];
  22417. var origBadInput = validity.badInput;
  22418. var origTypeMismatch = validity.typeMismatch;
  22419. timeout = $browser.defer(function() {
  22420. timeout = null;
  22421. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  22422. listener(ev);
  22423. }
  22424. });
  22425. }
  22426. });
  22427. }
  22428. ctrl.$render = function() {
  22429. // Workaround for Firefox validation #12102.
  22430. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  22431. if (element.val() !== value) {
  22432. element.val(value);
  22433. }
  22434. };
  22435. }
  22436. function weekParser(isoWeek, existingDate) {
  22437. if (isDate(isoWeek)) {
  22438. return isoWeek;
  22439. }
  22440. if (isString(isoWeek)) {
  22441. WEEK_REGEXP.lastIndex = 0;
  22442. var parts = WEEK_REGEXP.exec(isoWeek);
  22443. if (parts) {
  22444. var year = +parts[1],
  22445. week = +parts[2],
  22446. hours = 0,
  22447. minutes = 0,
  22448. seconds = 0,
  22449. milliseconds = 0,
  22450. firstThurs = getFirstThursdayOfYear(year),
  22451. addDays = (week - 1) * 7;
  22452. if (existingDate) {
  22453. hours = existingDate.getHours();
  22454. minutes = existingDate.getMinutes();
  22455. seconds = existingDate.getSeconds();
  22456. milliseconds = existingDate.getMilliseconds();
  22457. }
  22458. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  22459. }
  22460. }
  22461. return NaN;
  22462. }
  22463. function createDateParser(regexp, mapping) {
  22464. return function(iso, date) {
  22465. var parts, map;
  22466. if (isDate(iso)) {
  22467. return iso;
  22468. }
  22469. if (isString(iso)) {
  22470. // When a date is JSON'ified to wraps itself inside of an extra
  22471. // set of double quotes. This makes the date parsing code unable
  22472. // to match the date string and parse it as a date.
  22473. if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
  22474. iso = iso.substring(1, iso.length - 1);
  22475. }
  22476. if (ISO_DATE_REGEXP.test(iso)) {
  22477. return new Date(iso);
  22478. }
  22479. regexp.lastIndex = 0;
  22480. parts = regexp.exec(iso);
  22481. if (parts) {
  22482. parts.shift();
  22483. if (date) {
  22484. map = {
  22485. yyyy: date.getFullYear(),
  22486. MM: date.getMonth() + 1,
  22487. dd: date.getDate(),
  22488. HH: date.getHours(),
  22489. mm: date.getMinutes(),
  22490. ss: date.getSeconds(),
  22491. sss: date.getMilliseconds() / 1000
  22492. };
  22493. } else {
  22494. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  22495. }
  22496. forEach(parts, function(part, index) {
  22497. if (index < mapping.length) {
  22498. map[mapping[index]] = +part;
  22499. }
  22500. });
  22501. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  22502. }
  22503. }
  22504. return NaN;
  22505. };
  22506. }
  22507. function createDateInputType(type, regexp, parseDate, format) {
  22508. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  22509. badInputChecker(scope, element, attr, ctrl);
  22510. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22511. var timezone = ctrl && ctrl.$options.getOption('timezone');
  22512. var previousDate;
  22513. ctrl.$$parserName = type;
  22514. ctrl.$parsers.push(function(value) {
  22515. if (ctrl.$isEmpty(value)) return null;
  22516. if (regexp.test(value)) {
  22517. // Note: We cannot read ctrl.$modelValue, as there might be a different
  22518. // parser/formatter in the processing chain so that the model
  22519. // contains some different data format!
  22520. var parsedDate = parseDate(value, previousDate);
  22521. if (timezone) {
  22522. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  22523. }
  22524. return parsedDate;
  22525. }
  22526. return undefined;
  22527. });
  22528. ctrl.$formatters.push(function(value) {
  22529. if (value && !isDate(value)) {
  22530. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  22531. }
  22532. if (isValidDate(value)) {
  22533. previousDate = value;
  22534. if (previousDate && timezone) {
  22535. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  22536. }
  22537. return $filter('date')(value, format, timezone);
  22538. } else {
  22539. previousDate = null;
  22540. return '';
  22541. }
  22542. });
  22543. if (isDefined(attr.min) || attr.ngMin) {
  22544. var minVal;
  22545. ctrl.$validators.min = function(value) {
  22546. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  22547. };
  22548. attr.$observe('min', function(val) {
  22549. minVal = parseObservedDateValue(val);
  22550. ctrl.$validate();
  22551. });
  22552. }
  22553. if (isDefined(attr.max) || attr.ngMax) {
  22554. var maxVal;
  22555. ctrl.$validators.max = function(value) {
  22556. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  22557. };
  22558. attr.$observe('max', function(val) {
  22559. maxVal = parseObservedDateValue(val);
  22560. ctrl.$validate();
  22561. });
  22562. }
  22563. function isValidDate(value) {
  22564. // Invalid Date: getTime() returns NaN
  22565. return value && !(value.getTime && value.getTime() !== value.getTime());
  22566. }
  22567. function parseObservedDateValue(val) {
  22568. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  22569. }
  22570. };
  22571. }
  22572. function badInputChecker(scope, element, attr, ctrl) {
  22573. var node = element[0];
  22574. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  22575. if (nativeValidation) {
  22576. ctrl.$parsers.push(function(value) {
  22577. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  22578. return validity.badInput || validity.typeMismatch ? undefined : value;
  22579. });
  22580. }
  22581. }
  22582. function numberFormatterParser(ctrl) {
  22583. ctrl.$$parserName = 'number';
  22584. ctrl.$parsers.push(function(value) {
  22585. if (ctrl.$isEmpty(value)) return null;
  22586. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  22587. return undefined;
  22588. });
  22589. ctrl.$formatters.push(function(value) {
  22590. if (!ctrl.$isEmpty(value)) {
  22591. if (!isNumber(value)) {
  22592. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  22593. }
  22594. value = value.toString();
  22595. }
  22596. return value;
  22597. });
  22598. }
  22599. function parseNumberAttrVal(val) {
  22600. if (isDefined(val) && !isNumber(val)) {
  22601. val = parseFloat(val);
  22602. }
  22603. return !isNumberNaN(val) ? val : undefined;
  22604. }
  22605. function isNumberInteger(num) {
  22606. // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
  22607. // (minus the assumption that `num` is a number)
  22608. // eslint-disable-next-line no-bitwise
  22609. return (num | 0) === num;
  22610. }
  22611. function countDecimals(num) {
  22612. var numString = num.toString();
  22613. var decimalSymbolIndex = numString.indexOf('.');
  22614. if (decimalSymbolIndex === -1) {
  22615. if (-1 < num && num < 1) {
  22616. // It may be in the exponential notation format (`1e-X`)
  22617. var match = /e-(\d+)$/.exec(numString);
  22618. if (match) {
  22619. return Number(match[1]);
  22620. }
  22621. }
  22622. return 0;
  22623. }
  22624. return numString.length - decimalSymbolIndex - 1;
  22625. }
  22626. function isValidForStep(viewValue, stepBase, step) {
  22627. // At this point `stepBase` and `step` are expected to be non-NaN values
  22628. // and `viewValue` is expected to be a valid stringified number.
  22629. var value = Number(viewValue);
  22630. var isNonIntegerValue = !isNumberInteger(value);
  22631. var isNonIntegerStepBase = !isNumberInteger(stepBase);
  22632. var isNonIntegerStep = !isNumberInteger(step);
  22633. // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
  22634. // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
  22635. if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) {
  22636. var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0;
  22637. var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0;
  22638. var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0;
  22639. var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals);
  22640. var multiplier = Math.pow(10, decimalCount);
  22641. value = value * multiplier;
  22642. stepBase = stepBase * multiplier;
  22643. step = step * multiplier;
  22644. if (isNonIntegerValue) value = Math.round(value);
  22645. if (isNonIntegerStepBase) stepBase = Math.round(stepBase);
  22646. if (isNonIntegerStep) step = Math.round(step);
  22647. }
  22648. return (value - stepBase) % step === 0;
  22649. }
  22650. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22651. badInputChecker(scope, element, attr, ctrl);
  22652. numberFormatterParser(ctrl);
  22653. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22654. var minVal;
  22655. var maxVal;
  22656. if (isDefined(attr.min) || attr.ngMin) {
  22657. ctrl.$validators.min = function(value) {
  22658. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  22659. };
  22660. attr.$observe('min', function(val) {
  22661. minVal = parseNumberAttrVal(val);
  22662. // TODO(matsko): implement validateLater to reduce number of validations
  22663. ctrl.$validate();
  22664. });
  22665. }
  22666. if (isDefined(attr.max) || attr.ngMax) {
  22667. ctrl.$validators.max = function(value) {
  22668. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  22669. };
  22670. attr.$observe('max', function(val) {
  22671. maxVal = parseNumberAttrVal(val);
  22672. // TODO(matsko): implement validateLater to reduce number of validations
  22673. ctrl.$validate();
  22674. });
  22675. }
  22676. if (isDefined(attr.step) || attr.ngStep) {
  22677. var stepVal;
  22678. ctrl.$validators.step = function(modelValue, viewValue) {
  22679. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  22680. isValidForStep(viewValue, minVal || 0, stepVal);
  22681. };
  22682. attr.$observe('step', function(val) {
  22683. stepVal = parseNumberAttrVal(val);
  22684. // TODO(matsko): implement validateLater to reduce number of validations
  22685. ctrl.$validate();
  22686. });
  22687. }
  22688. }
  22689. function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22690. badInputChecker(scope, element, attr, ctrl);
  22691. numberFormatterParser(ctrl);
  22692. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22693. var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
  22694. minVal = supportsRange ? 0 : undefined,
  22695. maxVal = supportsRange ? 100 : undefined,
  22696. stepVal = supportsRange ? 1 : undefined,
  22697. validity = element[0].validity,
  22698. hasMinAttr = isDefined(attr.min),
  22699. hasMaxAttr = isDefined(attr.max),
  22700. hasStepAttr = isDefined(attr.step);
  22701. var originalRender = ctrl.$render;
  22702. ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
  22703. //Browsers that implement range will set these values automatically, but reading the adjusted values after
  22704. //$render would cause the min / max validators to be applied with the wrong value
  22705. function rangeRender() {
  22706. originalRender();
  22707. ctrl.$setViewValue(element.val());
  22708. } :
  22709. originalRender;
  22710. if (hasMinAttr) {
  22711. ctrl.$validators.min = supportsRange ?
  22712. // Since all browsers set the input to a valid value, we don't need to check validity
  22713. function noopMinValidator() { return true; } :
  22714. // non-support browsers validate the min val
  22715. function minValidator(modelValue, viewValue) {
  22716. return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
  22717. };
  22718. setInitialValueAndObserver('min', minChange);
  22719. }
  22720. if (hasMaxAttr) {
  22721. ctrl.$validators.max = supportsRange ?
  22722. // Since all browsers set the input to a valid value, we don't need to check validity
  22723. function noopMaxValidator() { return true; } :
  22724. // non-support browsers validate the max val
  22725. function maxValidator(modelValue, viewValue) {
  22726. return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
  22727. };
  22728. setInitialValueAndObserver('max', maxChange);
  22729. }
  22730. if (hasStepAttr) {
  22731. ctrl.$validators.step = supportsRange ?
  22732. function nativeStepValidator() {
  22733. // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
  22734. // input element value to a valid value). It's possible that other browsers set the stepMismatch
  22735. // validity error instead, so we can at least report an error in that case.
  22736. return !validity.stepMismatch;
  22737. } :
  22738. // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
  22739. function stepValidator(modelValue, viewValue) {
  22740. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  22741. isValidForStep(viewValue, minVal || 0, stepVal);
  22742. };
  22743. setInitialValueAndObserver('step', stepChange);
  22744. }
  22745. function setInitialValueAndObserver(htmlAttrName, changeFn) {
  22746. // interpolated attributes set the attribute value only after a digest, but we need the
  22747. // attribute value when the input is first rendered, so that the browser can adjust the
  22748. // input value based on the min/max value
  22749. element.attr(htmlAttrName, attr[htmlAttrName]);
  22750. attr.$observe(htmlAttrName, changeFn);
  22751. }
  22752. function minChange(val) {
  22753. minVal = parseNumberAttrVal(val);
  22754. // ignore changes before model is initialized
  22755. if (isNumberNaN(ctrl.$modelValue)) {
  22756. return;
  22757. }
  22758. if (supportsRange) {
  22759. var elVal = element.val();
  22760. // IE11 doesn't set the el val correctly if the minVal is greater than the element value
  22761. if (minVal > elVal) {
  22762. elVal = minVal;
  22763. element.val(elVal);
  22764. }
  22765. ctrl.$setViewValue(elVal);
  22766. } else {
  22767. // TODO(matsko): implement validateLater to reduce number of validations
  22768. ctrl.$validate();
  22769. }
  22770. }
  22771. function maxChange(val) {
  22772. maxVal = parseNumberAttrVal(val);
  22773. // ignore changes before model is initialized
  22774. if (isNumberNaN(ctrl.$modelValue)) {
  22775. return;
  22776. }
  22777. if (supportsRange) {
  22778. var elVal = element.val();
  22779. // IE11 doesn't set the el val correctly if the maxVal is less than the element value
  22780. if (maxVal < elVal) {
  22781. element.val(maxVal);
  22782. // IE11 and Chrome don't set the value to the minVal when max < min
  22783. elVal = maxVal < minVal ? minVal : maxVal;
  22784. }
  22785. ctrl.$setViewValue(elVal);
  22786. } else {
  22787. // TODO(matsko): implement validateLater to reduce number of validations
  22788. ctrl.$validate();
  22789. }
  22790. }
  22791. function stepChange(val) {
  22792. stepVal = parseNumberAttrVal(val);
  22793. // ignore changes before model is initialized
  22794. if (isNumberNaN(ctrl.$modelValue)) {
  22795. return;
  22796. }
  22797. // Some browsers don't adjust the input value correctly, but set the stepMismatch error
  22798. if (supportsRange && ctrl.$viewValue !== element.val()) {
  22799. ctrl.$setViewValue(element.val());
  22800. } else {
  22801. // TODO(matsko): implement validateLater to reduce number of validations
  22802. ctrl.$validate();
  22803. }
  22804. }
  22805. }
  22806. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22807. // Note: no badInputChecker here by purpose as `url` is only a validation
  22808. // in browsers, i.e. we can always read out input.value even if it is not valid!
  22809. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22810. stringBasedInputType(ctrl);
  22811. ctrl.$$parserName = 'url';
  22812. ctrl.$validators.url = function(modelValue, viewValue) {
  22813. var value = modelValue || viewValue;
  22814. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  22815. };
  22816. }
  22817. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22818. // Note: no badInputChecker here by purpose as `url` is only a validation
  22819. // in browsers, i.e. we can always read out input.value even if it is not valid!
  22820. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22821. stringBasedInputType(ctrl);
  22822. ctrl.$$parserName = 'email';
  22823. ctrl.$validators.email = function(modelValue, viewValue) {
  22824. var value = modelValue || viewValue;
  22825. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  22826. };
  22827. }
  22828. function radioInputType(scope, element, attr, ctrl) {
  22829. var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
  22830. // make the name unique, if not defined
  22831. if (isUndefined(attr.name)) {
  22832. element.attr('name', nextUid());
  22833. }
  22834. var listener = function(ev) {
  22835. var value;
  22836. if (element[0].checked) {
  22837. value = attr.value;
  22838. if (doTrim) {
  22839. value = trim(value);
  22840. }
  22841. ctrl.$setViewValue(value, ev && ev.type);
  22842. }
  22843. };
  22844. element.on('click', listener);
  22845. ctrl.$render = function() {
  22846. var value = attr.value;
  22847. if (doTrim) {
  22848. value = trim(value);
  22849. }
  22850. element[0].checked = (value === ctrl.$viewValue);
  22851. };
  22852. attr.$observe('value', ctrl.$render);
  22853. }
  22854. function parseConstantExpr($parse, context, name, expression, fallback) {
  22855. var parseFn;
  22856. if (isDefined(expression)) {
  22857. parseFn = $parse(expression);
  22858. if (!parseFn.constant) {
  22859. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  22860. '`{1}`.', name, expression);
  22861. }
  22862. return parseFn(context);
  22863. }
  22864. return fallback;
  22865. }
  22866. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  22867. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  22868. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  22869. var listener = function(ev) {
  22870. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  22871. };
  22872. element.on('click', listener);
  22873. ctrl.$render = function() {
  22874. element[0].checked = ctrl.$viewValue;
  22875. };
  22876. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  22877. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  22878. // it to a boolean.
  22879. ctrl.$isEmpty = function(value) {
  22880. return value === false;
  22881. };
  22882. ctrl.$formatters.push(function(value) {
  22883. return equals(value, trueValue);
  22884. });
  22885. ctrl.$parsers.push(function(value) {
  22886. return value ? trueValue : falseValue;
  22887. });
  22888. }
  22889. /**
  22890. * @ngdoc directive
  22891. * @name textarea
  22892. * @restrict E
  22893. *
  22894. * @description
  22895. * HTML textarea element control with angular data-binding. The data-binding and validation
  22896. * properties of this element are exactly the same as those of the
  22897. * {@link ng.directive:input input element}.
  22898. *
  22899. * @param {string} ngModel Assignable angular expression to data-bind to.
  22900. * @param {string=} name Property name of the form under which the control is published.
  22901. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22902. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22903. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22904. * `required` when you want to data-bind to the `required` attribute.
  22905. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22906. * minlength.
  22907. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22908. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  22909. * length.
  22910. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22911. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22912. * If the expression evaluates to a RegExp object, then this is used directly.
  22913. * If the expression evaluates to a string, then it will be converted to a RegExp
  22914. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22915. * `new RegExp('^abc$')`.<br />
  22916. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22917. * start at the index of the last search's match, thus not taking the whole input value into
  22918. * account.
  22919. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22920. * interaction with the input element.
  22921. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  22922. *
  22923. * @knownIssue
  22924. *
  22925. * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
  22926. * insert the placeholder value as the textarea's content. If the placeholder value contains
  22927. * interpolation (`{{ ... }}`), an error will be logged in the console when Angular tries to update
  22928. * the value of the by-then-removed text node. This doesn't affect the functionality of the
  22929. * textarea, but can be undesirable.
  22930. *
  22931. * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
  22932. * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
  22933. * find more details on `ngAttr` in the
  22934. * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
  22935. * Developer Guide.
  22936. */
  22937. /**
  22938. * @ngdoc directive
  22939. * @name input
  22940. * @restrict E
  22941. *
  22942. * @description
  22943. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  22944. * input state control, and validation.
  22945. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  22946. *
  22947. * <div class="alert alert-warning">
  22948. * **Note:** Not every feature offered is available for all input types.
  22949. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  22950. * </div>
  22951. *
  22952. * @param {string} ngModel Assignable angular expression to data-bind to.
  22953. * @param {string=} name Property name of the form under which the control is published.
  22954. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22955. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  22956. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22957. * minlength.
  22958. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22959. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  22960. * length.
  22961. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22962. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22963. * If the expression evaluates to a RegExp object, then this is used directly.
  22964. * If the expression evaluates to a string, then it will be converted to a RegExp
  22965. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22966. * `new RegExp('^abc$')`.<br />
  22967. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22968. * start at the index of the last search's match, thus not taking the whole input value into
  22969. * account.
  22970. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22971. * interaction with the input element.
  22972. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  22973. * This parameter is ignored for input[type=password] controls, which will never trim the
  22974. * input.
  22975. *
  22976. * @example
  22977. <example name="input-directive" module="inputExample">
  22978. <file name="index.html">
  22979. <script>
  22980. angular.module('inputExample', [])
  22981. .controller('ExampleController', ['$scope', function($scope) {
  22982. $scope.user = {name: 'guest', last: 'visitor'};
  22983. }]);
  22984. </script>
  22985. <div ng-controller="ExampleController">
  22986. <form name="myForm">
  22987. <label>
  22988. User name:
  22989. <input type="text" name="userName" ng-model="user.name" required>
  22990. </label>
  22991. <div role="alert">
  22992. <span class="error" ng-show="myForm.userName.$error.required">
  22993. Required!</span>
  22994. </div>
  22995. <label>
  22996. Last name:
  22997. <input type="text" name="lastName" ng-model="user.last"
  22998. ng-minlength="3" ng-maxlength="10">
  22999. </label>
  23000. <div role="alert">
  23001. <span class="error" ng-show="myForm.lastName.$error.minlength">
  23002. Too short!</span>
  23003. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  23004. Too long!</span>
  23005. </div>
  23006. </form>
  23007. <hr>
  23008. <tt>user = {{user}}</tt><br/>
  23009. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  23010. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  23011. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  23012. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  23013. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23014. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23015. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  23016. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  23017. </div>
  23018. </file>
  23019. <file name="protractor.js" type="protractor">
  23020. var user = element(by.exactBinding('user'));
  23021. var userNameValid = element(by.binding('myForm.userName.$valid'));
  23022. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  23023. var lastNameError = element(by.binding('myForm.lastName.$error'));
  23024. var formValid = element(by.binding('myForm.$valid'));
  23025. var userNameInput = element(by.model('user.name'));
  23026. var userLastInput = element(by.model('user.last'));
  23027. it('should initialize to model', function() {
  23028. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  23029. expect(userNameValid.getText()).toContain('true');
  23030. expect(formValid.getText()).toContain('true');
  23031. });
  23032. it('should be invalid if empty when required', function() {
  23033. userNameInput.clear();
  23034. userNameInput.sendKeys('');
  23035. expect(user.getText()).toContain('{"last":"visitor"}');
  23036. expect(userNameValid.getText()).toContain('false');
  23037. expect(formValid.getText()).toContain('false');
  23038. });
  23039. it('should be valid if empty when min length is set', function() {
  23040. userLastInput.clear();
  23041. userLastInput.sendKeys('');
  23042. expect(user.getText()).toContain('{"name":"guest","last":""}');
  23043. expect(lastNameValid.getText()).toContain('true');
  23044. expect(formValid.getText()).toContain('true');
  23045. });
  23046. it('should be invalid if less than required min length', function() {
  23047. userLastInput.clear();
  23048. userLastInput.sendKeys('xx');
  23049. expect(user.getText()).toContain('{"name":"guest"}');
  23050. expect(lastNameValid.getText()).toContain('false');
  23051. expect(lastNameError.getText()).toContain('minlength');
  23052. expect(formValid.getText()).toContain('false');
  23053. });
  23054. it('should be invalid if longer than max length', function() {
  23055. userLastInput.clear();
  23056. userLastInput.sendKeys('some ridiculously long name');
  23057. expect(user.getText()).toContain('{"name":"guest"}');
  23058. expect(lastNameValid.getText()).toContain('false');
  23059. expect(lastNameError.getText()).toContain('maxlength');
  23060. expect(formValid.getText()).toContain('false');
  23061. });
  23062. </file>
  23063. </example>
  23064. */
  23065. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  23066. function($browser, $sniffer, $filter, $parse) {
  23067. return {
  23068. restrict: 'E',
  23069. require: ['?ngModel'],
  23070. link: {
  23071. pre: function(scope, element, attr, ctrls) {
  23072. if (ctrls[0]) {
  23073. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  23074. $browser, $filter, $parse);
  23075. }
  23076. }
  23077. }
  23078. };
  23079. }];
  23080. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  23081. /**
  23082. * @ngdoc directive
  23083. * @name ngValue
  23084. *
  23085. * @description
  23086. * Binds the given expression to the value of the element.
  23087. *
  23088. * It is mainly used on {@link input[radio] `input[radio]`} and option elements,
  23089. * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
  23090. * {@link select `select`} parent element) is set to the bound value. It is especially useful
  23091. * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
  23092. *
  23093. * It can also be used to achieve one-way binding of a given expression to an input element
  23094. * such as an `input[text]` or a `textarea`, when that element does not use ngModel.
  23095. *
  23096. * @element input
  23097. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  23098. * and `value` property of the element.
  23099. *
  23100. * @example
  23101. <example name="ngValue-directive" module="valueExample">
  23102. <file name="index.html">
  23103. <script>
  23104. angular.module('valueExample', [])
  23105. .controller('ExampleController', ['$scope', function($scope) {
  23106. $scope.names = ['pizza', 'unicorns', 'robots'];
  23107. $scope.my = { favorite: 'unicorns' };
  23108. }]);
  23109. </script>
  23110. <form ng-controller="ExampleController">
  23111. <h2>Which is your favorite?</h2>
  23112. <label ng-repeat="name in names" for="{{name}}">
  23113. {{name}}
  23114. <input type="radio"
  23115. ng-model="my.favorite"
  23116. ng-value="name"
  23117. id="{{name}}"
  23118. name="favorite">
  23119. </label>
  23120. <div>You chose {{my.favorite}}</div>
  23121. </form>
  23122. </file>
  23123. <file name="protractor.js" type="protractor">
  23124. var favorite = element(by.binding('my.favorite'));
  23125. it('should initialize to model', function() {
  23126. expect(favorite.getText()).toContain('unicorns');
  23127. });
  23128. it('should bind the values to the inputs', function() {
  23129. element.all(by.model('my.favorite')).get(0).click();
  23130. expect(favorite.getText()).toContain('pizza');
  23131. });
  23132. </file>
  23133. </example>
  23134. */
  23135. var ngValueDirective = function() {
  23136. /**
  23137. * inputs use the value attribute as their default value if the value property is not set.
  23138. * Once the value property has been set (by adding input), it will not react to changes to
  23139. * the value attribute anymore. Setting both attribute and property fixes this behavior, and
  23140. * makes it possible to use ngValue as a sort of one-way bind.
  23141. */
  23142. function updateElementValue(element, attr, value) {
  23143. // Support: IE9 only
  23144. // In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`).
  23145. var propValue = isDefined(value) ? value : (msie === 9) ? '' : null;
  23146. element.prop('value', propValue);
  23147. attr.$set('value', value);
  23148. }
  23149. return {
  23150. restrict: 'A',
  23151. priority: 100,
  23152. compile: function(tpl, tplAttr) {
  23153. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  23154. return function ngValueConstantLink(scope, elm, attr) {
  23155. var value = scope.$eval(attr.ngValue);
  23156. updateElementValue(elm, attr, value);
  23157. };
  23158. } else {
  23159. return function ngValueLink(scope, elm, attr) {
  23160. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  23161. updateElementValue(elm, attr, value);
  23162. });
  23163. };
  23164. }
  23165. }
  23166. };
  23167. };
  23168. /**
  23169. * @ngdoc directive
  23170. * @name ngBind
  23171. * @restrict AC
  23172. *
  23173. * @description
  23174. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  23175. * with the value of a given expression, and to update the text content when the value of that
  23176. * expression changes.
  23177. *
  23178. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  23179. * `{{ expression }}` which is similar but less verbose.
  23180. *
  23181. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  23182. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  23183. * element attribute, it makes the bindings invisible to the user while the page is loading.
  23184. *
  23185. * An alternative solution to this problem would be using the
  23186. * {@link ng.directive:ngCloak ngCloak} directive.
  23187. *
  23188. *
  23189. * @element ANY
  23190. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  23191. *
  23192. * @example
  23193. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  23194. <example module="bindExample" name="ng-bind">
  23195. <file name="index.html">
  23196. <script>
  23197. angular.module('bindExample', [])
  23198. .controller('ExampleController', ['$scope', function($scope) {
  23199. $scope.name = 'Whirled';
  23200. }]);
  23201. </script>
  23202. <div ng-controller="ExampleController">
  23203. <label>Enter name: <input type="text" ng-model="name"></label><br>
  23204. Hello <span ng-bind="name"></span>!
  23205. </div>
  23206. </file>
  23207. <file name="protractor.js" type="protractor">
  23208. it('should check ng-bind', function() {
  23209. var nameInput = element(by.model('name'));
  23210. expect(element(by.binding('name')).getText()).toBe('Whirled');
  23211. nameInput.clear();
  23212. nameInput.sendKeys('world');
  23213. expect(element(by.binding('name')).getText()).toBe('world');
  23214. });
  23215. </file>
  23216. </example>
  23217. */
  23218. var ngBindDirective = ['$compile', function($compile) {
  23219. return {
  23220. restrict: 'AC',
  23221. compile: function ngBindCompile(templateElement) {
  23222. $compile.$$addBindingClass(templateElement);
  23223. return function ngBindLink(scope, element, attr) {
  23224. $compile.$$addBindingInfo(element, attr.ngBind);
  23225. element = element[0];
  23226. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  23227. element.textContent = stringify(value);
  23228. });
  23229. };
  23230. }
  23231. };
  23232. }];
  23233. /**
  23234. * @ngdoc directive
  23235. * @name ngBindTemplate
  23236. *
  23237. * @description
  23238. * The `ngBindTemplate` directive specifies that the element
  23239. * text content should be replaced with the interpolation of the template
  23240. * in the `ngBindTemplate` attribute.
  23241. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  23242. * expressions. This directive is needed since some HTML elements
  23243. * (such as TITLE and OPTION) cannot contain SPAN elements.
  23244. *
  23245. * @element ANY
  23246. * @param {string} ngBindTemplate template of form
  23247. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  23248. *
  23249. * @example
  23250. * Try it here: enter text in text box and watch the greeting change.
  23251. <example module="bindExample" name="ng-bind-template">
  23252. <file name="index.html">
  23253. <script>
  23254. angular.module('bindExample', [])
  23255. .controller('ExampleController', ['$scope', function($scope) {
  23256. $scope.salutation = 'Hello';
  23257. $scope.name = 'World';
  23258. }]);
  23259. </script>
  23260. <div ng-controller="ExampleController">
  23261. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  23262. <label>Name: <input type="text" ng-model="name"></label><br>
  23263. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  23264. </div>
  23265. </file>
  23266. <file name="protractor.js" type="protractor">
  23267. it('should check ng-bind', function() {
  23268. var salutationElem = element(by.binding('salutation'));
  23269. var salutationInput = element(by.model('salutation'));
  23270. var nameInput = element(by.model('name'));
  23271. expect(salutationElem.getText()).toBe('Hello World!');
  23272. salutationInput.clear();
  23273. salutationInput.sendKeys('Greetings');
  23274. nameInput.clear();
  23275. nameInput.sendKeys('user');
  23276. expect(salutationElem.getText()).toBe('Greetings user!');
  23277. });
  23278. </file>
  23279. </example>
  23280. */
  23281. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  23282. return {
  23283. compile: function ngBindTemplateCompile(templateElement) {
  23284. $compile.$$addBindingClass(templateElement);
  23285. return function ngBindTemplateLink(scope, element, attr) {
  23286. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  23287. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  23288. element = element[0];
  23289. attr.$observe('ngBindTemplate', function(value) {
  23290. element.textContent = isUndefined(value) ? '' : value;
  23291. });
  23292. };
  23293. }
  23294. };
  23295. }];
  23296. /**
  23297. * @ngdoc directive
  23298. * @name ngBindHtml
  23299. *
  23300. * @description
  23301. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  23302. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  23303. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  23304. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  23305. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  23306. *
  23307. * You may also bypass sanitization for values you know are safe. To do so, bind to
  23308. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  23309. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  23310. *
  23311. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  23312. * will have an exception (instead of an exploit.)
  23313. *
  23314. * @element ANY
  23315. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  23316. *
  23317. * @example
  23318. <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
  23319. <file name="index.html">
  23320. <div ng-controller="ExampleController">
  23321. <p ng-bind-html="myHTML"></p>
  23322. </div>
  23323. </file>
  23324. <file name="script.js">
  23325. angular.module('bindHtmlExample', ['ngSanitize'])
  23326. .controller('ExampleController', ['$scope', function($scope) {
  23327. $scope.myHTML =
  23328. 'I am an <code>HTML</code>string with ' +
  23329. '<a href="#">links!</a> and other <em>stuff</em>';
  23330. }]);
  23331. </file>
  23332. <file name="protractor.js" type="protractor">
  23333. it('should check ng-bind-html', function() {
  23334. expect(element(by.binding('myHTML')).getText()).toBe(
  23335. 'I am an HTMLstring with links! and other stuff');
  23336. });
  23337. </file>
  23338. </example>
  23339. */
  23340. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  23341. return {
  23342. restrict: 'A',
  23343. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  23344. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  23345. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  23346. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  23347. return $sce.valueOf(val);
  23348. });
  23349. $compile.$$addBindingClass(tElement);
  23350. return function ngBindHtmlLink(scope, element, attr) {
  23351. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  23352. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  23353. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  23354. var value = ngBindHtmlGetter(scope);
  23355. element.html($sce.getTrustedHtml(value) || '');
  23356. });
  23357. };
  23358. }
  23359. };
  23360. }];
  23361. /**
  23362. * @ngdoc directive
  23363. * @name ngChange
  23364. *
  23365. * @description
  23366. * Evaluate the given expression when the user changes the input.
  23367. * The expression is evaluated immediately, unlike the JavaScript onchange event
  23368. * which only triggers at the end of a change (usually, when the user leaves the
  23369. * form element or presses the return key).
  23370. *
  23371. * The `ngChange` expression is only evaluated when a change in the input value causes
  23372. * a new value to be committed to the model.
  23373. *
  23374. * It will not be evaluated:
  23375. * * if the value returned from the `$parsers` transformation pipeline has not changed
  23376. * * if the input has continued to be invalid since the model will stay `null`
  23377. * * if the model is changed programmatically and not by a change to the input value
  23378. *
  23379. *
  23380. * Note, this directive requires `ngModel` to be present.
  23381. *
  23382. * @element input
  23383. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  23384. * in input value.
  23385. *
  23386. * @example
  23387. * <example name="ngChange-directive" module="changeExample">
  23388. * <file name="index.html">
  23389. * <script>
  23390. * angular.module('changeExample', [])
  23391. * .controller('ExampleController', ['$scope', function($scope) {
  23392. * $scope.counter = 0;
  23393. * $scope.change = function() {
  23394. * $scope.counter++;
  23395. * };
  23396. * }]);
  23397. * </script>
  23398. * <div ng-controller="ExampleController">
  23399. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  23400. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  23401. * <label for="ng-change-example2">Confirmed</label><br />
  23402. * <tt>debug = {{confirmed}}</tt><br/>
  23403. * <tt>counter = {{counter}}</tt><br/>
  23404. * </div>
  23405. * </file>
  23406. * <file name="protractor.js" type="protractor">
  23407. * var counter = element(by.binding('counter'));
  23408. * var debug = element(by.binding('confirmed'));
  23409. *
  23410. * it('should evaluate the expression if changing from view', function() {
  23411. * expect(counter.getText()).toContain('0');
  23412. *
  23413. * element(by.id('ng-change-example1')).click();
  23414. *
  23415. * expect(counter.getText()).toContain('1');
  23416. * expect(debug.getText()).toContain('true');
  23417. * });
  23418. *
  23419. * it('should not evaluate the expression if changing from model', function() {
  23420. * element(by.id('ng-change-example2')).click();
  23421. * expect(counter.getText()).toContain('0');
  23422. * expect(debug.getText()).toContain('true');
  23423. * });
  23424. * </file>
  23425. * </example>
  23426. */
  23427. var ngChangeDirective = valueFn({
  23428. restrict: 'A',
  23429. require: 'ngModel',
  23430. link: function(scope, element, attr, ctrl) {
  23431. ctrl.$viewChangeListeners.push(function() {
  23432. scope.$eval(attr.ngChange);
  23433. });
  23434. }
  23435. });
  23436. /* exported
  23437. ngClassDirective,
  23438. ngClassEvenDirective,
  23439. ngClassOddDirective
  23440. */
  23441. function classDirective(name, selector) {
  23442. name = 'ngClass' + name;
  23443. var indexWatchExpression;
  23444. return ['$parse', function($parse) {
  23445. return {
  23446. restrict: 'AC',
  23447. link: function(scope, element, attr) {
  23448. var expression = attr[name].trim();
  23449. var isOneTime = (expression.charAt(0) === ':') && (expression.charAt(1) === ':');
  23450. var watchInterceptor = isOneTime ? toFlatValue : toClassString;
  23451. var watchExpression = $parse(expression, watchInterceptor);
  23452. var watchAction = isOneTime ? ngClassOneTimeWatchAction : ngClassWatchAction;
  23453. var classCounts = element.data('$classCounts');
  23454. var oldModulo = true;
  23455. var oldClassString;
  23456. if (!classCounts) {
  23457. // Use createMap() to prevent class assumptions involving property
  23458. // names in Object.prototype
  23459. classCounts = createMap();
  23460. element.data('$classCounts', classCounts);
  23461. }
  23462. if (name !== 'ngClass') {
  23463. if (!indexWatchExpression) {
  23464. indexWatchExpression = $parse('$index', function moduloTwo($index) {
  23465. // eslint-disable-next-line no-bitwise
  23466. return $index & 1;
  23467. });
  23468. }
  23469. scope.$watch(indexWatchExpression, ngClassIndexWatchAction);
  23470. }
  23471. scope.$watch(watchExpression, watchAction, isOneTime);
  23472. function addClasses(classString) {
  23473. classString = digestClassCounts(split(classString), 1);
  23474. attr.$addClass(classString);
  23475. }
  23476. function removeClasses(classString) {
  23477. classString = digestClassCounts(split(classString), -1);
  23478. attr.$removeClass(classString);
  23479. }
  23480. function updateClasses(oldClassString, newClassString) {
  23481. var oldClassArray = split(oldClassString);
  23482. var newClassArray = split(newClassString);
  23483. var toRemoveArray = arrayDifference(oldClassArray, newClassArray);
  23484. var toAddArray = arrayDifference(newClassArray, oldClassArray);
  23485. var toRemoveString = digestClassCounts(toRemoveArray, -1);
  23486. var toAddString = digestClassCounts(toAddArray, 1);
  23487. attr.$addClass(toAddString);
  23488. attr.$removeClass(toRemoveString);
  23489. }
  23490. function digestClassCounts(classArray, count) {
  23491. var classesToUpdate = [];
  23492. forEach(classArray, function(className) {
  23493. if (count > 0 || classCounts[className]) {
  23494. classCounts[className] = (classCounts[className] || 0) + count;
  23495. if (classCounts[className] === +(count > 0)) {
  23496. classesToUpdate.push(className);
  23497. }
  23498. }
  23499. });
  23500. return classesToUpdate.join(' ');
  23501. }
  23502. function ngClassIndexWatchAction(newModulo) {
  23503. // This watch-action should run before the `ngClass[OneTime]WatchAction()`, thus it
  23504. // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the
  23505. // `ngClass[OneTime]WatchAction()` will update the classes.
  23506. if (newModulo === selector) {
  23507. addClasses(oldClassString);
  23508. } else {
  23509. removeClasses(oldClassString);
  23510. }
  23511. oldModulo = newModulo;
  23512. }
  23513. function ngClassOneTimeWatchAction(newClassValue) {
  23514. var newClassString = toClassString(newClassValue);
  23515. if (newClassString !== oldClassString) {
  23516. ngClassWatchAction(newClassString);
  23517. }
  23518. }
  23519. function ngClassWatchAction(newClassString) {
  23520. if (oldModulo === selector) {
  23521. updateClasses(oldClassString, newClassString);
  23522. }
  23523. oldClassString = newClassString;
  23524. }
  23525. }
  23526. };
  23527. }];
  23528. // Helpers
  23529. function arrayDifference(tokens1, tokens2) {
  23530. if (!tokens1 || !tokens1.length) return [];
  23531. if (!tokens2 || !tokens2.length) return tokens1;
  23532. var values = [];
  23533. outer:
  23534. for (var i = 0; i < tokens1.length; i++) {
  23535. var token = tokens1[i];
  23536. for (var j = 0; j < tokens2.length; j++) {
  23537. if (token === tokens2[j]) continue outer;
  23538. }
  23539. values.push(token);
  23540. }
  23541. return values;
  23542. }
  23543. function split(classString) {
  23544. return classString && classString.split(' ');
  23545. }
  23546. function toClassString(classValue) {
  23547. var classString = classValue;
  23548. if (isArray(classValue)) {
  23549. classString = classValue.map(toClassString).join(' ');
  23550. } else if (isObject(classValue)) {
  23551. classString = Object.keys(classValue).
  23552. filter(function(key) { return classValue[key]; }).
  23553. join(' ');
  23554. }
  23555. return classString;
  23556. }
  23557. function toFlatValue(classValue) {
  23558. var flatValue = classValue;
  23559. if (isArray(classValue)) {
  23560. flatValue = classValue.map(toFlatValue);
  23561. } else if (isObject(classValue)) {
  23562. var hasUndefined = false;
  23563. flatValue = Object.keys(classValue).filter(function(key) {
  23564. var value = classValue[key];
  23565. if (!hasUndefined && isUndefined(value)) {
  23566. hasUndefined = true;
  23567. }
  23568. return value;
  23569. });
  23570. if (hasUndefined) {
  23571. // Prevent the `oneTimeLiteralWatchInterceptor` from unregistering
  23572. // the watcher, by including at least one `undefined` value.
  23573. flatValue.push(undefined);
  23574. }
  23575. }
  23576. return flatValue;
  23577. }
  23578. }
  23579. /**
  23580. * @ngdoc directive
  23581. * @name ngClass
  23582. * @restrict AC
  23583. *
  23584. * @description
  23585. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  23586. * an expression that represents all classes to be added.
  23587. *
  23588. * The directive operates in three different ways, depending on which of three types the expression
  23589. * evaluates to:
  23590. *
  23591. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  23592. * names.
  23593. *
  23594. * 2. If the expression evaluates to an object, then for each key-value pair of the
  23595. * object with a truthy value the corresponding key is used as a class name.
  23596. *
  23597. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  23598. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  23599. * to give you more control over what CSS classes appear. See the code below for an example of this.
  23600. *
  23601. *
  23602. * The directive won't add duplicate classes if a particular class was already set.
  23603. *
  23604. * When the expression changes, the previously added classes are removed and only then are the
  23605. * new classes added.
  23606. *
  23607. * @knownIssue
  23608. * You should not use {@link guide/interpolation interpolation} in the value of the `class`
  23609. * attribute, when using the `ngClass` directive on the same element.
  23610. * See {@link guide/interpolation#known-issues here} for more info.
  23611. *
  23612. * @animations
  23613. * | Animation | Occurs |
  23614. * |----------------------------------|-------------------------------------|
  23615. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  23616. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  23617. *
  23618. * @element ANY
  23619. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  23620. * of the evaluation can be a string representing space delimited class
  23621. * names, an array, or a map of class names to boolean values. In the case of a map, the
  23622. * names of the properties whose values are truthy will be added as css classes to the
  23623. * element.
  23624. *
  23625. * @example Example that demonstrates basic bindings via ngClass directive.
  23626. <example name="ng-class">
  23627. <file name="index.html">
  23628. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  23629. <label>
  23630. <input type="checkbox" ng-model="deleted">
  23631. deleted (apply "strike" class)
  23632. </label><br>
  23633. <label>
  23634. <input type="checkbox" ng-model="important">
  23635. important (apply "bold" class)
  23636. </label><br>
  23637. <label>
  23638. <input type="checkbox" ng-model="error">
  23639. error (apply "has-error" class)
  23640. </label>
  23641. <hr>
  23642. <p ng-class="style">Using String Syntax</p>
  23643. <input type="text" ng-model="style"
  23644. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  23645. <hr>
  23646. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  23647. <input ng-model="style1"
  23648. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  23649. <input ng-model="style2"
  23650. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  23651. <input ng-model="style3"
  23652. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  23653. <hr>
  23654. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  23655. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  23656. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  23657. </file>
  23658. <file name="style.css">
  23659. .strike {
  23660. text-decoration: line-through;
  23661. }
  23662. .bold {
  23663. font-weight: bold;
  23664. }
  23665. .red {
  23666. color: red;
  23667. }
  23668. .has-error {
  23669. color: red;
  23670. background-color: yellow;
  23671. }
  23672. .orange {
  23673. color: orange;
  23674. }
  23675. </file>
  23676. <file name="protractor.js" type="protractor">
  23677. var ps = element.all(by.css('p'));
  23678. it('should let you toggle the class', function() {
  23679. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  23680. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  23681. element(by.model('important')).click();
  23682. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  23683. element(by.model('error')).click();
  23684. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  23685. });
  23686. it('should let you toggle string example', function() {
  23687. expect(ps.get(1).getAttribute('class')).toBe('');
  23688. element(by.model('style')).clear();
  23689. element(by.model('style')).sendKeys('red');
  23690. expect(ps.get(1).getAttribute('class')).toBe('red');
  23691. });
  23692. it('array example should have 3 classes', function() {
  23693. expect(ps.get(2).getAttribute('class')).toBe('');
  23694. element(by.model('style1')).sendKeys('bold');
  23695. element(by.model('style2')).sendKeys('strike');
  23696. element(by.model('style3')).sendKeys('red');
  23697. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  23698. });
  23699. it('array with map example should have 2 classes', function() {
  23700. expect(ps.last().getAttribute('class')).toBe('');
  23701. element(by.model('style4')).sendKeys('bold');
  23702. element(by.model('warning')).click();
  23703. expect(ps.last().getAttribute('class')).toBe('bold orange');
  23704. });
  23705. </file>
  23706. </example>
  23707. ## Animations
  23708. The example below demonstrates how to perform animations using ngClass.
  23709. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
  23710. <file name="index.html">
  23711. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  23712. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  23713. <br>
  23714. <span class="base-class" ng-class="myVar">Sample Text</span>
  23715. </file>
  23716. <file name="style.css">
  23717. .base-class {
  23718. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  23719. }
  23720. .base-class.my-class {
  23721. color: red;
  23722. font-size:3em;
  23723. }
  23724. </file>
  23725. <file name="protractor.js" type="protractor">
  23726. it('should check ng-class', function() {
  23727. expect(element(by.css('.base-class')).getAttribute('class')).not.
  23728. toMatch(/my-class/);
  23729. element(by.id('setbtn')).click();
  23730. expect(element(by.css('.base-class')).getAttribute('class')).
  23731. toMatch(/my-class/);
  23732. element(by.id('clearbtn')).click();
  23733. expect(element(by.css('.base-class')).getAttribute('class')).not.
  23734. toMatch(/my-class/);
  23735. });
  23736. </file>
  23737. </example>
  23738. ## ngClass and pre-existing CSS3 Transitions/Animations
  23739. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  23740. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  23741. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  23742. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  23743. {@link $animate#removeClass $animate.removeClass}.
  23744. */
  23745. var ngClassDirective = classDirective('', true);
  23746. /**
  23747. * @ngdoc directive
  23748. * @name ngClassOdd
  23749. * @restrict AC
  23750. *
  23751. * @description
  23752. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  23753. * {@link ng.directive:ngClass ngClass}, except they work in
  23754. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  23755. *
  23756. * This directive can be applied only within the scope of an
  23757. * {@link ng.directive:ngRepeat ngRepeat}.
  23758. *
  23759. * @element ANY
  23760. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  23761. * of the evaluation can be a string representing space delimited class names or an array.
  23762. *
  23763. * @example
  23764. <example name="ng-class-odd">
  23765. <file name="index.html">
  23766. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  23767. <li ng-repeat="name in names">
  23768. <span ng-class-odd="'odd'" ng-class-even="'even'">
  23769. {{name}}
  23770. </span>
  23771. </li>
  23772. </ol>
  23773. </file>
  23774. <file name="style.css">
  23775. .odd {
  23776. color: red;
  23777. }
  23778. .even {
  23779. color: blue;
  23780. }
  23781. </file>
  23782. <file name="protractor.js" type="protractor">
  23783. it('should check ng-class-odd and ng-class-even', function() {
  23784. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  23785. toMatch(/odd/);
  23786. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  23787. toMatch(/even/);
  23788. });
  23789. </file>
  23790. </example>
  23791. */
  23792. var ngClassOddDirective = classDirective('Odd', 0);
  23793. /**
  23794. * @ngdoc directive
  23795. * @name ngClassEven
  23796. * @restrict AC
  23797. *
  23798. * @description
  23799. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  23800. * {@link ng.directive:ngClass ngClass}, except they work in
  23801. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  23802. *
  23803. * This directive can be applied only within the scope of an
  23804. * {@link ng.directive:ngRepeat ngRepeat}.
  23805. *
  23806. * @element ANY
  23807. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  23808. * result of the evaluation can be a string representing space delimited class names or an array.
  23809. *
  23810. * @example
  23811. <example name="ng-class-even">
  23812. <file name="index.html">
  23813. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  23814. <li ng-repeat="name in names">
  23815. <span ng-class-odd="'odd'" ng-class-even="'even'">
  23816. {{name}} &nbsp; &nbsp; &nbsp;
  23817. </span>
  23818. </li>
  23819. </ol>
  23820. </file>
  23821. <file name="style.css">
  23822. .odd {
  23823. color: red;
  23824. }
  23825. .even {
  23826. color: blue;
  23827. }
  23828. </file>
  23829. <file name="protractor.js" type="protractor">
  23830. it('should check ng-class-odd and ng-class-even', function() {
  23831. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  23832. toMatch(/odd/);
  23833. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  23834. toMatch(/even/);
  23835. });
  23836. </file>
  23837. </example>
  23838. */
  23839. var ngClassEvenDirective = classDirective('Even', 1);
  23840. /**
  23841. * @ngdoc directive
  23842. * @name ngCloak
  23843. * @restrict AC
  23844. *
  23845. * @description
  23846. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  23847. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  23848. * directive to avoid the undesirable flicker effect caused by the html template display.
  23849. *
  23850. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  23851. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  23852. * of the browser view.
  23853. *
  23854. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  23855. * `angular.min.js`.
  23856. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  23857. *
  23858. * ```css
  23859. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  23860. * display: none !important;
  23861. * }
  23862. * ```
  23863. *
  23864. * When this css rule is loaded by the browser, all html elements (including their children) that
  23865. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  23866. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  23867. * the compiled element visible.
  23868. *
  23869. * For the best result, the `angular.js` script must be loaded in the head section of the html
  23870. * document; alternatively, the css rule above must be included in the external stylesheet of the
  23871. * application.
  23872. *
  23873. * @element ANY
  23874. *
  23875. * @example
  23876. <example name="ng-cloak">
  23877. <file name="index.html">
  23878. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  23879. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  23880. </file>
  23881. <file name="protractor.js" type="protractor">
  23882. it('should remove the template directive and css class', function() {
  23883. expect($('#template1').getAttribute('ng-cloak')).
  23884. toBeNull();
  23885. expect($('#template2').getAttribute('ng-cloak')).
  23886. toBeNull();
  23887. });
  23888. </file>
  23889. </example>
  23890. *
  23891. */
  23892. var ngCloakDirective = ngDirective({
  23893. compile: function(element, attr) {
  23894. attr.$set('ngCloak', undefined);
  23895. element.removeClass('ng-cloak');
  23896. }
  23897. });
  23898. /**
  23899. * @ngdoc directive
  23900. * @name ngController
  23901. *
  23902. * @description
  23903. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  23904. * supports the principles behind the Model-View-Controller design pattern.
  23905. *
  23906. * MVC components in angular:
  23907. *
  23908. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  23909. * are accessed through bindings.
  23910. * * View — The template (HTML with data bindings) that is rendered into the View.
  23911. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  23912. * logic behind the application to decorate the scope with functions and values
  23913. *
  23914. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  23915. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  23916. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  23917. * and executed twice.
  23918. *
  23919. * @element ANY
  23920. * @scope
  23921. * @priority 500
  23922. * @param {expression} ngController Name of a constructor function registered with the current
  23923. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  23924. * that on the current scope evaluates to a constructor function.
  23925. *
  23926. * The controller instance can be published into a scope property by specifying
  23927. * `ng-controller="as propertyName"`.
  23928. *
  23929. * If the current `$controllerProvider` is configured to use globals (via
  23930. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  23931. * also be the name of a globally accessible constructor function (deprecated, not recommended).
  23932. *
  23933. * @example
  23934. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  23935. * greeting are methods declared on the controller (see source tab). These methods can
  23936. * easily be called from the angular markup. Any changes to the data are automatically reflected
  23937. * in the View without the need for a manual update.
  23938. *
  23939. * Two different declaration styles are included below:
  23940. *
  23941. * * one binds methods and properties directly onto the controller using `this`:
  23942. * `ng-controller="SettingsController1 as settings"`
  23943. * * one injects `$scope` into the controller:
  23944. * `ng-controller="SettingsController2"`
  23945. *
  23946. * The second option is more common in the Angular community, and is generally used in boilerplates
  23947. * and in this guide. However, there are advantages to binding properties directly to the controller
  23948. * and avoiding scope.
  23949. *
  23950. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  23951. * multiple controllers apply to an element.
  23952. * * If you are writing your controllers as classes you have easier access to the properties and
  23953. * methods, which will appear on the scope, from inside the controller code.
  23954. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  23955. * inheritance masking primitives.
  23956. *
  23957. * This example demonstrates the `controller as` syntax.
  23958. *
  23959. * <example name="ngControllerAs" module="controllerAsExample">
  23960. * <file name="index.html">
  23961. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  23962. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  23963. * <button ng-click="settings.greet()">greet</button><br/>
  23964. * Contact:
  23965. * <ul>
  23966. * <li ng-repeat="contact in settings.contacts">
  23967. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  23968. * <option>phone</option>
  23969. * <option>email</option>
  23970. * </select>
  23971. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  23972. * <button ng-click="settings.clearContact(contact)">clear</button>
  23973. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  23974. * </li>
  23975. * <li><button ng-click="settings.addContact()">add</button></li>
  23976. * </ul>
  23977. * </div>
  23978. * </file>
  23979. * <file name="app.js">
  23980. * angular.module('controllerAsExample', [])
  23981. * .controller('SettingsController1', SettingsController1);
  23982. *
  23983. * function SettingsController1() {
  23984. * this.name = 'John Smith';
  23985. * this.contacts = [
  23986. * {type: 'phone', value: '408 555 1212'},
  23987. * {type: 'email', value: 'john.smith@example.org'}
  23988. * ];
  23989. * }
  23990. *
  23991. * SettingsController1.prototype.greet = function() {
  23992. * alert(this.name);
  23993. * };
  23994. *
  23995. * SettingsController1.prototype.addContact = function() {
  23996. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  23997. * };
  23998. *
  23999. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  24000. * var index = this.contacts.indexOf(contactToRemove);
  24001. * this.contacts.splice(index, 1);
  24002. * };
  24003. *
  24004. * SettingsController1.prototype.clearContact = function(contact) {
  24005. * contact.type = 'phone';
  24006. * contact.value = '';
  24007. * };
  24008. * </file>
  24009. * <file name="protractor.js" type="protractor">
  24010. * it('should check controller as', function() {
  24011. * var container = element(by.id('ctrl-as-exmpl'));
  24012. * expect(container.element(by.model('settings.name'))
  24013. * .getAttribute('value')).toBe('John Smith');
  24014. *
  24015. * var firstRepeat =
  24016. * container.element(by.repeater('contact in settings.contacts').row(0));
  24017. * var secondRepeat =
  24018. * container.element(by.repeater('contact in settings.contacts').row(1));
  24019. *
  24020. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24021. * .toBe('408 555 1212');
  24022. *
  24023. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24024. * .toBe('john.smith@example.org');
  24025. *
  24026. * firstRepeat.element(by.buttonText('clear')).click();
  24027. *
  24028. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24029. * .toBe('');
  24030. *
  24031. * container.element(by.buttonText('add')).click();
  24032. *
  24033. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  24034. * .element(by.model('contact.value'))
  24035. * .getAttribute('value'))
  24036. * .toBe('yourname@example.org');
  24037. * });
  24038. * </file>
  24039. * </example>
  24040. *
  24041. * This example demonstrates the "attach to `$scope`" style of controller.
  24042. *
  24043. * <example name="ngController" module="controllerExample">
  24044. * <file name="index.html">
  24045. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  24046. * <label>Name: <input type="text" ng-model="name"/></label>
  24047. * <button ng-click="greet()">greet</button><br/>
  24048. * Contact:
  24049. * <ul>
  24050. * <li ng-repeat="contact in contacts">
  24051. * <select ng-model="contact.type" id="select_{{$index}}">
  24052. * <option>phone</option>
  24053. * <option>email</option>
  24054. * </select>
  24055. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24056. * <button ng-click="clearContact(contact)">clear</button>
  24057. * <button ng-click="removeContact(contact)">X</button>
  24058. * </li>
  24059. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  24060. * </ul>
  24061. * </div>
  24062. * </file>
  24063. * <file name="app.js">
  24064. * angular.module('controllerExample', [])
  24065. * .controller('SettingsController2', ['$scope', SettingsController2]);
  24066. *
  24067. * function SettingsController2($scope) {
  24068. * $scope.name = 'John Smith';
  24069. * $scope.contacts = [
  24070. * {type:'phone', value:'408 555 1212'},
  24071. * {type:'email', value:'john.smith@example.org'}
  24072. * ];
  24073. *
  24074. * $scope.greet = function() {
  24075. * alert($scope.name);
  24076. * };
  24077. *
  24078. * $scope.addContact = function() {
  24079. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  24080. * };
  24081. *
  24082. * $scope.removeContact = function(contactToRemove) {
  24083. * var index = $scope.contacts.indexOf(contactToRemove);
  24084. * $scope.contacts.splice(index, 1);
  24085. * };
  24086. *
  24087. * $scope.clearContact = function(contact) {
  24088. * contact.type = 'phone';
  24089. * contact.value = '';
  24090. * };
  24091. * }
  24092. * </file>
  24093. * <file name="protractor.js" type="protractor">
  24094. * it('should check controller', function() {
  24095. * var container = element(by.id('ctrl-exmpl'));
  24096. *
  24097. * expect(container.element(by.model('name'))
  24098. * .getAttribute('value')).toBe('John Smith');
  24099. *
  24100. * var firstRepeat =
  24101. * container.element(by.repeater('contact in contacts').row(0));
  24102. * var secondRepeat =
  24103. * container.element(by.repeater('contact in contacts').row(1));
  24104. *
  24105. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24106. * .toBe('408 555 1212');
  24107. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24108. * .toBe('john.smith@example.org');
  24109. *
  24110. * firstRepeat.element(by.buttonText('clear')).click();
  24111. *
  24112. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24113. * .toBe('');
  24114. *
  24115. * container.element(by.buttonText('add')).click();
  24116. *
  24117. * expect(container.element(by.repeater('contact in contacts').row(2))
  24118. * .element(by.model('contact.value'))
  24119. * .getAttribute('value'))
  24120. * .toBe('yourname@example.org');
  24121. * });
  24122. * </file>
  24123. *</example>
  24124. */
  24125. var ngControllerDirective = [function() {
  24126. return {
  24127. restrict: 'A',
  24128. scope: true,
  24129. controller: '@',
  24130. priority: 500
  24131. };
  24132. }];
  24133. /**
  24134. * @ngdoc directive
  24135. * @name ngCsp
  24136. *
  24137. * @restrict A
  24138. * @element ANY
  24139. * @description
  24140. *
  24141. * Angular has some features that can conflict with certain restrictions that are applied when using
  24142. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  24143. *
  24144. * If you intend to implement CSP with these rules then you must tell Angular not to use these
  24145. * features.
  24146. *
  24147. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  24148. *
  24149. *
  24150. * The following default rules in CSP affect Angular:
  24151. *
  24152. * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute
  24153. * code from strings is forbidden. Angular makes use of this in the {@link $parse} service to
  24154. * provide a 30% increase in the speed of evaluating Angular expressions. (This CSP rule can be
  24155. * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would
  24156. * weaken the protections offered by CSP.)
  24157. *
  24158. * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden.
  24159. * This prevents apps from injecting custom styles directly into the document. Angular makes use of
  24160. * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these
  24161. * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css`
  24162. * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but
  24163. * it is generally not recommended as it would weaken the protections offered by CSP.)
  24164. *
  24165. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking dynamic code
  24166. * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically
  24167. * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a
  24168. * CSP error to be logged in the console:
  24169. *
  24170. * ```
  24171. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  24172. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  24173. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  24174. * ```
  24175. *
  24176. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  24177. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  24178. * the `angular.js` file.
  24179. *
  24180. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  24181. *
  24182. * You can specify which of the CSP related Angular features should be deactivated by providing
  24183. * a value for the `ng-csp` attribute. The options are as follows:
  24184. *
  24185. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  24186. *
  24187. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  24188. *
  24189. * You can use these values in the following combinations:
  24190. *
  24191. *
  24192. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  24193. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous
  24194. * versions of Angular.
  24195. *
  24196. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  24197. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous
  24198. * versions of Angular.
  24199. *
  24200. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can
  24201. * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  24202. *
  24203. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  24204. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  24205. *
  24206. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  24207. * styles nor use eval, which is the same as an empty: ng-csp.
  24208. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  24209. *
  24210. * @example
  24211. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  24212. ```html
  24213. <!doctype html>
  24214. <html ng-app ng-csp>
  24215. ...
  24216. ...
  24217. </html>
  24218. ```
  24219. * @example
  24220. <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! -->
  24221. <example name="example.csp" module="cspExample" ng-csp="true">
  24222. <file name="index.html">
  24223. <div ng-controller="MainController as ctrl">
  24224. <div>
  24225. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  24226. <span id="counter">
  24227. {{ctrl.counter}}
  24228. </span>
  24229. </div>
  24230. <div>
  24231. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  24232. <span id="evilError">
  24233. {{ctrl.evilError}}
  24234. </span>
  24235. </div>
  24236. </div>
  24237. </file>
  24238. <file name="script.js">
  24239. angular.module('cspExample', [])
  24240. .controller('MainController', function MainController() {
  24241. this.counter = 0;
  24242. this.inc = function() {
  24243. this.counter++;
  24244. };
  24245. this.evil = function() {
  24246. try {
  24247. eval('1+2'); // eslint-disable-line no-eval
  24248. } catch (e) {
  24249. this.evilError = e.message;
  24250. }
  24251. };
  24252. });
  24253. </file>
  24254. <file name="protractor.js" type="protractor">
  24255. var util, webdriver;
  24256. var incBtn = element(by.id('inc'));
  24257. var counter = element(by.id('counter'));
  24258. var evilBtn = element(by.id('evil'));
  24259. var evilError = element(by.id('evilError'));
  24260. function getAndClearSevereErrors() {
  24261. return browser.manage().logs().get('browser').then(function(browserLog) {
  24262. return browserLog.filter(function(logEntry) {
  24263. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  24264. });
  24265. });
  24266. }
  24267. function clearErrors() {
  24268. getAndClearSevereErrors();
  24269. }
  24270. function expectNoErrors() {
  24271. getAndClearSevereErrors().then(function(filteredLog) {
  24272. expect(filteredLog.length).toEqual(0);
  24273. if (filteredLog.length) {
  24274. console.log('browser console errors: ' + util.inspect(filteredLog));
  24275. }
  24276. });
  24277. }
  24278. function expectError(regex) {
  24279. getAndClearSevereErrors().then(function(filteredLog) {
  24280. var found = false;
  24281. filteredLog.forEach(function(log) {
  24282. if (log.message.match(regex)) {
  24283. found = true;
  24284. }
  24285. });
  24286. if (!found) {
  24287. throw new Error('expected an error that matches ' + regex);
  24288. }
  24289. });
  24290. }
  24291. beforeEach(function() {
  24292. util = require('util');
  24293. webdriver = require('selenium-webdriver');
  24294. });
  24295. // For now, we only test on Chrome,
  24296. // as Safari does not load the page with Protractor's injected scripts,
  24297. // and Firefox webdriver always disables content security policy (#6358)
  24298. if (browser.params.browser !== 'chrome') {
  24299. return;
  24300. }
  24301. it('should not report errors when the page is loaded', function() {
  24302. // clear errors so we are not dependent on previous tests
  24303. clearErrors();
  24304. // Need to reload the page as the page is already loaded when
  24305. // we come here
  24306. browser.driver.getCurrentUrl().then(function(url) {
  24307. browser.get(url);
  24308. });
  24309. expectNoErrors();
  24310. });
  24311. it('should evaluate expressions', function() {
  24312. expect(counter.getText()).toEqual('0');
  24313. incBtn.click();
  24314. expect(counter.getText()).toEqual('1');
  24315. expectNoErrors();
  24316. });
  24317. it('should throw and report an error when using "eval"', function() {
  24318. evilBtn.click();
  24319. expect(evilError.getText()).toMatch(/Content Security Policy/);
  24320. expectError(/Content Security Policy/);
  24321. });
  24322. </file>
  24323. </example>
  24324. */
  24325. // `ngCsp` is not implemented as a proper directive any more, because we need it be processed while
  24326. // we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()`
  24327. // fn that looks for the `ng-csp` attribute anywhere in the current doc.
  24328. /**
  24329. * @ngdoc directive
  24330. * @name ngClick
  24331. *
  24332. * @description
  24333. * The ngClick directive allows you to specify custom behavior when
  24334. * an element is clicked.
  24335. *
  24336. * @element ANY
  24337. * @priority 0
  24338. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  24339. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  24340. *
  24341. * @example
  24342. <example name="ng-click">
  24343. <file name="index.html">
  24344. <button ng-click="count = count + 1" ng-init="count=0">
  24345. Increment
  24346. </button>
  24347. <span>
  24348. count: {{count}}
  24349. </span>
  24350. </file>
  24351. <file name="protractor.js" type="protractor">
  24352. it('should check ng-click', function() {
  24353. expect(element(by.binding('count')).getText()).toMatch('0');
  24354. element(by.css('button')).click();
  24355. expect(element(by.binding('count')).getText()).toMatch('1');
  24356. });
  24357. </file>
  24358. </example>
  24359. */
  24360. /*
  24361. * A collection of directives that allows creation of custom event handlers that are defined as
  24362. * angular expressions and are compiled and executed within the current scope.
  24363. */
  24364. var ngEventDirectives = {};
  24365. // For events that might fire synchronously during DOM manipulation
  24366. // we need to execute their event handlers asynchronously using $evalAsync,
  24367. // so that they are not executed in an inconsistent state.
  24368. var forceAsyncEvents = {
  24369. 'blur': true,
  24370. 'focus': true
  24371. };
  24372. forEach(
  24373. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  24374. function(eventName) {
  24375. var directiveName = directiveNormalize('ng-' + eventName);
  24376. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  24377. return {
  24378. restrict: 'A',
  24379. compile: function($element, attr) {
  24380. // NOTE:
  24381. // We expose the powerful `$event` object on the scope that provides access to the Window,
  24382. // etc. This is OK, because expressions are not sandboxed any more (and the expression
  24383. // sandbox was never meant to be a security feature anyway).
  24384. var fn = $parse(attr[directiveName]);
  24385. return function ngEventHandler(scope, element) {
  24386. element.on(eventName, function(event) {
  24387. var callback = function() {
  24388. fn(scope, {$event: event});
  24389. };
  24390. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  24391. scope.$evalAsync(callback);
  24392. } else {
  24393. scope.$apply(callback);
  24394. }
  24395. });
  24396. };
  24397. }
  24398. };
  24399. }];
  24400. }
  24401. );
  24402. /**
  24403. * @ngdoc directive
  24404. * @name ngDblclick
  24405. *
  24406. * @description
  24407. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  24408. *
  24409. * @element ANY
  24410. * @priority 0
  24411. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  24412. * a dblclick. (The Event object is available as `$event`)
  24413. *
  24414. * @example
  24415. <example name="ng-dblclick">
  24416. <file name="index.html">
  24417. <button ng-dblclick="count = count + 1" ng-init="count=0">
  24418. Increment (on double click)
  24419. </button>
  24420. count: {{count}}
  24421. </file>
  24422. </example>
  24423. */
  24424. /**
  24425. * @ngdoc directive
  24426. * @name ngMousedown
  24427. *
  24428. * @description
  24429. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  24430. *
  24431. * @element ANY
  24432. * @priority 0
  24433. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  24434. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  24435. *
  24436. * @example
  24437. <example name="ng-mousedown">
  24438. <file name="index.html">
  24439. <button ng-mousedown="count = count + 1" ng-init="count=0">
  24440. Increment (on mouse down)
  24441. </button>
  24442. count: {{count}}
  24443. </file>
  24444. </example>
  24445. */
  24446. /**
  24447. * @ngdoc directive
  24448. * @name ngMouseup
  24449. *
  24450. * @description
  24451. * Specify custom behavior on mouseup event.
  24452. *
  24453. * @element ANY
  24454. * @priority 0
  24455. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  24456. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  24457. *
  24458. * @example
  24459. <example name="ng-mouseup">
  24460. <file name="index.html">
  24461. <button ng-mouseup="count = count + 1" ng-init="count=0">
  24462. Increment (on mouse up)
  24463. </button>
  24464. count: {{count}}
  24465. </file>
  24466. </example>
  24467. */
  24468. /**
  24469. * @ngdoc directive
  24470. * @name ngMouseover
  24471. *
  24472. * @description
  24473. * Specify custom behavior on mouseover event.
  24474. *
  24475. * @element ANY
  24476. * @priority 0
  24477. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  24478. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  24479. *
  24480. * @example
  24481. <example name="ng-mouseover">
  24482. <file name="index.html">
  24483. <button ng-mouseover="count = count + 1" ng-init="count=0">
  24484. Increment (when mouse is over)
  24485. </button>
  24486. count: {{count}}
  24487. </file>
  24488. </example>
  24489. */
  24490. /**
  24491. * @ngdoc directive
  24492. * @name ngMouseenter
  24493. *
  24494. * @description
  24495. * Specify custom behavior on mouseenter event.
  24496. *
  24497. * @element ANY
  24498. * @priority 0
  24499. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  24500. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  24501. *
  24502. * @example
  24503. <example name="ng-mouseenter">
  24504. <file name="index.html">
  24505. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  24506. Increment (when mouse enters)
  24507. </button>
  24508. count: {{count}}
  24509. </file>
  24510. </example>
  24511. */
  24512. /**
  24513. * @ngdoc directive
  24514. * @name ngMouseleave
  24515. *
  24516. * @description
  24517. * Specify custom behavior on mouseleave event.
  24518. *
  24519. * @element ANY
  24520. * @priority 0
  24521. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  24522. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  24523. *
  24524. * @example
  24525. <example name="ng-mouseleave">
  24526. <file name="index.html">
  24527. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  24528. Increment (when mouse leaves)
  24529. </button>
  24530. count: {{count}}
  24531. </file>
  24532. </example>
  24533. */
  24534. /**
  24535. * @ngdoc directive
  24536. * @name ngMousemove
  24537. *
  24538. * @description
  24539. * Specify custom behavior on mousemove event.
  24540. *
  24541. * @element ANY
  24542. * @priority 0
  24543. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  24544. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  24545. *
  24546. * @example
  24547. <example name="ng-mousemove">
  24548. <file name="index.html">
  24549. <button ng-mousemove="count = count + 1" ng-init="count=0">
  24550. Increment (when mouse moves)
  24551. </button>
  24552. count: {{count}}
  24553. </file>
  24554. </example>
  24555. */
  24556. /**
  24557. * @ngdoc directive
  24558. * @name ngKeydown
  24559. *
  24560. * @description
  24561. * Specify custom behavior on keydown event.
  24562. *
  24563. * @element ANY
  24564. * @priority 0
  24565. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  24566. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  24567. *
  24568. * @example
  24569. <example name="ng-keydown">
  24570. <file name="index.html">
  24571. <input ng-keydown="count = count + 1" ng-init="count=0">
  24572. key down count: {{count}}
  24573. </file>
  24574. </example>
  24575. */
  24576. /**
  24577. * @ngdoc directive
  24578. * @name ngKeyup
  24579. *
  24580. * @description
  24581. * Specify custom behavior on keyup event.
  24582. *
  24583. * @element ANY
  24584. * @priority 0
  24585. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  24586. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  24587. *
  24588. * @example
  24589. <example name="ng-keyup">
  24590. <file name="index.html">
  24591. <p>Typing in the input box below updates the key count</p>
  24592. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  24593. <p>Typing in the input box below updates the keycode</p>
  24594. <input ng-keyup="event=$event">
  24595. <p>event keyCode: {{ event.keyCode }}</p>
  24596. <p>event altKey: {{ event.altKey }}</p>
  24597. </file>
  24598. </example>
  24599. */
  24600. /**
  24601. * @ngdoc directive
  24602. * @name ngKeypress
  24603. *
  24604. * @description
  24605. * Specify custom behavior on keypress event.
  24606. *
  24607. * @element ANY
  24608. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  24609. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  24610. * and can be interrogated for keyCode, altKey, etc.)
  24611. *
  24612. * @example
  24613. <example name="ng-keypress">
  24614. <file name="index.html">
  24615. <input ng-keypress="count = count + 1" ng-init="count=0">
  24616. key press count: {{count}}
  24617. </file>
  24618. </example>
  24619. */
  24620. /**
  24621. * @ngdoc directive
  24622. * @name ngSubmit
  24623. *
  24624. * @description
  24625. * Enables binding angular expressions to onsubmit events.
  24626. *
  24627. * Additionally it prevents the default action (which for form means sending the request to the
  24628. * server and reloading the current page), but only if the form does not contain `action`,
  24629. * `data-action`, or `x-action` attributes.
  24630. *
  24631. * <div class="alert alert-warning">
  24632. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  24633. * `ngSubmit` handlers together. See the
  24634. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  24635. * for a detailed discussion of when `ngSubmit` may be triggered.
  24636. * </div>
  24637. *
  24638. * @element form
  24639. * @priority 0
  24640. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  24641. * ({@link guide/expression#-event- Event object is available as `$event`})
  24642. *
  24643. * @example
  24644. <example module="submitExample" name="ng-submit">
  24645. <file name="index.html">
  24646. <script>
  24647. angular.module('submitExample', [])
  24648. .controller('ExampleController', ['$scope', function($scope) {
  24649. $scope.list = [];
  24650. $scope.text = 'hello';
  24651. $scope.submit = function() {
  24652. if ($scope.text) {
  24653. $scope.list.push(this.text);
  24654. $scope.text = '';
  24655. }
  24656. };
  24657. }]);
  24658. </script>
  24659. <form ng-submit="submit()" ng-controller="ExampleController">
  24660. Enter text and hit enter:
  24661. <input type="text" ng-model="text" name="text" />
  24662. <input type="submit" id="submit" value="Submit" />
  24663. <pre>list={{list}}</pre>
  24664. </form>
  24665. </file>
  24666. <file name="protractor.js" type="protractor">
  24667. it('should check ng-submit', function() {
  24668. expect(element(by.binding('list')).getText()).toBe('list=[]');
  24669. element(by.css('#submit')).click();
  24670. expect(element(by.binding('list')).getText()).toContain('hello');
  24671. expect(element(by.model('text')).getAttribute('value')).toBe('');
  24672. });
  24673. it('should ignore empty strings', function() {
  24674. expect(element(by.binding('list')).getText()).toBe('list=[]');
  24675. element(by.css('#submit')).click();
  24676. element(by.css('#submit')).click();
  24677. expect(element(by.binding('list')).getText()).toContain('hello');
  24678. });
  24679. </file>
  24680. </example>
  24681. */
  24682. /**
  24683. * @ngdoc directive
  24684. * @name ngFocus
  24685. *
  24686. * @description
  24687. * Specify custom behavior on focus event.
  24688. *
  24689. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  24690. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  24691. * during an `$apply` to ensure a consistent state.
  24692. *
  24693. * @element window, input, select, textarea, a
  24694. * @priority 0
  24695. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  24696. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  24697. *
  24698. * @example
  24699. * See {@link ng.directive:ngClick ngClick}
  24700. */
  24701. /**
  24702. * @ngdoc directive
  24703. * @name ngBlur
  24704. *
  24705. * @description
  24706. * Specify custom behavior on blur event.
  24707. *
  24708. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  24709. * an element has lost focus.
  24710. *
  24711. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  24712. * (e.g. removing a focussed input),
  24713. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  24714. * during an `$apply` to ensure a consistent state.
  24715. *
  24716. * @element window, input, select, textarea, a
  24717. * @priority 0
  24718. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  24719. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  24720. *
  24721. * @example
  24722. * See {@link ng.directive:ngClick ngClick}
  24723. */
  24724. /**
  24725. * @ngdoc directive
  24726. * @name ngCopy
  24727. *
  24728. * @description
  24729. * Specify custom behavior on copy event.
  24730. *
  24731. * @element window, input, select, textarea, a
  24732. * @priority 0
  24733. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  24734. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  24735. *
  24736. * @example
  24737. <example name="ng-copy">
  24738. <file name="index.html">
  24739. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  24740. copied: {{copied}}
  24741. </file>
  24742. </example>
  24743. */
  24744. /**
  24745. * @ngdoc directive
  24746. * @name ngCut
  24747. *
  24748. * @description
  24749. * Specify custom behavior on cut event.
  24750. *
  24751. * @element window, input, select, textarea, a
  24752. * @priority 0
  24753. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  24754. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  24755. *
  24756. * @example
  24757. <example name="ng-cut">
  24758. <file name="index.html">
  24759. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  24760. cut: {{cut}}
  24761. </file>
  24762. </example>
  24763. */
  24764. /**
  24765. * @ngdoc directive
  24766. * @name ngPaste
  24767. *
  24768. * @description
  24769. * Specify custom behavior on paste event.
  24770. *
  24771. * @element window, input, select, textarea, a
  24772. * @priority 0
  24773. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  24774. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  24775. *
  24776. * @example
  24777. <example name="ng-paste">
  24778. <file name="index.html">
  24779. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  24780. pasted: {{paste}}
  24781. </file>
  24782. </example>
  24783. */
  24784. /**
  24785. * @ngdoc directive
  24786. * @name ngIf
  24787. * @restrict A
  24788. * @multiElement
  24789. *
  24790. * @description
  24791. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  24792. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  24793. * value then the element is removed from the DOM, otherwise a clone of the
  24794. * element is reinserted into the DOM.
  24795. *
  24796. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  24797. * element in the DOM rather than changing its visibility via the `display` css property. A common
  24798. * case when this difference is significant is when using css selectors that rely on an element's
  24799. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  24800. *
  24801. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  24802. * is created when the element is restored. The scope created within `ngIf` inherits from
  24803. * its parent scope using
  24804. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  24805. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  24806. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  24807. * variable within the child scope will override (hide) the value in the parent scope.
  24808. *
  24809. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  24810. * is if an element's class attribute is directly modified after it's compiled, using something like
  24811. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  24812. * the added class will be lost because the original compiled state is used to regenerate the element.
  24813. *
  24814. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  24815. * and `leave` effects.
  24816. *
  24817. * @animations
  24818. * | Animation | Occurs |
  24819. * |----------------------------------|-------------------------------------|
  24820. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  24821. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  24822. *
  24823. * @element ANY
  24824. * @scope
  24825. * @priority 600
  24826. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  24827. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  24828. * element is added to the DOM tree.
  24829. *
  24830. * @example
  24831. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
  24832. <file name="index.html">
  24833. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  24834. Show when checked:
  24835. <span ng-if="checked" class="animate-if">
  24836. This is removed when the checkbox is unchecked.
  24837. </span>
  24838. </file>
  24839. <file name="animations.css">
  24840. .animate-if {
  24841. background:white;
  24842. border:1px solid black;
  24843. padding:10px;
  24844. }
  24845. .animate-if.ng-enter, .animate-if.ng-leave {
  24846. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24847. }
  24848. .animate-if.ng-enter,
  24849. .animate-if.ng-leave.ng-leave-active {
  24850. opacity:0;
  24851. }
  24852. .animate-if.ng-leave,
  24853. .animate-if.ng-enter.ng-enter-active {
  24854. opacity:1;
  24855. }
  24856. </file>
  24857. </example>
  24858. */
  24859. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  24860. return {
  24861. multiElement: true,
  24862. transclude: 'element',
  24863. priority: 600,
  24864. terminal: true,
  24865. restrict: 'A',
  24866. $$tlb: true,
  24867. link: function($scope, $element, $attr, ctrl, $transclude) {
  24868. var block, childScope, previousElements;
  24869. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  24870. if (value) {
  24871. if (!childScope) {
  24872. $transclude(function(clone, newScope) {
  24873. childScope = newScope;
  24874. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  24875. // Note: We only need the first/last node of the cloned nodes.
  24876. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  24877. // by a directive with templateUrl when its template arrives.
  24878. block = {
  24879. clone: clone
  24880. };
  24881. $animate.enter(clone, $element.parent(), $element);
  24882. });
  24883. }
  24884. } else {
  24885. if (previousElements) {
  24886. previousElements.remove();
  24887. previousElements = null;
  24888. }
  24889. if (childScope) {
  24890. childScope.$destroy();
  24891. childScope = null;
  24892. }
  24893. if (block) {
  24894. previousElements = getBlockNodes(block.clone);
  24895. $animate.leave(previousElements).done(function(response) {
  24896. if (response !== false) previousElements = null;
  24897. });
  24898. block = null;
  24899. }
  24900. }
  24901. });
  24902. }
  24903. };
  24904. }];
  24905. /**
  24906. * @ngdoc directive
  24907. * @name ngInclude
  24908. * @restrict ECA
  24909. *
  24910. * @description
  24911. * Fetches, compiles and includes an external HTML fragment.
  24912. *
  24913. * By default, the template URL is restricted to the same domain and protocol as the
  24914. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  24915. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  24916. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  24917. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  24918. * ng.$sce Strict Contextual Escaping}.
  24919. *
  24920. * In addition, the browser's
  24921. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  24922. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  24923. * policy may further restrict whether the template is successfully loaded.
  24924. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  24925. * access on some browsers.
  24926. *
  24927. * @animations
  24928. * | Animation | Occurs |
  24929. * |----------------------------------|-------------------------------------|
  24930. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  24931. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  24932. *
  24933. * The enter and leave animation occur concurrently.
  24934. *
  24935. * @scope
  24936. * @priority 400
  24937. *
  24938. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  24939. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  24940. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  24941. * <div class="alert alert-warning">
  24942. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  24943. * a function with the name on the window element, which will usually throw a
  24944. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  24945. * different form that {@link guide/directive#normalization matches} `onload`.
  24946. * </div>
  24947. *
  24948. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  24949. * $anchorScroll} to scroll the viewport after the content is loaded.
  24950. *
  24951. * - If the attribute is not set, disable scrolling.
  24952. * - If the attribute is set without value, enable scrolling.
  24953. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  24954. *
  24955. * @example
  24956. <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
  24957. <file name="index.html">
  24958. <div ng-controller="ExampleController">
  24959. <select ng-model="template" ng-options="t.name for t in templates">
  24960. <option value="">(blank)</option>
  24961. </select>
  24962. url of the template: <code>{{template.url}}</code>
  24963. <hr/>
  24964. <div class="slide-animate-container">
  24965. <div class="slide-animate" ng-include="template.url"></div>
  24966. </div>
  24967. </div>
  24968. </file>
  24969. <file name="script.js">
  24970. angular.module('includeExample', ['ngAnimate'])
  24971. .controller('ExampleController', ['$scope', function($scope) {
  24972. $scope.templates =
  24973. [{ name: 'template1.html', url: 'template1.html'},
  24974. { name: 'template2.html', url: 'template2.html'}];
  24975. $scope.template = $scope.templates[0];
  24976. }]);
  24977. </file>
  24978. <file name="template1.html">
  24979. Content of template1.html
  24980. </file>
  24981. <file name="template2.html">
  24982. Content of template2.html
  24983. </file>
  24984. <file name="animations.css">
  24985. .slide-animate-container {
  24986. position:relative;
  24987. background:white;
  24988. border:1px solid black;
  24989. height:40px;
  24990. overflow:hidden;
  24991. }
  24992. .slide-animate {
  24993. padding:10px;
  24994. }
  24995. .slide-animate.ng-enter, .slide-animate.ng-leave {
  24996. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24997. position:absolute;
  24998. top:0;
  24999. left:0;
  25000. right:0;
  25001. bottom:0;
  25002. display:block;
  25003. padding:10px;
  25004. }
  25005. .slide-animate.ng-enter {
  25006. top:-50px;
  25007. }
  25008. .slide-animate.ng-enter.ng-enter-active {
  25009. top:0;
  25010. }
  25011. .slide-animate.ng-leave {
  25012. top:0;
  25013. }
  25014. .slide-animate.ng-leave.ng-leave-active {
  25015. top:50px;
  25016. }
  25017. </file>
  25018. <file name="protractor.js" type="protractor">
  25019. var templateSelect = element(by.model('template'));
  25020. var includeElem = element(by.css('[ng-include]'));
  25021. it('should load template1.html', function() {
  25022. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  25023. });
  25024. it('should load template2.html', function() {
  25025. if (browser.params.browser === 'firefox') {
  25026. // Firefox can't handle using selects
  25027. // See https://github.com/angular/protractor/issues/480
  25028. return;
  25029. }
  25030. templateSelect.click();
  25031. templateSelect.all(by.css('option')).get(2).click();
  25032. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  25033. });
  25034. it('should change to blank', function() {
  25035. if (browser.params.browser === 'firefox') {
  25036. // Firefox can't handle using selects
  25037. return;
  25038. }
  25039. templateSelect.click();
  25040. templateSelect.all(by.css('option')).get(0).click();
  25041. expect(includeElem.isPresent()).toBe(false);
  25042. });
  25043. </file>
  25044. </example>
  25045. */
  25046. /**
  25047. * @ngdoc event
  25048. * @name ngInclude#$includeContentRequested
  25049. * @eventType emit on the scope ngInclude was declared in
  25050. * @description
  25051. * Emitted every time the ngInclude content is requested.
  25052. *
  25053. * @param {Object} angularEvent Synthetic event object.
  25054. * @param {String} src URL of content to load.
  25055. */
  25056. /**
  25057. * @ngdoc event
  25058. * @name ngInclude#$includeContentLoaded
  25059. * @eventType emit on the current ngInclude scope
  25060. * @description
  25061. * Emitted every time the ngInclude content is reloaded.
  25062. *
  25063. * @param {Object} angularEvent Synthetic event object.
  25064. * @param {String} src URL of content to load.
  25065. */
  25066. /**
  25067. * @ngdoc event
  25068. * @name ngInclude#$includeContentError
  25069. * @eventType emit on the scope ngInclude was declared in
  25070. * @description
  25071. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  25072. *
  25073. * @param {Object} angularEvent Synthetic event object.
  25074. * @param {String} src URL of content to load.
  25075. */
  25076. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  25077. function($templateRequest, $anchorScroll, $animate) {
  25078. return {
  25079. restrict: 'ECA',
  25080. priority: 400,
  25081. terminal: true,
  25082. transclude: 'element',
  25083. controller: angular.noop,
  25084. compile: function(element, attr) {
  25085. var srcExp = attr.ngInclude || attr.src,
  25086. onloadExp = attr.onload || '',
  25087. autoScrollExp = attr.autoscroll;
  25088. return function(scope, $element, $attr, ctrl, $transclude) {
  25089. var changeCounter = 0,
  25090. currentScope,
  25091. previousElement,
  25092. currentElement;
  25093. var cleanupLastIncludeContent = function() {
  25094. if (previousElement) {
  25095. previousElement.remove();
  25096. previousElement = null;
  25097. }
  25098. if (currentScope) {
  25099. currentScope.$destroy();
  25100. currentScope = null;
  25101. }
  25102. if (currentElement) {
  25103. $animate.leave(currentElement).done(function(response) {
  25104. if (response !== false) previousElement = null;
  25105. });
  25106. previousElement = currentElement;
  25107. currentElement = null;
  25108. }
  25109. };
  25110. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  25111. var afterAnimation = function(response) {
  25112. if (response !== false && isDefined(autoScrollExp) &&
  25113. (!autoScrollExp || scope.$eval(autoScrollExp))) {
  25114. $anchorScroll();
  25115. }
  25116. };
  25117. var thisChangeId = ++changeCounter;
  25118. if (src) {
  25119. //set the 2nd param to true to ignore the template request error so that the inner
  25120. //contents and scope can be cleaned up.
  25121. $templateRequest(src, true).then(function(response) {
  25122. if (scope.$$destroyed) return;
  25123. if (thisChangeId !== changeCounter) return;
  25124. var newScope = scope.$new();
  25125. ctrl.template = response;
  25126. // Note: This will also link all children of ng-include that were contained in the original
  25127. // html. If that content contains controllers, ... they could pollute/change the scope.
  25128. // However, using ng-include on an element with additional content does not make sense...
  25129. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  25130. // function is called before linking the content, which would apply child
  25131. // directives to non existing elements.
  25132. var clone = $transclude(newScope, function(clone) {
  25133. cleanupLastIncludeContent();
  25134. $animate.enter(clone, null, $element).done(afterAnimation);
  25135. });
  25136. currentScope = newScope;
  25137. currentElement = clone;
  25138. currentScope.$emit('$includeContentLoaded', src);
  25139. scope.$eval(onloadExp);
  25140. }, function() {
  25141. if (scope.$$destroyed) return;
  25142. if (thisChangeId === changeCounter) {
  25143. cleanupLastIncludeContent();
  25144. scope.$emit('$includeContentError', src);
  25145. }
  25146. });
  25147. scope.$emit('$includeContentRequested', src);
  25148. } else {
  25149. cleanupLastIncludeContent();
  25150. ctrl.template = null;
  25151. }
  25152. });
  25153. };
  25154. }
  25155. };
  25156. }];
  25157. // This directive is called during the $transclude call of the first `ngInclude` directive.
  25158. // It will replace and compile the content of the element with the loaded template.
  25159. // We need this directive so that the element content is already filled when
  25160. // the link function of another directive on the same element as ngInclude
  25161. // is called.
  25162. var ngIncludeFillContentDirective = ['$compile',
  25163. function($compile) {
  25164. return {
  25165. restrict: 'ECA',
  25166. priority: -400,
  25167. require: 'ngInclude',
  25168. link: function(scope, $element, $attr, ctrl) {
  25169. if (toString.call($element[0]).match(/SVG/)) {
  25170. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  25171. // support innerHTML, so detect this here and try to generate the contents
  25172. // specially.
  25173. $element.empty();
  25174. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  25175. function namespaceAdaptedClone(clone) {
  25176. $element.append(clone);
  25177. }, {futureParentElement: $element});
  25178. return;
  25179. }
  25180. $element.html(ctrl.template);
  25181. $compile($element.contents())(scope);
  25182. }
  25183. };
  25184. }];
  25185. /**
  25186. * @ngdoc directive
  25187. * @name ngInit
  25188. * @restrict AC
  25189. *
  25190. * @description
  25191. * The `ngInit` directive allows you to evaluate an expression in the
  25192. * current scope.
  25193. *
  25194. * <div class="alert alert-danger">
  25195. * This directive can be abused to add unnecessary amounts of logic into your templates.
  25196. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  25197. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  25198. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  25199. * rather than `ngInit` to initialize values on a scope.
  25200. * </div>
  25201. *
  25202. * <div class="alert alert-warning">
  25203. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  25204. * sure you have parentheses to ensure correct operator precedence:
  25205. * <pre class="prettyprint">
  25206. * `<div ng-init="test1 = ($index | toString)"></div>`
  25207. * </pre>
  25208. * </div>
  25209. *
  25210. * @priority 450
  25211. *
  25212. * @element ANY
  25213. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  25214. *
  25215. * @example
  25216. <example module="initExample" name="ng-init">
  25217. <file name="index.html">
  25218. <script>
  25219. angular.module('initExample', [])
  25220. .controller('ExampleController', ['$scope', function($scope) {
  25221. $scope.list = [['a', 'b'], ['c', 'd']];
  25222. }]);
  25223. </script>
  25224. <div ng-controller="ExampleController">
  25225. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  25226. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  25227. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  25228. </div>
  25229. </div>
  25230. </div>
  25231. </file>
  25232. <file name="protractor.js" type="protractor">
  25233. it('should alias index positions', function() {
  25234. var elements = element.all(by.css('.example-init'));
  25235. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  25236. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  25237. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  25238. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  25239. });
  25240. </file>
  25241. </example>
  25242. */
  25243. var ngInitDirective = ngDirective({
  25244. priority: 450,
  25245. compile: function() {
  25246. return {
  25247. pre: function(scope, element, attrs) {
  25248. scope.$eval(attrs.ngInit);
  25249. }
  25250. };
  25251. }
  25252. });
  25253. /**
  25254. * @ngdoc directive
  25255. * @name ngList
  25256. *
  25257. * @description
  25258. * Text input that converts between a delimited string and an array of strings. The default
  25259. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  25260. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  25261. *
  25262. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  25263. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  25264. * list item is respected. This implies that the user of the directive is responsible for
  25265. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  25266. * tab or newline character.
  25267. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  25268. * when joining the list items back together) and whitespace around each list item is stripped
  25269. * before it is added to the model.
  25270. *
  25271. * ### Example with Validation
  25272. *
  25273. * <example name="ngList-directive" module="listExample">
  25274. * <file name="app.js">
  25275. * angular.module('listExample', [])
  25276. * .controller('ExampleController', ['$scope', function($scope) {
  25277. * $scope.names = ['morpheus', 'neo', 'trinity'];
  25278. * }]);
  25279. * </file>
  25280. * <file name="index.html">
  25281. * <form name="myForm" ng-controller="ExampleController">
  25282. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  25283. * <span role="alert">
  25284. * <span class="error" ng-show="myForm.namesInput.$error.required">
  25285. * Required!</span>
  25286. * </span>
  25287. * <br>
  25288. * <tt>names = {{names}}</tt><br/>
  25289. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  25290. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  25291. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  25292. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  25293. * </form>
  25294. * </file>
  25295. * <file name="protractor.js" type="protractor">
  25296. * var listInput = element(by.model('names'));
  25297. * var names = element(by.exactBinding('names'));
  25298. * var valid = element(by.binding('myForm.namesInput.$valid'));
  25299. * var error = element(by.css('span.error'));
  25300. *
  25301. * it('should initialize to model', function() {
  25302. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  25303. * expect(valid.getText()).toContain('true');
  25304. * expect(error.getCssValue('display')).toBe('none');
  25305. * });
  25306. *
  25307. * it('should be invalid if empty', function() {
  25308. * listInput.clear();
  25309. * listInput.sendKeys('');
  25310. *
  25311. * expect(names.getText()).toContain('');
  25312. * expect(valid.getText()).toContain('false');
  25313. * expect(error.getCssValue('display')).not.toBe('none');
  25314. * });
  25315. * </file>
  25316. * </example>
  25317. *
  25318. * ### Example - splitting on newline
  25319. * <example name="ngList-directive-newlines">
  25320. * <file name="index.html">
  25321. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  25322. * <pre>{{ list | json }}</pre>
  25323. * </file>
  25324. * <file name="protractor.js" type="protractor">
  25325. * it("should split the text by newlines", function() {
  25326. * var listInput = element(by.model('list'));
  25327. * var output = element(by.binding('list | json'));
  25328. * listInput.sendKeys('abc\ndef\nghi');
  25329. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  25330. * });
  25331. * </file>
  25332. * </example>
  25333. *
  25334. * @element input
  25335. * @param {string=} ngList optional delimiter that should be used to split the value.
  25336. */
  25337. var ngListDirective = function() {
  25338. return {
  25339. restrict: 'A',
  25340. priority: 100,
  25341. require: 'ngModel',
  25342. link: function(scope, element, attr, ctrl) {
  25343. var ngList = attr.ngList || ', ';
  25344. var trimValues = attr.ngTrim !== 'false';
  25345. var separator = trimValues ? trim(ngList) : ngList;
  25346. var parse = function(viewValue) {
  25347. // If the viewValue is invalid (say required but empty) it will be `undefined`
  25348. if (isUndefined(viewValue)) return;
  25349. var list = [];
  25350. if (viewValue) {
  25351. forEach(viewValue.split(separator), function(value) {
  25352. if (value) list.push(trimValues ? trim(value) : value);
  25353. });
  25354. }
  25355. return list;
  25356. };
  25357. ctrl.$parsers.push(parse);
  25358. ctrl.$formatters.push(function(value) {
  25359. if (isArray(value)) {
  25360. return value.join(ngList);
  25361. }
  25362. return undefined;
  25363. });
  25364. // Override the standard $isEmpty because an empty array means the input is empty.
  25365. ctrl.$isEmpty = function(value) {
  25366. return !value || !value.length;
  25367. };
  25368. }
  25369. };
  25370. };
  25371. /* global VALID_CLASS: true,
  25372. INVALID_CLASS: true,
  25373. PRISTINE_CLASS: true,
  25374. DIRTY_CLASS: true,
  25375. UNTOUCHED_CLASS: true,
  25376. TOUCHED_CLASS: true,
  25377. PENDING_CLASS: true,
  25378. addSetValidityMethod: true,
  25379. setupValidity: true,
  25380. defaultModelOptions: false
  25381. */
  25382. var VALID_CLASS = 'ng-valid',
  25383. INVALID_CLASS = 'ng-invalid',
  25384. PRISTINE_CLASS = 'ng-pristine',
  25385. DIRTY_CLASS = 'ng-dirty',
  25386. UNTOUCHED_CLASS = 'ng-untouched',
  25387. TOUCHED_CLASS = 'ng-touched',
  25388. EMPTY_CLASS = 'ng-empty',
  25389. NOT_EMPTY_CLASS = 'ng-not-empty';
  25390. var ngModelMinErr = minErr('ngModel');
  25391. /**
  25392. * @ngdoc type
  25393. * @name ngModel.NgModelController
  25394. *
  25395. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  25396. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  25397. * is set.
  25398. * @property {*} $modelValue The value in the model that the control is bound to.
  25399. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  25400. the control reads value from the DOM. The functions are called in array order, each passing
  25401. its return value through to the next. The last return value is forwarded to the
  25402. {@link ngModel.NgModelController#$validators `$validators`} collection.
  25403. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  25404. `$viewValue`}.
  25405. Returning `undefined` from a parser means a parse error occurred. In that case,
  25406. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  25407. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  25408. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  25409. *
  25410. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  25411. the model value changes. The functions are called in reverse array order, each passing the value through to the
  25412. next. The last return value is used as the actual DOM value.
  25413. Used to format / convert values for display in the control.
  25414. * ```js
  25415. * function formatter(value) {
  25416. * if (value) {
  25417. * return value.toUpperCase();
  25418. * }
  25419. * }
  25420. * ngModel.$formatters.push(formatter);
  25421. * ```
  25422. *
  25423. * @property {Object.<string, function>} $validators A collection of validators that are applied
  25424. * whenever the model value changes. The key value within the object refers to the name of the
  25425. * validator while the function refers to the validation operation. The validation operation is
  25426. * provided with the model value as an argument and must return a true or false value depending
  25427. * on the response of that validation.
  25428. *
  25429. * ```js
  25430. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  25431. * var value = modelValue || viewValue;
  25432. * return /[0-9]+/.test(value) &&
  25433. * /[a-z]+/.test(value) &&
  25434. * /[A-Z]+/.test(value) &&
  25435. * /\W+/.test(value);
  25436. * };
  25437. * ```
  25438. *
  25439. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  25440. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  25441. * is expected to return a promise when it is run during the model validation process. Once the promise
  25442. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  25443. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  25444. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  25445. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  25446. * will only run once all synchronous validators have passed.
  25447. *
  25448. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  25449. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  25450. *
  25451. * ```js
  25452. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  25453. * var value = modelValue || viewValue;
  25454. *
  25455. * // Lookup user by username
  25456. * return $http.get('/api/users/' + value).
  25457. * then(function resolved() {
  25458. * //username exists, this means validation fails
  25459. * return $q.reject('exists');
  25460. * }, function rejected() {
  25461. * //username does not exist, therefore this validation passes
  25462. * return true;
  25463. * });
  25464. * };
  25465. * ```
  25466. *
  25467. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  25468. * view value has changed. It is called with no arguments, and its return value is ignored.
  25469. * This can be used in place of additional $watches against the model value.
  25470. *
  25471. * @property {Object} $error An object hash with all failing validator ids as keys.
  25472. * @property {Object} $pending An object hash with all pending validator ids as keys.
  25473. *
  25474. * @property {boolean} $untouched True if control has not lost focus yet.
  25475. * @property {boolean} $touched True if control has lost focus.
  25476. * @property {boolean} $pristine True if user has not interacted with the control yet.
  25477. * @property {boolean} $dirty True if user has already interacted with the control.
  25478. * @property {boolean} $valid True if there is no error.
  25479. * @property {boolean} $invalid True if at least one error on the control.
  25480. * @property {string} $name The name attribute of the control.
  25481. *
  25482. * @description
  25483. *
  25484. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  25485. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  25486. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  25487. * listening to DOM events.
  25488. * Such DOM related logic should be provided by other directives which make use of
  25489. * `NgModelController` for data-binding to control elements.
  25490. * Angular provides this DOM logic for most {@link input `input`} elements.
  25491. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  25492. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  25493. *
  25494. * @example
  25495. * ### Custom Control Example
  25496. * This example shows how to use `NgModelController` with a custom control to achieve
  25497. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  25498. * collaborate together to achieve the desired result.
  25499. *
  25500. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  25501. * contents be edited in place by the user.
  25502. *
  25503. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  25504. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  25505. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  25506. * that content using the `$sce` service.
  25507. *
  25508. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  25509. <file name="style.css">
  25510. [contenteditable] {
  25511. border: 1px solid black;
  25512. background-color: white;
  25513. min-height: 20px;
  25514. }
  25515. .ng-invalid {
  25516. border: 1px solid red;
  25517. }
  25518. </file>
  25519. <file name="script.js">
  25520. angular.module('customControl', ['ngSanitize']).
  25521. directive('contenteditable', ['$sce', function($sce) {
  25522. return {
  25523. restrict: 'A', // only activate on element attribute
  25524. require: '?ngModel', // get a hold of NgModelController
  25525. link: function(scope, element, attrs, ngModel) {
  25526. if (!ngModel) return; // do nothing if no ng-model
  25527. // Specify how UI should be updated
  25528. ngModel.$render = function() {
  25529. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  25530. };
  25531. // Listen for change events to enable binding
  25532. element.on('blur keyup change', function() {
  25533. scope.$evalAsync(read);
  25534. });
  25535. read(); // initialize
  25536. // Write data to the model
  25537. function read() {
  25538. var html = element.html();
  25539. // When we clear the content editable the browser leaves a <br> behind
  25540. // If strip-br attribute is provided then we strip this out
  25541. if (attrs.stripBr && html === '<br>') {
  25542. html = '';
  25543. }
  25544. ngModel.$setViewValue(html);
  25545. }
  25546. }
  25547. };
  25548. }]);
  25549. </file>
  25550. <file name="index.html">
  25551. <form name="myForm">
  25552. <div contenteditable
  25553. name="myWidget" ng-model="userContent"
  25554. strip-br="true"
  25555. required>Change me!</div>
  25556. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  25557. <hr>
  25558. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  25559. </form>
  25560. </file>
  25561. <file name="protractor.js" type="protractor">
  25562. it('should data-bind and become invalid', function() {
  25563. if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
  25564. // SafariDriver can't handle contenteditable
  25565. // and Firefox driver can't clear contenteditables very well
  25566. return;
  25567. }
  25568. var contentEditable = element(by.css('[contenteditable]'));
  25569. var content = 'Change me!';
  25570. expect(contentEditable.getText()).toEqual(content);
  25571. contentEditable.clear();
  25572. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  25573. expect(contentEditable.getText()).toEqual('');
  25574. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  25575. });
  25576. </file>
  25577. * </example>
  25578. *
  25579. *
  25580. */
  25581. NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];
  25582. function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {
  25583. this.$viewValue = Number.NaN;
  25584. this.$modelValue = Number.NaN;
  25585. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  25586. this.$validators = {};
  25587. this.$asyncValidators = {};
  25588. this.$parsers = [];
  25589. this.$formatters = [];
  25590. this.$viewChangeListeners = [];
  25591. this.$untouched = true;
  25592. this.$touched = false;
  25593. this.$pristine = true;
  25594. this.$dirty = false;
  25595. this.$valid = true;
  25596. this.$invalid = false;
  25597. this.$error = {}; // keep invalid keys here
  25598. this.$$success = {}; // keep valid keys here
  25599. this.$pending = undefined; // keep pending keys here
  25600. this.$name = $interpolate($attr.name || '', false)($scope);
  25601. this.$$parentForm = nullFormCtrl;
  25602. this.$options = defaultModelOptions;
  25603. this.$$parsedNgModel = $parse($attr.ngModel);
  25604. this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;
  25605. this.$$ngModelGet = this.$$parsedNgModel;
  25606. this.$$ngModelSet = this.$$parsedNgModelAssign;
  25607. this.$$pendingDebounce = null;
  25608. this.$$parserValid = undefined;
  25609. this.$$currentValidationRunId = 0;
  25610. this.$$scope = $scope;
  25611. this.$$attr = $attr;
  25612. this.$$element = $element;
  25613. this.$$animate = $animate;
  25614. this.$$timeout = $timeout;
  25615. this.$$parse = $parse;
  25616. this.$$q = $q;
  25617. this.$$exceptionHandler = $exceptionHandler;
  25618. setupValidity(this);
  25619. setupModelWatcher(this);
  25620. }
  25621. NgModelController.prototype = {
  25622. $$initGetterSetters: function() {
  25623. if (this.$options.getOption('getterSetter')) {
  25624. var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),
  25625. invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');
  25626. this.$$ngModelGet = function($scope) {
  25627. var modelValue = this.$$parsedNgModel($scope);
  25628. if (isFunction(modelValue)) {
  25629. modelValue = invokeModelGetter($scope);
  25630. }
  25631. return modelValue;
  25632. };
  25633. this.$$ngModelSet = function($scope, newValue) {
  25634. if (isFunction(this.$$parsedNgModel($scope))) {
  25635. invokeModelSetter($scope, {$$$p: newValue});
  25636. } else {
  25637. this.$$parsedNgModelAssign($scope, newValue);
  25638. }
  25639. };
  25640. } else if (!this.$$parsedNgModel.assign) {
  25641. throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
  25642. this.$$attr.ngModel, startingTag(this.$$element));
  25643. }
  25644. },
  25645. /**
  25646. * @ngdoc method
  25647. * @name ngModel.NgModelController#$render
  25648. *
  25649. * @description
  25650. * Called when the view needs to be updated. It is expected that the user of the ng-model
  25651. * directive will implement this method.
  25652. *
  25653. * The `$render()` method is invoked in the following situations:
  25654. *
  25655. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  25656. * committed value then `$render()` is called to update the input control.
  25657. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  25658. * the `$viewValue` are different from last time.
  25659. *
  25660. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  25661. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  25662. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  25663. * invoked if you only change a property on the objects.
  25664. */
  25665. $render: noop,
  25666. /**
  25667. * @ngdoc method
  25668. * @name ngModel.NgModelController#$isEmpty
  25669. *
  25670. * @description
  25671. * This is called when we need to determine if the value of an input is empty.
  25672. *
  25673. * For instance, the required directive does this to work out if the input has data or not.
  25674. *
  25675. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  25676. *
  25677. * You can override this for input directives whose concept of being empty is different from the
  25678. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  25679. * implies empty.
  25680. *
  25681. * @param {*} value The value of the input to check for emptiness.
  25682. * @returns {boolean} True if `value` is "empty".
  25683. */
  25684. $isEmpty: function(value) {
  25685. // eslint-disable-next-line no-self-compare
  25686. return isUndefined(value) || value === '' || value === null || value !== value;
  25687. },
  25688. $$updateEmptyClasses: function(value) {
  25689. if (this.$isEmpty(value)) {
  25690. this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);
  25691. this.$$animate.addClass(this.$$element, EMPTY_CLASS);
  25692. } else {
  25693. this.$$animate.removeClass(this.$$element, EMPTY_CLASS);
  25694. this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);
  25695. }
  25696. },
  25697. /**
  25698. * @ngdoc method
  25699. * @name ngModel.NgModelController#$setPristine
  25700. *
  25701. * @description
  25702. * Sets the control to its pristine state.
  25703. *
  25704. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  25705. * state (`ng-pristine` class). A model is considered to be pristine when the control
  25706. * has not been changed from when first compiled.
  25707. */
  25708. $setPristine: function() {
  25709. this.$dirty = false;
  25710. this.$pristine = true;
  25711. this.$$animate.removeClass(this.$$element, DIRTY_CLASS);
  25712. this.$$animate.addClass(this.$$element, PRISTINE_CLASS);
  25713. },
  25714. /**
  25715. * @ngdoc method
  25716. * @name ngModel.NgModelController#$setDirty
  25717. *
  25718. * @description
  25719. * Sets the control to its dirty state.
  25720. *
  25721. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  25722. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  25723. * from when first compiled.
  25724. */
  25725. $setDirty: function() {
  25726. this.$dirty = true;
  25727. this.$pristine = false;
  25728. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  25729. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  25730. this.$$parentForm.$setDirty();
  25731. },
  25732. /**
  25733. * @ngdoc method
  25734. * @name ngModel.NgModelController#$setUntouched
  25735. *
  25736. * @description
  25737. * Sets the control to its untouched state.
  25738. *
  25739. * This method can be called to remove the `ng-touched` class and set the control to its
  25740. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  25741. * by default, however this function can be used to restore that state if the model has
  25742. * already been touched by the user.
  25743. */
  25744. $setUntouched: function() {
  25745. this.$touched = false;
  25746. this.$untouched = true;
  25747. this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  25748. },
  25749. /**
  25750. * @ngdoc method
  25751. * @name ngModel.NgModelController#$setTouched
  25752. *
  25753. * @description
  25754. * Sets the control to its touched state.
  25755. *
  25756. * This method can be called to remove the `ng-untouched` class and set the control to its
  25757. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  25758. * first focused the control element and then shifted focus away from the control (blur event).
  25759. */
  25760. $setTouched: function() {
  25761. this.$touched = true;
  25762. this.$untouched = false;
  25763. this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  25764. },
  25765. /**
  25766. * @ngdoc method
  25767. * @name ngModel.NgModelController#$rollbackViewValue
  25768. *
  25769. * @description
  25770. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  25771. * which may be caused by a pending debounced event or because the input is waiting for some
  25772. * future event.
  25773. *
  25774. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  25775. * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of
  25776. * sync with the ngModel's `$modelValue`.
  25777. *
  25778. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  25779. * and reset the input to the last committed view value.
  25780. *
  25781. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  25782. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  25783. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  25784. *
  25785. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  25786. * input which may have such events pending. This is important in order to make sure that the
  25787. * input field will be updated with the new model value and any pending operations are cancelled.
  25788. *
  25789. * <example name="ng-model-cancel-update" module="cancel-update-example">
  25790. * <file name="app.js">
  25791. * angular.module('cancel-update-example', [])
  25792. *
  25793. * .controller('CancelUpdateController', ['$scope', function($scope) {
  25794. * $scope.model = {value1: '', value2: ''};
  25795. *
  25796. * $scope.setEmpty = function(e, value, rollback) {
  25797. * if (e.keyCode === 27) {
  25798. * e.preventDefault();
  25799. * if (rollback) {
  25800. * $scope.myForm[value].$rollbackViewValue();
  25801. * }
  25802. * $scope.model[value] = '';
  25803. * }
  25804. * };
  25805. * }]);
  25806. * </file>
  25807. * <file name="index.html">
  25808. * <div ng-controller="CancelUpdateController">
  25809. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  25810. * empty them. Follow these steps and observe the difference:</p>
  25811. * <ol>
  25812. * <li>Type something in the input. You will see that the model is not yet updated</li>
  25813. * <li>Press the Escape key.
  25814. * <ol>
  25815. * <li> In the first example, nothing happens, because the model is already '', and no
  25816. * update is detected. If you blur the input, the model will be set to the current view.
  25817. * </li>
  25818. * <li> In the second example, the pending update is cancelled, and the input is set back
  25819. * to the last committed view value (''). Blurring the input does nothing.
  25820. * </li>
  25821. * </ol>
  25822. * </li>
  25823. * </ol>
  25824. *
  25825. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  25826. * <div>
  25827. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  25828. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  25829. * ng-keydown="setEmpty($event, 'value1')">
  25830. * value1: "{{ model.value1 }}"
  25831. * </div>
  25832. *
  25833. * <div>
  25834. * <p id="inputDescription2">With $rollbackViewValue():</p>
  25835. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  25836. * ng-keydown="setEmpty($event, 'value2', true)">
  25837. * value2: "{{ model.value2 }}"
  25838. * </div>
  25839. * </form>
  25840. * </div>
  25841. * </file>
  25842. <file name="style.css">
  25843. div {
  25844. display: table-cell;
  25845. }
  25846. div:nth-child(1) {
  25847. padding-right: 30px;
  25848. }
  25849. </file>
  25850. * </example>
  25851. */
  25852. $rollbackViewValue: function() {
  25853. this.$$timeout.cancel(this.$$pendingDebounce);
  25854. this.$viewValue = this.$$lastCommittedViewValue;
  25855. this.$render();
  25856. },
  25857. /**
  25858. * @ngdoc method
  25859. * @name ngModel.NgModelController#$validate
  25860. *
  25861. * @description
  25862. * Runs each of the registered validators (first synchronous validators and then
  25863. * asynchronous validators).
  25864. * If the validity changes to invalid, the model will be set to `undefined`,
  25865. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  25866. * If the validity changes to valid, it will set the model to the last available valid
  25867. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  25868. */
  25869. $validate: function() {
  25870. // ignore $validate before model is initialized
  25871. if (isNumberNaN(this.$modelValue)) {
  25872. return;
  25873. }
  25874. var viewValue = this.$$lastCommittedViewValue;
  25875. // Note: we use the $$rawModelValue as $modelValue might have been
  25876. // set to undefined during a view -> model update that found validation
  25877. // errors. We can't parse the view here, since that could change
  25878. // the model although neither viewValue nor the model on the scope changed
  25879. var modelValue = this.$$rawModelValue;
  25880. var prevValid = this.$valid;
  25881. var prevModelValue = this.$modelValue;
  25882. var allowInvalid = this.$options.getOption('allowInvalid');
  25883. var that = this;
  25884. this.$$runValidators(modelValue, viewValue, function(allValid) {
  25885. // If there was no change in validity, don't update the model
  25886. // This prevents changing an invalid modelValue to undefined
  25887. if (!allowInvalid && prevValid !== allValid) {
  25888. // Note: Don't check this.$valid here, as we could have
  25889. // external validators (e.g. calculated on the server),
  25890. // that just call $setValidity and need the model value
  25891. // to calculate their validity.
  25892. that.$modelValue = allValid ? modelValue : undefined;
  25893. if (that.$modelValue !== prevModelValue) {
  25894. that.$$writeModelToScope();
  25895. }
  25896. }
  25897. });
  25898. },
  25899. $$runValidators: function(modelValue, viewValue, doneCallback) {
  25900. this.$$currentValidationRunId++;
  25901. var localValidationRunId = this.$$currentValidationRunId;
  25902. var that = this;
  25903. // check parser error
  25904. if (!processParseErrors()) {
  25905. validationDone(false);
  25906. return;
  25907. }
  25908. if (!processSyncValidators()) {
  25909. validationDone(false);
  25910. return;
  25911. }
  25912. processAsyncValidators();
  25913. function processParseErrors() {
  25914. var errorKey = that.$$parserName || 'parse';
  25915. if (isUndefined(that.$$parserValid)) {
  25916. setValidity(errorKey, null);
  25917. } else {
  25918. if (!that.$$parserValid) {
  25919. forEach(that.$validators, function(v, name) {
  25920. setValidity(name, null);
  25921. });
  25922. forEach(that.$asyncValidators, function(v, name) {
  25923. setValidity(name, null);
  25924. });
  25925. }
  25926. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  25927. setValidity(errorKey, that.$$parserValid);
  25928. return that.$$parserValid;
  25929. }
  25930. return true;
  25931. }
  25932. function processSyncValidators() {
  25933. var syncValidatorsValid = true;
  25934. forEach(that.$validators, function(validator, name) {
  25935. var result = Boolean(validator(modelValue, viewValue));
  25936. syncValidatorsValid = syncValidatorsValid && result;
  25937. setValidity(name, result);
  25938. });
  25939. if (!syncValidatorsValid) {
  25940. forEach(that.$asyncValidators, function(v, name) {
  25941. setValidity(name, null);
  25942. });
  25943. return false;
  25944. }
  25945. return true;
  25946. }
  25947. function processAsyncValidators() {
  25948. var validatorPromises = [];
  25949. var allValid = true;
  25950. forEach(that.$asyncValidators, function(validator, name) {
  25951. var promise = validator(modelValue, viewValue);
  25952. if (!isPromiseLike(promise)) {
  25953. throw ngModelMinErr('nopromise',
  25954. 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
  25955. }
  25956. setValidity(name, undefined);
  25957. validatorPromises.push(promise.then(function() {
  25958. setValidity(name, true);
  25959. }, function() {
  25960. allValid = false;
  25961. setValidity(name, false);
  25962. }));
  25963. });
  25964. if (!validatorPromises.length) {
  25965. validationDone(true);
  25966. } else {
  25967. that.$$q.all(validatorPromises).then(function() {
  25968. validationDone(allValid);
  25969. }, noop);
  25970. }
  25971. }
  25972. function setValidity(name, isValid) {
  25973. if (localValidationRunId === that.$$currentValidationRunId) {
  25974. that.$setValidity(name, isValid);
  25975. }
  25976. }
  25977. function validationDone(allValid) {
  25978. if (localValidationRunId === that.$$currentValidationRunId) {
  25979. doneCallback(allValid);
  25980. }
  25981. }
  25982. },
  25983. /**
  25984. * @ngdoc method
  25985. * @name ngModel.NgModelController#$commitViewValue
  25986. *
  25987. * @description
  25988. * Commit a pending update to the `$modelValue`.
  25989. *
  25990. * Updates may be pending by a debounced event or because the input is waiting for a some future
  25991. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  25992. * usually handles calling this in response to input events.
  25993. */
  25994. $commitViewValue: function() {
  25995. var viewValue = this.$viewValue;
  25996. this.$$timeout.cancel(this.$$pendingDebounce);
  25997. // If the view value has not changed then we should just exit, except in the case where there is
  25998. // a native validator on the element. In this case the validation state may have changed even though
  25999. // the viewValue has stayed empty.
  26000. if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {
  26001. return;
  26002. }
  26003. this.$$updateEmptyClasses(viewValue);
  26004. this.$$lastCommittedViewValue = viewValue;
  26005. // change to dirty
  26006. if (this.$pristine) {
  26007. this.$setDirty();
  26008. }
  26009. this.$$parseAndValidate();
  26010. },
  26011. $$parseAndValidate: function() {
  26012. var viewValue = this.$$lastCommittedViewValue;
  26013. var modelValue = viewValue;
  26014. var that = this;
  26015. this.$$parserValid = isUndefined(modelValue) ? undefined : true;
  26016. if (this.$$parserValid) {
  26017. for (var i = 0; i < this.$parsers.length; i++) {
  26018. modelValue = this.$parsers[i](modelValue);
  26019. if (isUndefined(modelValue)) {
  26020. this.$$parserValid = false;
  26021. break;
  26022. }
  26023. }
  26024. }
  26025. if (isNumberNaN(this.$modelValue)) {
  26026. // this.$modelValue has not been touched yet...
  26027. this.$modelValue = this.$$ngModelGet(this.$$scope);
  26028. }
  26029. var prevModelValue = this.$modelValue;
  26030. var allowInvalid = this.$options.getOption('allowInvalid');
  26031. this.$$rawModelValue = modelValue;
  26032. if (allowInvalid) {
  26033. this.$modelValue = modelValue;
  26034. writeToModelIfNeeded();
  26035. }
  26036. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  26037. // This can happen if e.g. $setViewValue is called from inside a parser
  26038. this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {
  26039. if (!allowInvalid) {
  26040. // Note: Don't check this.$valid here, as we could have
  26041. // external validators (e.g. calculated on the server),
  26042. // that just call $setValidity and need the model value
  26043. // to calculate their validity.
  26044. that.$modelValue = allValid ? modelValue : undefined;
  26045. writeToModelIfNeeded();
  26046. }
  26047. });
  26048. function writeToModelIfNeeded() {
  26049. if (that.$modelValue !== prevModelValue) {
  26050. that.$$writeModelToScope();
  26051. }
  26052. }
  26053. },
  26054. $$writeModelToScope: function() {
  26055. this.$$ngModelSet(this.$$scope, this.$modelValue);
  26056. forEach(this.$viewChangeListeners, function(listener) {
  26057. try {
  26058. listener();
  26059. } catch (e) {
  26060. // eslint-disable-next-line no-invalid-this
  26061. this.$$exceptionHandler(e);
  26062. }
  26063. }, this);
  26064. },
  26065. /**
  26066. * @ngdoc method
  26067. * @name ngModel.NgModelController#$setViewValue
  26068. *
  26069. * @description
  26070. * Update the view value.
  26071. *
  26072. * This method should be called when a control wants to change the view value; typically,
  26073. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  26074. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  26075. * calls it when an option is selected.
  26076. *
  26077. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  26078. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  26079. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  26080. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  26081. * in the `$viewChangeListeners` list, are called.
  26082. *
  26083. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  26084. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  26085. * `updateOn` events is triggered on the DOM element.
  26086. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  26087. * directive is used with a custom debounce for this particular event.
  26088. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  26089. * is specified, once the timer runs out.
  26090. *
  26091. * When used with standard inputs, the view value will always be a string (which is in some cases
  26092. * parsed into another type, such as a `Date` object for `input[date]`.)
  26093. * However, custom controls might also pass objects to this method. In this case, we should make
  26094. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  26095. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  26096. * the property of the object then ngModel will not realize that the object has changed and
  26097. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  26098. * not change properties of the copy once it has been passed to `$setViewValue`.
  26099. * Otherwise you may cause the model value on the scope to change incorrectly.
  26100. *
  26101. * <div class="alert alert-info">
  26102. * In any case, the value passed to the method should always reflect the current value
  26103. * of the control. For example, if you are calling `$setViewValue` for an input element,
  26104. * you should pass the input DOM value. Otherwise, the control and the scope model become
  26105. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  26106. * the control's DOM value in any way. If we want to change the control's DOM value
  26107. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  26108. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  26109. * to update the DOM, and finally call `$validate` on it.
  26110. * </div>
  26111. *
  26112. * @param {*} value value from the view.
  26113. * @param {string} trigger Event that triggered the update.
  26114. */
  26115. $setViewValue: function(value, trigger) {
  26116. this.$viewValue = value;
  26117. if (this.$options.getOption('updateOnDefault')) {
  26118. this.$$debounceViewValueCommit(trigger);
  26119. }
  26120. },
  26121. $$debounceViewValueCommit: function(trigger) {
  26122. var debounceDelay = this.$options.getOption('debounce');
  26123. if (isNumber(debounceDelay[trigger])) {
  26124. debounceDelay = debounceDelay[trigger];
  26125. } else if (isNumber(debounceDelay['default'])) {
  26126. debounceDelay = debounceDelay['default'];
  26127. }
  26128. this.$$timeout.cancel(this.$$pendingDebounce);
  26129. var that = this;
  26130. if (debounceDelay > 0) { // this fails if debounceDelay is an object
  26131. this.$$pendingDebounce = this.$$timeout(function() {
  26132. that.$commitViewValue();
  26133. }, debounceDelay);
  26134. } else if (this.$$scope.$root.$$phase) {
  26135. this.$commitViewValue();
  26136. } else {
  26137. this.$$scope.$apply(function() {
  26138. that.$commitViewValue();
  26139. });
  26140. }
  26141. },
  26142. /**
  26143. * @ngdoc method
  26144. *
  26145. * @name ngModel.NgModelController#$overrideModelOptions
  26146. *
  26147. * @description
  26148. *
  26149. * Override the current model options settings programmatically.
  26150. *
  26151. * The previous `ModelOptions` value will not be modified. Instead, a
  26152. * new `ModelOptions` object will inherit from the previous one overriding
  26153. * or inheriting settings that are defined in the given parameter.
  26154. *
  26155. * See {@link ngModelOptions} for information about what options can be specified
  26156. * and how model option inheritance works.
  26157. *
  26158. * @param {Object} options a hash of settings to override the previous options
  26159. *
  26160. */
  26161. $overrideModelOptions: function(options) {
  26162. this.$options = this.$options.createChild(options);
  26163. }
  26164. };
  26165. function setupModelWatcher(ctrl) {
  26166. // model -> value
  26167. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  26168. // 1. scope value is 'a'
  26169. // 2. user enters 'b'
  26170. // 3. ng-change kicks in and reverts scope value to 'a'
  26171. // -> scope value did not change since the last digest as
  26172. // ng-change executes in apply phase
  26173. // 4. view should be changed back to 'a'
  26174. ctrl.$$scope.$watch(function ngModelWatch() {
  26175. var modelValue = ctrl.$$ngModelGet(ctrl.$$scope);
  26176. // if scope model value and ngModel value are out of sync
  26177. // TODO(perf): why not move this to the action fn?
  26178. if (modelValue !== ctrl.$modelValue &&
  26179. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  26180. // eslint-disable-next-line no-self-compare
  26181. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  26182. ) {
  26183. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  26184. ctrl.$$parserValid = undefined;
  26185. var formatters = ctrl.$formatters,
  26186. idx = formatters.length;
  26187. var viewValue = modelValue;
  26188. while (idx--) {
  26189. viewValue = formatters[idx](viewValue);
  26190. }
  26191. if (ctrl.$viewValue !== viewValue) {
  26192. ctrl.$$updateEmptyClasses(viewValue);
  26193. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  26194. ctrl.$render();
  26195. // It is possible that model and view value have been updated during render
  26196. ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop);
  26197. }
  26198. }
  26199. return modelValue;
  26200. });
  26201. }
  26202. /**
  26203. * @ngdoc method
  26204. * @name ngModel.NgModelController#$setValidity
  26205. *
  26206. * @description
  26207. * Change the validity state, and notify the form.
  26208. *
  26209. * This method can be called within $parsers/$formatters or a custom validation implementation.
  26210. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  26211. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  26212. *
  26213. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  26214. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  26215. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  26216. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  26217. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  26218. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  26219. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  26220. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  26221. * Skipped is used by Angular when validators do not run because of parse errors and
  26222. * when `$asyncValidators` do not run because any of the `$validators` failed.
  26223. */
  26224. addSetValidityMethod({
  26225. clazz: NgModelController,
  26226. set: function(object, property) {
  26227. object[property] = true;
  26228. },
  26229. unset: function(object, property) {
  26230. delete object[property];
  26231. }
  26232. });
  26233. /**
  26234. * @ngdoc directive
  26235. * @name ngModel
  26236. *
  26237. * @element input
  26238. * @priority 1
  26239. *
  26240. * @description
  26241. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  26242. * property on the scope using {@link ngModel.NgModelController NgModelController},
  26243. * which is created and exposed by this directive.
  26244. *
  26245. * `ngModel` is responsible for:
  26246. *
  26247. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  26248. * require.
  26249. * - Providing validation behavior (i.e. required, number, email, url).
  26250. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  26251. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  26252. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  26253. * - Registering the control with its parent {@link ng.directive:form form}.
  26254. *
  26255. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  26256. * current scope. If the property doesn't already exist on this scope, it will be created
  26257. * implicitly and added to the scope.
  26258. *
  26259. * For best practices on using `ngModel`, see:
  26260. *
  26261. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  26262. *
  26263. * For basic examples, how to use `ngModel`, see:
  26264. *
  26265. * - {@link ng.directive:input input}
  26266. * - {@link input[text] text}
  26267. * - {@link input[checkbox] checkbox}
  26268. * - {@link input[radio] radio}
  26269. * - {@link input[number] number}
  26270. * - {@link input[email] email}
  26271. * - {@link input[url] url}
  26272. * - {@link input[date] date}
  26273. * - {@link input[datetime-local] datetime-local}
  26274. * - {@link input[time] time}
  26275. * - {@link input[month] month}
  26276. * - {@link input[week] week}
  26277. * - {@link ng.directive:select select}
  26278. * - {@link ng.directive:textarea textarea}
  26279. *
  26280. * # Complex Models (objects or collections)
  26281. *
  26282. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  26283. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  26284. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  26285. *
  26286. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  26287. *
  26288. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  26289. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  26290. * if the select is given the `multiple` attribute.
  26291. *
  26292. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  26293. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  26294. * not trigger a re-rendering of the model.
  26295. *
  26296. * # CSS classes
  26297. * The following CSS classes are added and removed on the associated input/select/textarea element
  26298. * depending on the validity of the model.
  26299. *
  26300. * - `ng-valid`: the model is valid
  26301. * - `ng-invalid`: the model is invalid
  26302. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  26303. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  26304. * - `ng-pristine`: the control hasn't been interacted with yet
  26305. * - `ng-dirty`: the control has been interacted with
  26306. * - `ng-touched`: the control has been blurred
  26307. * - `ng-untouched`: the control hasn't been blurred
  26308. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  26309. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  26310. * by the {@link ngModel.NgModelController#$isEmpty} method
  26311. * - `ng-not-empty`: the view contains a non-empty value
  26312. *
  26313. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  26314. *
  26315. * ## Animation Hooks
  26316. *
  26317. * Animations within models are triggered when any of the associated CSS classes are added and removed
  26318. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  26319. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  26320. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  26321. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  26322. *
  26323. * The following example shows a simple way to utilize CSS transitions to style an input element
  26324. * that has been rendered as invalid after it has been validated:
  26325. *
  26326. * <pre>
  26327. * //be sure to include ngAnimate as a module to hook into more
  26328. * //advanced animations
  26329. * .my-input {
  26330. * transition:0.5s linear all;
  26331. * background: white;
  26332. * }
  26333. * .my-input.ng-invalid {
  26334. * background: red;
  26335. * color:white;
  26336. * }
  26337. * </pre>
  26338. *
  26339. * @example
  26340. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
  26341. <file name="index.html">
  26342. <script>
  26343. angular.module('inputExample', [])
  26344. .controller('ExampleController', ['$scope', function($scope) {
  26345. $scope.val = '1';
  26346. }]);
  26347. </script>
  26348. <style>
  26349. .my-input {
  26350. transition:all linear 0.5s;
  26351. background: transparent;
  26352. }
  26353. .my-input.ng-invalid {
  26354. color:white;
  26355. background: red;
  26356. }
  26357. </style>
  26358. <p id="inputDescription">
  26359. Update input to see transitions when valid/invalid.
  26360. Integer is a valid value.
  26361. </p>
  26362. <form name="testForm" ng-controller="ExampleController">
  26363. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  26364. aria-describedby="inputDescription" />
  26365. </form>
  26366. </file>
  26367. * </example>
  26368. *
  26369. * ## Binding to a getter/setter
  26370. *
  26371. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  26372. * function that returns a representation of the model when called with zero arguments, and sets
  26373. * the internal state of a model when called with an argument. It's sometimes useful to use this
  26374. * for models that have an internal representation that's different from what the model exposes
  26375. * to the view.
  26376. *
  26377. * <div class="alert alert-success">
  26378. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  26379. * frequently than other parts of your code.
  26380. * </div>
  26381. *
  26382. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  26383. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  26384. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  26385. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  26386. *
  26387. * The following example shows how to use `ngModel` with a getter/setter:
  26388. *
  26389. * @example
  26390. * <example name="ngModel-getter-setter" module="getterSetterExample">
  26391. <file name="index.html">
  26392. <div ng-controller="ExampleController">
  26393. <form name="userForm">
  26394. <label>Name:
  26395. <input type="text" name="userName"
  26396. ng-model="user.name"
  26397. ng-model-options="{ getterSetter: true }" />
  26398. </label>
  26399. </form>
  26400. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  26401. </div>
  26402. </file>
  26403. <file name="app.js">
  26404. angular.module('getterSetterExample', [])
  26405. .controller('ExampleController', ['$scope', function($scope) {
  26406. var _name = 'Brian';
  26407. $scope.user = {
  26408. name: function(newName) {
  26409. // Note that newName can be undefined for two reasons:
  26410. // 1. Because it is called as a getter and thus called with no arguments
  26411. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  26412. // input is invalid
  26413. return arguments.length ? (_name = newName) : _name;
  26414. }
  26415. };
  26416. }]);
  26417. </file>
  26418. * </example>
  26419. */
  26420. var ngModelDirective = ['$rootScope', function($rootScope) {
  26421. return {
  26422. restrict: 'A',
  26423. require: ['ngModel', '^?form', '^?ngModelOptions'],
  26424. controller: NgModelController,
  26425. // Prelink needs to run before any input directive
  26426. // so that we can set the NgModelOptions in NgModelController
  26427. // before anyone else uses it.
  26428. priority: 1,
  26429. compile: function ngModelCompile(element) {
  26430. // Setup initial state of the control
  26431. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  26432. return {
  26433. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  26434. var modelCtrl = ctrls[0],
  26435. formCtrl = ctrls[1] || modelCtrl.$$parentForm,
  26436. optionsCtrl = ctrls[2];
  26437. if (optionsCtrl) {
  26438. modelCtrl.$options = optionsCtrl.$options;
  26439. }
  26440. modelCtrl.$$initGetterSetters();
  26441. // notify others, especially parent forms
  26442. formCtrl.$addControl(modelCtrl);
  26443. attr.$observe('name', function(newValue) {
  26444. if (modelCtrl.$name !== newValue) {
  26445. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  26446. }
  26447. });
  26448. scope.$on('$destroy', function() {
  26449. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  26450. });
  26451. },
  26452. post: function ngModelPostLink(scope, element, attr, ctrls) {
  26453. var modelCtrl = ctrls[0];
  26454. if (modelCtrl.$options.getOption('updateOn')) {
  26455. element.on(modelCtrl.$options.getOption('updateOn'), function(ev) {
  26456. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  26457. });
  26458. }
  26459. function setTouched() {
  26460. modelCtrl.$setTouched();
  26461. }
  26462. element.on('blur', function() {
  26463. if (modelCtrl.$touched) return;
  26464. if ($rootScope.$$phase) {
  26465. scope.$evalAsync(setTouched);
  26466. } else {
  26467. scope.$apply(setTouched);
  26468. }
  26469. });
  26470. }
  26471. };
  26472. }
  26473. };
  26474. }];
  26475. /* exported defaultModelOptions */
  26476. var defaultModelOptions;
  26477. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  26478. /**
  26479. * @ngdoc type
  26480. * @name ModelOptions
  26481. * @description
  26482. * A container for the options set by the {@link ngModelOptions} directive
  26483. */
  26484. function ModelOptions(options) {
  26485. this.$$options = options;
  26486. }
  26487. ModelOptions.prototype = {
  26488. /**
  26489. * @ngdoc method
  26490. * @name ModelOptions#getOption
  26491. * @param {string} name the name of the option to retrieve
  26492. * @returns {*} the value of the option
  26493. * @description
  26494. * Returns the value of the given option
  26495. */
  26496. getOption: function(name) {
  26497. return this.$$options[name];
  26498. },
  26499. /**
  26500. * @ngdoc method
  26501. * @name ModelOptions#createChild
  26502. * @param {Object} options a hash of options for the new child that will override the parent's options
  26503. * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
  26504. */
  26505. createChild: function(options) {
  26506. var inheritAll = false;
  26507. // make a shallow copy
  26508. options = extend({}, options);
  26509. // Inherit options from the parent if specified by the value `"$inherit"`
  26510. forEach(options, /* @this */ function(option, key) {
  26511. if (option === '$inherit') {
  26512. if (key === '*') {
  26513. inheritAll = true;
  26514. } else {
  26515. options[key] = this.$$options[key];
  26516. // `updateOn` is special so we must also inherit the `updateOnDefault` option
  26517. if (key === 'updateOn') {
  26518. options.updateOnDefault = this.$$options.updateOnDefault;
  26519. }
  26520. }
  26521. } else {
  26522. if (key === 'updateOn') {
  26523. // If the `updateOn` property contains the `default` event then we have to remove
  26524. // it from the event list and set the `updateOnDefault` flag.
  26525. options.updateOnDefault = false;
  26526. options[key] = trim(option.replace(DEFAULT_REGEXP, function() {
  26527. options.updateOnDefault = true;
  26528. return ' ';
  26529. }));
  26530. }
  26531. }
  26532. }, this);
  26533. if (inheritAll) {
  26534. // We have a property of the form: `"*": "$inherit"`
  26535. delete options['*'];
  26536. defaults(options, this.$$options);
  26537. }
  26538. // Finally add in any missing defaults
  26539. defaults(options, defaultModelOptions.$$options);
  26540. return new ModelOptions(options);
  26541. }
  26542. };
  26543. defaultModelOptions = new ModelOptions({
  26544. updateOn: '',
  26545. updateOnDefault: true,
  26546. debounce: 0,
  26547. getterSetter: false,
  26548. allowInvalid: false,
  26549. timezone: null
  26550. });
  26551. /**
  26552. * @ngdoc directive
  26553. * @name ngModelOptions
  26554. *
  26555. * @description
  26556. * This directive allows you to modify the behaviour of {@link ngModel} directives within your
  26557. * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}
  26558. * directives will use the options of their nearest `ngModelOptions` ancestor.
  26559. *
  26560. * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as
  26561. * an Angular expression. This expression should evaluate to an object, whose properties contain
  26562. * the settings. For example: `<div "ng-model-options"="{ debounce: 100 }"`.
  26563. *
  26564. * ## Inheriting Options
  26565. *
  26566. * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions`
  26567. * directive by giving it the value of `"$inherit"`.
  26568. * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the
  26569. * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings
  26570. * will be used.
  26571. *
  26572. * For example given the following fragment of HTML
  26573. *
  26574. *
  26575. * ```html
  26576. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  26577. * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }">
  26578. * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" />
  26579. * </form>
  26580. * </div>
  26581. * ```
  26582. *
  26583. * the `input` element will have the following settings
  26584. *
  26585. * ```js
  26586. * { allowInvalid: true, updateOn: 'default', debounce: 0 }
  26587. * ```
  26588. *
  26589. * Notice that the `debounce` setting was not inherited and used the default value instead.
  26590. *
  26591. * You can specify that all undefined settings are automatically inherited from an ancestor by
  26592. * including a property with key of `"*"` and value of `"$inherit"`.
  26593. *
  26594. * For example given the following fragment of HTML
  26595. *
  26596. *
  26597. * ```html
  26598. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  26599. * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }">
  26600. * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" />
  26601. * </form>
  26602. * </div>
  26603. * ```
  26604. *
  26605. * the `input` element will have the following settings
  26606. *
  26607. * ```js
  26608. * { allowInvalid: true, updateOn: 'default', debounce: 200 }
  26609. * ```
  26610. *
  26611. * Notice that the `debounce` setting now inherits the value from the outer `<div>` element.
  26612. *
  26613. * If you are creating a reusable component then you should be careful when using `"*": "$inherit"`
  26614. * since you may inadvertently inherit a setting in the future that changes the behavior of your component.
  26615. *
  26616. *
  26617. * ## Triggering and debouncing model updates
  26618. *
  26619. * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
  26620. * trigger a model update and/or a debouncing delay so that the actual update only takes place when
  26621. * a timer expires; this timer will be reset after another change takes place.
  26622. *
  26623. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  26624. * be different from the value in the actual model. This means that if you update the model you
  26625. * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in
  26626. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  26627. *
  26628. * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}
  26629. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  26630. * important because `form` controllers are published to the related scope under the name in their
  26631. * `name` attribute.
  26632. *
  26633. * Any pending changes will take place immediately when an enclosing form is submitted via the
  26634. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  26635. * to have access to the updated model.
  26636. *
  26637. * The following example shows how to override immediate updates. Changes on the inputs within the
  26638. * form will update the model only when the control loses focus (blur event). If `escape` key is
  26639. * pressed while the input field is focused, the value is reset to the value in the current model.
  26640. *
  26641. * <example name="ngModelOptions-directive-blur" module="optionsExample">
  26642. * <file name="index.html">
  26643. * <div ng-controller="ExampleController">
  26644. * <form name="userForm">
  26645. * <label>
  26646. * Name:
  26647. * <input type="text" name="userName"
  26648. * ng-model="user.name"
  26649. * ng-model-options="{ updateOn: 'blur' }"
  26650. * ng-keyup="cancel($event)" />
  26651. * </label><br />
  26652. * <label>
  26653. * Other data:
  26654. * <input type="text" ng-model="user.data" />
  26655. * </label><br />
  26656. * </form>
  26657. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  26658. * </div>
  26659. * </file>
  26660. * <file name="app.js">
  26661. * angular.module('optionsExample', [])
  26662. * .controller('ExampleController', ['$scope', function($scope) {
  26663. * $scope.user = { name: 'say', data: '' };
  26664. *
  26665. * $scope.cancel = function(e) {
  26666. * if (e.keyCode === 27) {
  26667. * $scope.userForm.userName.$rollbackViewValue();
  26668. * }
  26669. * };
  26670. * }]);
  26671. * </file>
  26672. * <file name="protractor.js" type="protractor">
  26673. * var model = element(by.binding('user.name'));
  26674. * var input = element(by.model('user.name'));
  26675. * var other = element(by.model('user.data'));
  26676. *
  26677. * it('should allow custom events', function() {
  26678. * input.sendKeys(' hello');
  26679. * input.click();
  26680. * expect(model.getText()).toEqual('say');
  26681. * other.click();
  26682. * expect(model.getText()).toEqual('say hello');
  26683. * });
  26684. *
  26685. * it('should $rollbackViewValue when model changes', function() {
  26686. * input.sendKeys(' hello');
  26687. * expect(input.getAttribute('value')).toEqual('say hello');
  26688. * input.sendKeys(protractor.Key.ESCAPE);
  26689. * expect(input.getAttribute('value')).toEqual('say');
  26690. * other.click();
  26691. * expect(model.getText()).toEqual('say');
  26692. * });
  26693. * </file>
  26694. * </example>
  26695. *
  26696. * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
  26697. * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  26698. *
  26699. * <example name="ngModelOptions-directive-debounce" module="optionsExample">
  26700. * <file name="index.html">
  26701. * <div ng-controller="ExampleController">
  26702. * <form name="userForm">
  26703. * Name:
  26704. * <input type="text" name="userName"
  26705. * ng-model="user.name"
  26706. * ng-model-options="{ debounce: 1000 }" />
  26707. * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  26708. * </form>
  26709. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  26710. * </div>
  26711. * </file>
  26712. * <file name="app.js">
  26713. * angular.module('optionsExample', [])
  26714. * .controller('ExampleController', ['$scope', function($scope) {
  26715. * $scope.user = { name: 'say' };
  26716. * }]);
  26717. * </file>
  26718. * </example>
  26719. *
  26720. * ## Model updates and validation
  26721. *
  26722. * The default behaviour in `ngModel` is that the model value is set to `undefined` when the
  26723. * validation determines that the value is invalid. By setting the `allowInvalid` property to true,
  26724. * the model will still be updated even if the value is invalid.
  26725. *
  26726. *
  26727. * ## Connecting to the scope
  26728. *
  26729. * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
  26730. * on the scope refers to a "getter/setter" function rather than the value itself.
  26731. *
  26732. * The following example shows how to bind to getter/setters:
  26733. *
  26734. * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  26735. * <file name="index.html">
  26736. * <div ng-controller="ExampleController">
  26737. * <form name="userForm">
  26738. * <label>
  26739. * Name:
  26740. * <input type="text" name="userName"
  26741. * ng-model="user.name"
  26742. * ng-model-options="{ getterSetter: true }" />
  26743. * </label>
  26744. * </form>
  26745. * <pre>user.name = <span ng-bind="user.name()"></span></pre>
  26746. * </div>
  26747. * </file>
  26748. * <file name="app.js">
  26749. * angular.module('getterSetterExample', [])
  26750. * .controller('ExampleController', ['$scope', function($scope) {
  26751. * var _name = 'Brian';
  26752. * $scope.user = {
  26753. * name: function(newName) {
  26754. * return angular.isDefined(newName) ? (_name = newName) : _name;
  26755. * }
  26756. * };
  26757. * }]);
  26758. * </file>
  26759. * </example>
  26760. *
  26761. *
  26762. * ## Specifying timezones
  26763. *
  26764. * You can specify the timezone that date/time input directives expect by providing its name in the
  26765. * `timezone` property.
  26766. *
  26767. * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and
  26768. * and its descendents. Valid keys are:
  26769. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  26770. * events using an space delimited list. There is a special event called `default` that
  26771. * matches the default events belonging to the control.
  26772. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  26773. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  26774. * custom value for each event. For example:
  26775. * ```
  26776. * ng-model-options="{
  26777. * updateOn: 'default blur',
  26778. * debounce: { 'default': 500, 'blur': 0 }
  26779. * }"
  26780. * ```
  26781. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  26782. * not validate correctly instead of the default behavior of setting the model to undefined.
  26783. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  26784. * `ngModel` as getters/setters.
  26785. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  26786. * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the
  26787. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  26788. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  26789. * If not specified, the timezone of the browser will be used.
  26790. *
  26791. */
  26792. var ngModelOptionsDirective = function() {
  26793. NgModelOptionsController.$inject = ['$attrs', '$scope'];
  26794. function NgModelOptionsController($attrs, $scope) {
  26795. this.$$attrs = $attrs;
  26796. this.$$scope = $scope;
  26797. }
  26798. NgModelOptionsController.prototype = {
  26799. $onInit: function() {
  26800. var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions;
  26801. var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions);
  26802. this.$options = parentOptions.createChild(modelOptionsDefinition);
  26803. }
  26804. };
  26805. return {
  26806. restrict: 'A',
  26807. // ngModelOptions needs to run before ngModel and input directives
  26808. priority: 10,
  26809. require: {parentCtrl: '?^^ngModelOptions'},
  26810. bindToController: true,
  26811. controller: NgModelOptionsController
  26812. };
  26813. };
  26814. // shallow copy over values from `src` that are not already specified on `dst`
  26815. function defaults(dst, src) {
  26816. forEach(src, function(value, key) {
  26817. if (!isDefined(dst[key])) {
  26818. dst[key] = value;
  26819. }
  26820. });
  26821. }
  26822. /**
  26823. * @ngdoc directive
  26824. * @name ngNonBindable
  26825. * @restrict AC
  26826. * @priority 1000
  26827. *
  26828. * @description
  26829. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  26830. * DOM element. This is useful if the element contains what appears to be Angular directives and
  26831. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  26832. * displays snippets of code, for instance.
  26833. *
  26834. * @element ANY
  26835. *
  26836. * @example
  26837. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  26838. * but the one wrapped in `ngNonBindable` is left alone.
  26839. *
  26840. * @example
  26841. <example name="ng-non-bindable">
  26842. <file name="index.html">
  26843. <div>Normal: {{1 + 2}}</div>
  26844. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  26845. </file>
  26846. <file name="protractor.js" type="protractor">
  26847. it('should check ng-non-bindable', function() {
  26848. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  26849. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  26850. });
  26851. </file>
  26852. </example>
  26853. */
  26854. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  26855. /* exported ngOptionsDirective */
  26856. /* global jqLiteRemove */
  26857. var ngOptionsMinErr = minErr('ngOptions');
  26858. /**
  26859. * @ngdoc directive
  26860. * @name ngOptions
  26861. * @restrict A
  26862. *
  26863. * @description
  26864. *
  26865. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  26866. * elements for the `<select>` element using the array or object obtained by evaluating the
  26867. * `ngOptions` comprehension expression.
  26868. *
  26869. * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of
  26870. * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits:
  26871. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  26872. * comprehension expression
  26873. * - reduced memory consumption by not creating a new scope for each repeated instance
  26874. * - increased render speed by creating the options in a documentFragment instead of individually
  26875. *
  26876. * When an item in the `<select>` menu is selected, the array element or object property
  26877. * represented by the selected option will be bound to the model identified by the `ngModel`
  26878. * directive.
  26879. *
  26880. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  26881. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  26882. * option. See example below for demonstration.
  26883. *
  26884. * ## Complex Models (objects or collections)
  26885. *
  26886. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  26887. * binding the select to a model that is an object or a collection.
  26888. *
  26889. * One issue occurs if you want to preselect an option. For example, if you set
  26890. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  26891. * because the objects are not identical. So by default, you should always reference the item in your collection
  26892. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  26893. *
  26894. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  26895. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  26896. * collection items have an id property, you would `track by item.id`.
  26897. *
  26898. * A different issue with objects or collections is that ngModel won't detect if an object property or
  26899. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  26900. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  26901. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  26902. * has not changed identity, but only a property on the object or an item in the collection changes.
  26903. *
  26904. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  26905. * if the model is an array). This means that changing a property deeper than the first level inside the
  26906. * object/collection will not trigger a re-rendering.
  26907. *
  26908. * ## `select` **`as`**
  26909. *
  26910. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  26911. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  26912. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  26913. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  26914. *
  26915. *
  26916. * ### `select` **`as`** and **`track by`**
  26917. *
  26918. * <div class="alert alert-warning">
  26919. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  26920. * </div>
  26921. *
  26922. * Given this array of items on the $scope:
  26923. *
  26924. * ```js
  26925. * $scope.items = [{
  26926. * id: 1,
  26927. * label: 'aLabel',
  26928. * subItem: { name: 'aSubItem' }
  26929. * }, {
  26930. * id: 2,
  26931. * label: 'bLabel',
  26932. * subItem: { name: 'bSubItem' }
  26933. * }];
  26934. * ```
  26935. *
  26936. * This will work:
  26937. *
  26938. * ```html
  26939. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  26940. * ```
  26941. * ```js
  26942. * $scope.selected = $scope.items[0];
  26943. * ```
  26944. *
  26945. * but this will not work:
  26946. *
  26947. * ```html
  26948. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  26949. * ```
  26950. * ```js
  26951. * $scope.selected = $scope.items[0].subItem;
  26952. * ```
  26953. *
  26954. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  26955. * `items` array. Because the selected option has been set programmatically in the controller, the
  26956. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  26957. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  26958. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  26959. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  26960. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  26961. *
  26962. *
  26963. * @param {string} ngModel Assignable angular expression to data-bind to.
  26964. * @param {string=} name Property name of the form under which the control is published.
  26965. * @param {string=} required The control is considered valid only if value is entered.
  26966. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  26967. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  26968. * `required` when you want to data-bind to the `required` attribute.
  26969. * @param {comprehension_expression=} ngOptions in one of the following forms:
  26970. *
  26971. * * for array data sources:
  26972. * * `label` **`for`** `value` **`in`** `array`
  26973. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  26974. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  26975. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  26976. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  26977. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  26978. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  26979. * (for including a filter with `track by`)
  26980. * * for object data sources:
  26981. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  26982. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  26983. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  26984. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  26985. * * `select` **`as`** `label` **`group by`** `group`
  26986. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  26987. * * `select` **`as`** `label` **`disable when`** `disable`
  26988. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  26989. *
  26990. * Where:
  26991. *
  26992. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  26993. * * `value`: local variable which will refer to each item in the `array` or each property value
  26994. * of `object` during iteration.
  26995. * * `key`: local variable which will refer to a property name in `object` during iteration.
  26996. * * `label`: The result of this expression will be the label for `<option>` element. The
  26997. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  26998. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  26999. * element. If not specified, `select` expression will default to `value`.
  27000. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  27001. * DOM element.
  27002. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  27003. * element. Return `true` to disable.
  27004. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  27005. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  27006. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  27007. * even when the options are recreated (e.g. reloaded from the server).
  27008. *
  27009. * @example
  27010. <example module="selectExample" name="select">
  27011. <file name="index.html">
  27012. <script>
  27013. angular.module('selectExample', [])
  27014. .controller('ExampleController', ['$scope', function($scope) {
  27015. $scope.colors = [
  27016. {name:'black', shade:'dark'},
  27017. {name:'white', shade:'light', notAnOption: true},
  27018. {name:'red', shade:'dark'},
  27019. {name:'blue', shade:'dark', notAnOption: true},
  27020. {name:'yellow', shade:'light', notAnOption: false}
  27021. ];
  27022. $scope.myColor = $scope.colors[2]; // red
  27023. }]);
  27024. </script>
  27025. <div ng-controller="ExampleController">
  27026. <ul>
  27027. <li ng-repeat="color in colors">
  27028. <label>Name: <input ng-model="color.name"></label>
  27029. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  27030. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  27031. </li>
  27032. <li>
  27033. <button ng-click="colors.push({})">add</button>
  27034. </li>
  27035. </ul>
  27036. <hr/>
  27037. <label>Color (null not allowed):
  27038. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  27039. </label><br/>
  27040. <label>Color (null allowed):
  27041. <span class="nullable">
  27042. <select ng-model="myColor" ng-options="color.name for color in colors">
  27043. <option value="">-- choose color --</option>
  27044. </select>
  27045. </span></label><br/>
  27046. <label>Color grouped by shade:
  27047. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  27048. </select>
  27049. </label><br/>
  27050. <label>Color grouped by shade, with some disabled:
  27051. <select ng-model="myColor"
  27052. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  27053. </select>
  27054. </label><br/>
  27055. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  27056. <br/>
  27057. <hr/>
  27058. Currently selected: {{ {selected_color:myColor} }}
  27059. <div style="border:solid 1px black; height:20px"
  27060. ng-style="{'background-color':myColor.name}">
  27061. </div>
  27062. </div>
  27063. </file>
  27064. <file name="protractor.js" type="protractor">
  27065. it('should check ng-options', function() {
  27066. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  27067. element.all(by.model('myColor')).first().click();
  27068. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  27069. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  27070. element(by.css('.nullable select[ng-model="myColor"]')).click();
  27071. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  27072. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  27073. });
  27074. </file>
  27075. </example>
  27076. */
  27077. /* eslint-disable max-len */
  27078. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999
  27079. 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]+?))?$/;
  27080. // 1: value expression (valueFn)
  27081. // 2: label expression (displayFn)
  27082. // 3: group by expression (groupByFn)
  27083. // 4: disable when expression (disableWhenFn)
  27084. // 5: array item variable name
  27085. // 6: object item key variable name
  27086. // 7: object item value variable name
  27087. // 8: collection expression
  27088. // 9: track by expression
  27089. /* eslint-enable */
  27090. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  27091. function parseOptionsExpression(optionsExp, selectElement, scope) {
  27092. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  27093. if (!(match)) {
  27094. throw ngOptionsMinErr('iexp',
  27095. 'Expected expression in form of ' +
  27096. '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
  27097. ' but got \'{0}\'. Element: {1}',
  27098. optionsExp, startingTag(selectElement));
  27099. }
  27100. // Extract the parts from the ngOptions expression
  27101. // The variable name for the value of the item in the collection
  27102. var valueName = match[5] || match[7];
  27103. // The variable name for the key of the item in the collection
  27104. var keyName = match[6];
  27105. // An expression that generates the viewValue for an option if there is a label expression
  27106. var selectAs = / as /.test(match[0]) && match[1];
  27107. // An expression that is used to track the id of each object in the options collection
  27108. var trackBy = match[9];
  27109. // An expression that generates the viewValue for an option if there is no label expression
  27110. var valueFn = $parse(match[2] ? match[1] : valueName);
  27111. var selectAsFn = selectAs && $parse(selectAs);
  27112. var viewValueFn = selectAsFn || valueFn;
  27113. var trackByFn = trackBy && $parse(trackBy);
  27114. // Get the value by which we are going to track the option
  27115. // if we have a trackFn then use that (passing scope and locals)
  27116. // otherwise just hash the given viewValue
  27117. var getTrackByValueFn = trackBy ?
  27118. function(value, locals) { return trackByFn(scope, locals); } :
  27119. function getHashOfValue(value) { return hashKey(value); };
  27120. var getTrackByValue = function(value, key) {
  27121. return getTrackByValueFn(value, getLocals(value, key));
  27122. };
  27123. var displayFn = $parse(match[2] || match[1]);
  27124. var groupByFn = $parse(match[3] || '');
  27125. var disableWhenFn = $parse(match[4] || '');
  27126. var valuesFn = $parse(match[8]);
  27127. var locals = {};
  27128. var getLocals = keyName ? function(value, key) {
  27129. locals[keyName] = key;
  27130. locals[valueName] = value;
  27131. return locals;
  27132. } : function(value) {
  27133. locals[valueName] = value;
  27134. return locals;
  27135. };
  27136. function Option(selectValue, viewValue, label, group, disabled) {
  27137. this.selectValue = selectValue;
  27138. this.viewValue = viewValue;
  27139. this.label = label;
  27140. this.group = group;
  27141. this.disabled = disabled;
  27142. }
  27143. function getOptionValuesKeys(optionValues) {
  27144. var optionValuesKeys;
  27145. if (!keyName && isArrayLike(optionValues)) {
  27146. optionValuesKeys = optionValues;
  27147. } else {
  27148. // if object, extract keys, in enumeration order, unsorted
  27149. optionValuesKeys = [];
  27150. for (var itemKey in optionValues) {
  27151. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  27152. optionValuesKeys.push(itemKey);
  27153. }
  27154. }
  27155. }
  27156. return optionValuesKeys;
  27157. }
  27158. return {
  27159. trackBy: trackBy,
  27160. getTrackByValue: getTrackByValue,
  27161. getWatchables: $parse(valuesFn, function(optionValues) {
  27162. // Create a collection of things that we would like to watch (watchedArray)
  27163. // so that they can all be watched using a single $watchCollection
  27164. // that only runs the handler once if anything changes
  27165. var watchedArray = [];
  27166. optionValues = optionValues || [];
  27167. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27168. var optionValuesLength = optionValuesKeys.length;
  27169. for (var index = 0; index < optionValuesLength; index++) {
  27170. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27171. var value = optionValues[key];
  27172. var locals = getLocals(value, key);
  27173. var selectValue = getTrackByValueFn(value, locals);
  27174. watchedArray.push(selectValue);
  27175. // Only need to watch the displayFn if there is a specific label expression
  27176. if (match[2] || match[1]) {
  27177. var label = displayFn(scope, locals);
  27178. watchedArray.push(label);
  27179. }
  27180. // Only need to watch the disableWhenFn if there is a specific disable expression
  27181. if (match[4]) {
  27182. var disableWhen = disableWhenFn(scope, locals);
  27183. watchedArray.push(disableWhen);
  27184. }
  27185. }
  27186. return watchedArray;
  27187. }),
  27188. getOptions: function() {
  27189. var optionItems = [];
  27190. var selectValueMap = {};
  27191. // The option values were already computed in the `getWatchables` fn,
  27192. // which must have been called to trigger `getOptions`
  27193. var optionValues = valuesFn(scope) || [];
  27194. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27195. var optionValuesLength = optionValuesKeys.length;
  27196. for (var index = 0; index < optionValuesLength; index++) {
  27197. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27198. var value = optionValues[key];
  27199. var locals = getLocals(value, key);
  27200. var viewValue = viewValueFn(scope, locals);
  27201. var selectValue = getTrackByValueFn(viewValue, locals);
  27202. var label = displayFn(scope, locals);
  27203. var group = groupByFn(scope, locals);
  27204. var disabled = disableWhenFn(scope, locals);
  27205. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  27206. optionItems.push(optionItem);
  27207. selectValueMap[selectValue] = optionItem;
  27208. }
  27209. return {
  27210. items: optionItems,
  27211. selectValueMap: selectValueMap,
  27212. getOptionFromViewValue: function(value) {
  27213. return selectValueMap[getTrackByValue(value)];
  27214. },
  27215. getViewValueFromOption: function(option) {
  27216. // If the viewValue could be an object that may be mutated by the application,
  27217. // we need to make a copy and not return the reference to the value on the option.
  27218. return trackBy ? copy(option.viewValue) : option.viewValue;
  27219. }
  27220. };
  27221. }
  27222. };
  27223. }
  27224. // we can't just jqLite('<option>') since jqLite is not smart enough
  27225. // to create it in <select> and IE barfs otherwise.
  27226. var optionTemplate = window.document.createElement('option'),
  27227. optGroupTemplate = window.document.createElement('optgroup');
  27228. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  27229. var selectCtrl = ctrls[0];
  27230. var ngModelCtrl = ctrls[1];
  27231. var multiple = attr.multiple;
  27232. // The emptyOption allows the application developer to provide their own custom "empty"
  27233. // option when the viewValue does not match any of the option values.
  27234. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  27235. if (children[i].value === '') {
  27236. selectCtrl.hasEmptyOption = true;
  27237. selectCtrl.emptyOption = children.eq(i);
  27238. break;
  27239. }
  27240. }
  27241. var providedEmptyOption = !!selectCtrl.emptyOption;
  27242. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  27243. unknownOption.val('?');
  27244. var options;
  27245. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  27246. // This stores the newly created options before they are appended to the select.
  27247. // Since the contents are removed from the fragment when it is appended,
  27248. // we only need to create it once.
  27249. var listFragment = $document[0].createDocumentFragment();
  27250. // Overwrite the implementation. ngOptions doesn't use hashes
  27251. selectCtrl.generateUnknownOptionValue = function(val) {
  27252. return '?';
  27253. };
  27254. // Update the controller methods for multiple selectable options
  27255. if (!multiple) {
  27256. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  27257. var selectedOption = options.selectValueMap[selectElement.val()];
  27258. var option = options.getOptionFromViewValue(value);
  27259. // Make sure to remove the selected attribute from the previously selected option
  27260. // Otherwise, screen readers might get confused
  27261. if (selectedOption) selectedOption.element.removeAttribute('selected');
  27262. if (option) {
  27263. // Don't update the option when it is already selected.
  27264. // For example, the browser will select the first option by default. In that case,
  27265. // most properties are set automatically - except the `selected` attribute, which we
  27266. // set always
  27267. if (selectElement[0].value !== option.selectValue) {
  27268. selectCtrl.removeUnknownOption();
  27269. selectCtrl.unselectEmptyOption();
  27270. selectElement[0].value = option.selectValue;
  27271. option.element.selected = true;
  27272. }
  27273. option.element.setAttribute('selected', 'selected');
  27274. } else {
  27275. if (providedEmptyOption) {
  27276. selectCtrl.selectEmptyOption();
  27277. } else if (selectCtrl.unknownOption.parent().length) {
  27278. selectCtrl.updateUnknownOption(value);
  27279. } else {
  27280. selectCtrl.renderUnknownOption(value);
  27281. }
  27282. }
  27283. };
  27284. selectCtrl.readValue = function readNgOptionsValue() {
  27285. var selectedOption = options.selectValueMap[selectElement.val()];
  27286. if (selectedOption && !selectedOption.disabled) {
  27287. selectCtrl.unselectEmptyOption();
  27288. selectCtrl.removeUnknownOption();
  27289. return options.getViewValueFromOption(selectedOption);
  27290. }
  27291. return null;
  27292. };
  27293. // If we are using `track by` then we must watch the tracked value on the model
  27294. // since ngModel only watches for object identity change
  27295. // FIXME: When a user selects an option, this watch will fire needlessly
  27296. if (ngOptions.trackBy) {
  27297. scope.$watch(
  27298. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  27299. function() { ngModelCtrl.$render(); }
  27300. );
  27301. }
  27302. } else {
  27303. selectCtrl.writeValue = function writeNgOptionsMultiple(values) {
  27304. // Only set `<option>.selected` if necessary, in order to prevent some browsers from
  27305. // scrolling to `<option>` elements that are outside the `<select>` element's viewport.
  27306. var selectedOptions = values && values.map(getAndUpdateSelectedOption) || [];
  27307. options.items.forEach(function(option) {
  27308. if (option.element.selected && !includes(selectedOptions, option)) {
  27309. option.element.selected = false;
  27310. }
  27311. });
  27312. };
  27313. selectCtrl.readValue = function readNgOptionsMultiple() {
  27314. var selectedValues = selectElement.val() || [],
  27315. selections = [];
  27316. forEach(selectedValues, function(value) {
  27317. var option = options.selectValueMap[value];
  27318. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  27319. });
  27320. return selections;
  27321. };
  27322. // If we are using `track by` then we must watch these tracked values on the model
  27323. // since ngModel only watches for object identity change
  27324. if (ngOptions.trackBy) {
  27325. scope.$watchCollection(function() {
  27326. if (isArray(ngModelCtrl.$viewValue)) {
  27327. return ngModelCtrl.$viewValue.map(function(value) {
  27328. return ngOptions.getTrackByValue(value);
  27329. });
  27330. }
  27331. }, function() {
  27332. ngModelCtrl.$render();
  27333. });
  27334. }
  27335. }
  27336. if (providedEmptyOption) {
  27337. // we need to remove it before calling selectElement.empty() because otherwise IE will
  27338. // remove the label from the element. wtf?
  27339. selectCtrl.emptyOption.remove();
  27340. // compile the element since there might be bindings in it
  27341. $compile(selectCtrl.emptyOption)(scope);
  27342. if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) {
  27343. // This means the empty option has currently no actual DOM node, probably because
  27344. // it has been modified by a transclusion directive.
  27345. selectCtrl.hasEmptyOption = false;
  27346. // Redefine the registerOption function, which will catch
  27347. // options that are added by ngIf etc. (rendering of the node is async because of
  27348. // lazy transclusion)
  27349. selectCtrl.registerOption = function(optionScope, optionEl) {
  27350. if (optionEl.val() === '') {
  27351. selectCtrl.hasEmptyOption = true;
  27352. selectCtrl.emptyOption = optionEl;
  27353. selectCtrl.emptyOption.removeClass('ng-scope');
  27354. // This ensures the new empty option is selected if previously no option was selected
  27355. ngModelCtrl.$render();
  27356. optionEl.on('$destroy', function() {
  27357. selectCtrl.hasEmptyOption = false;
  27358. selectCtrl.emptyOption = undefined;
  27359. });
  27360. }
  27361. };
  27362. } else {
  27363. // remove the class, which is added automatically because we recompile the element and it
  27364. // becomes the compilation root
  27365. selectCtrl.emptyOption.removeClass('ng-scope');
  27366. }
  27367. }
  27368. selectElement.empty();
  27369. // We need to do this here to ensure that the options object is defined
  27370. // when we first hit it in writeNgOptionsValue
  27371. updateOptions();
  27372. // We will re-render the option elements if the option values or labels change
  27373. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  27374. // ------------------------------------------------------------------ //
  27375. function addOptionElement(option, parent) {
  27376. var optionElement = optionTemplate.cloneNode(false);
  27377. parent.appendChild(optionElement);
  27378. updateOptionElement(option, optionElement);
  27379. }
  27380. function getAndUpdateSelectedOption(viewValue) {
  27381. var option = options.getOptionFromViewValue(viewValue);
  27382. var element = option && option.element;
  27383. if (element && !element.selected) element.selected = true;
  27384. return option;
  27385. }
  27386. function updateOptionElement(option, element) {
  27387. option.element = element;
  27388. element.disabled = option.disabled;
  27389. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  27390. // selects in certain circumstances when multiple selects are next to each other and display
  27391. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  27392. // See https://github.com/angular/angular.js/issues/11314 for more info.
  27393. // This is unfortunately untestable with unit / e2e tests
  27394. if (option.label !== element.label) {
  27395. element.label = option.label;
  27396. element.textContent = option.label;
  27397. }
  27398. element.value = option.selectValue;
  27399. }
  27400. function updateOptions() {
  27401. var previousValue = options && selectCtrl.readValue();
  27402. // We must remove all current options, but cannot simply set innerHTML = null
  27403. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  27404. // must preserve.
  27405. // Instead, iterate over the current option elements and remove them or their optgroup
  27406. // parents
  27407. if (options) {
  27408. for (var i = options.items.length - 1; i >= 0; i--) {
  27409. var option = options.items[i];
  27410. if (isDefined(option.group)) {
  27411. jqLiteRemove(option.element.parentNode);
  27412. } else {
  27413. jqLiteRemove(option.element);
  27414. }
  27415. }
  27416. }
  27417. options = ngOptions.getOptions();
  27418. var groupElementMap = {};
  27419. // Ensure that the empty option is always there if it was explicitly provided
  27420. if (providedEmptyOption) {
  27421. selectElement.prepend(selectCtrl.emptyOption);
  27422. }
  27423. options.items.forEach(function addOption(option) {
  27424. var groupElement;
  27425. if (isDefined(option.group)) {
  27426. // This option is to live in a group
  27427. // See if we have already created this group
  27428. groupElement = groupElementMap[option.group];
  27429. if (!groupElement) {
  27430. groupElement = optGroupTemplate.cloneNode(false);
  27431. listFragment.appendChild(groupElement);
  27432. // Update the label on the group element
  27433. // "null" is special cased because of Safari
  27434. groupElement.label = option.group === null ? 'null' : option.group;
  27435. // Store it for use later
  27436. groupElementMap[option.group] = groupElement;
  27437. }
  27438. addOptionElement(option, groupElement);
  27439. } else {
  27440. // This option is not in a group
  27441. addOptionElement(option, listFragment);
  27442. }
  27443. });
  27444. selectElement[0].appendChild(listFragment);
  27445. ngModelCtrl.$render();
  27446. // Check to see if the value has changed due to the update to the options
  27447. if (!ngModelCtrl.$isEmpty(previousValue)) {
  27448. var nextValue = selectCtrl.readValue();
  27449. var isNotPrimitive = ngOptions.trackBy || multiple;
  27450. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  27451. ngModelCtrl.$setViewValue(nextValue);
  27452. ngModelCtrl.$render();
  27453. }
  27454. }
  27455. }
  27456. }
  27457. return {
  27458. restrict: 'A',
  27459. terminal: true,
  27460. require: ['select', 'ngModel'],
  27461. link: {
  27462. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  27463. // Deactivate the SelectController.register method to prevent
  27464. // option directives from accidentally registering themselves
  27465. // (and unwanted $destroy handlers etc.)
  27466. ctrls[0].registerOption = noop;
  27467. },
  27468. post: ngOptionsPostLink
  27469. }
  27470. };
  27471. }];
  27472. /**
  27473. * @ngdoc directive
  27474. * @name ngPluralize
  27475. * @restrict EA
  27476. *
  27477. * @description
  27478. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  27479. * These rules are bundled with angular.js, but can be overridden
  27480. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  27481. * by specifying the mappings between
  27482. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  27483. * and the strings to be displayed.
  27484. *
  27485. * # Plural categories and explicit number rules
  27486. * There are two
  27487. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  27488. * in Angular's default en-US locale: "one" and "other".
  27489. *
  27490. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  27491. * any number that is not 1), an explicit number rule can only match one number. For example, the
  27492. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  27493. * and explicit number rules throughout the rest of this documentation.
  27494. *
  27495. * # Configuring ngPluralize
  27496. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  27497. * You can also provide an optional attribute, `offset`.
  27498. *
  27499. * The value of the `count` attribute can be either a string or an {@link guide/expression
  27500. * Angular expression}; these are evaluated on the current scope for its bound value.
  27501. *
  27502. * The `when` attribute specifies the mappings between plural categories and the actual
  27503. * string to be displayed. The value of the attribute should be a JSON object.
  27504. *
  27505. * The following example shows how to configure ngPluralize:
  27506. *
  27507. * ```html
  27508. * <ng-pluralize count="personCount"
  27509. when="{'0': 'Nobody is viewing.',
  27510. * 'one': '1 person is viewing.',
  27511. * 'other': '{} people are viewing.'}">
  27512. * </ng-pluralize>
  27513. *```
  27514. *
  27515. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  27516. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  27517. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  27518. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  27519. * show "a dozen people are viewing".
  27520. *
  27521. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  27522. * into pluralized strings. In the previous example, Angular will replace `{}` with
  27523. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  27524. * for <span ng-non-bindable>{{numberExpression}}</span>.
  27525. *
  27526. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  27527. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  27528. *
  27529. * # Configuring ngPluralize with offset
  27530. * The `offset` attribute allows further customization of pluralized text, which can result in
  27531. * a better user experience. For example, instead of the message "4 people are viewing this document",
  27532. * you might display "John, Kate and 2 others are viewing this document".
  27533. * The offset attribute allows you to offset a number by any desired value.
  27534. * Let's take a look at an example:
  27535. *
  27536. * ```html
  27537. * <ng-pluralize count="personCount" offset=2
  27538. * when="{'0': 'Nobody is viewing.',
  27539. * '1': '{{person1}} is viewing.',
  27540. * '2': '{{person1}} and {{person2}} are viewing.',
  27541. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  27542. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  27543. * </ng-pluralize>
  27544. * ```
  27545. *
  27546. * Notice that we are still using two plural categories(one, other), but we added
  27547. * three explicit number rules 0, 1 and 2.
  27548. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  27549. * When three people view the document, no explicit number rule is found, so
  27550. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  27551. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  27552. * is shown.
  27553. *
  27554. * Note that when you specify offsets, you must provide explicit number rules for
  27555. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  27556. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  27557. * plural categories "one" and "other".
  27558. *
  27559. * @param {string|expression} count The variable to be bound to.
  27560. * @param {string} when The mapping between plural category to its corresponding strings.
  27561. * @param {number=} offset Offset to deduct from the total number.
  27562. *
  27563. * @example
  27564. <example module="pluralizeExample" name="ng-pluralize">
  27565. <file name="index.html">
  27566. <script>
  27567. angular.module('pluralizeExample', [])
  27568. .controller('ExampleController', ['$scope', function($scope) {
  27569. $scope.person1 = 'Igor';
  27570. $scope.person2 = 'Misko';
  27571. $scope.personCount = 1;
  27572. }]);
  27573. </script>
  27574. <div ng-controller="ExampleController">
  27575. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  27576. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  27577. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  27578. <!--- Example with simple pluralization rules for en locale --->
  27579. Without Offset:
  27580. <ng-pluralize count="personCount"
  27581. when="{'0': 'Nobody is viewing.',
  27582. 'one': '1 person is viewing.',
  27583. 'other': '{} people are viewing.'}">
  27584. </ng-pluralize><br>
  27585. <!--- Example with offset --->
  27586. With Offset(2):
  27587. <ng-pluralize count="personCount" offset=2
  27588. when="{'0': 'Nobody is viewing.',
  27589. '1': '{{person1}} is viewing.',
  27590. '2': '{{person1}} and {{person2}} are viewing.',
  27591. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  27592. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  27593. </ng-pluralize>
  27594. </div>
  27595. </file>
  27596. <file name="protractor.js" type="protractor">
  27597. it('should show correct pluralized string', function() {
  27598. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  27599. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  27600. var countInput = element(by.model('personCount'));
  27601. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  27602. expect(withOffset.getText()).toEqual('Igor is viewing.');
  27603. countInput.clear();
  27604. countInput.sendKeys('0');
  27605. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  27606. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  27607. countInput.clear();
  27608. countInput.sendKeys('2');
  27609. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  27610. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  27611. countInput.clear();
  27612. countInput.sendKeys('3');
  27613. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  27614. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  27615. countInput.clear();
  27616. countInput.sendKeys('4');
  27617. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  27618. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  27619. });
  27620. it('should show data-bound names', function() {
  27621. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  27622. var personCount = element(by.model('personCount'));
  27623. var person1 = element(by.model('person1'));
  27624. var person2 = element(by.model('person2'));
  27625. personCount.clear();
  27626. personCount.sendKeys('4');
  27627. person1.clear();
  27628. person1.sendKeys('Di');
  27629. person2.clear();
  27630. person2.sendKeys('Vojta');
  27631. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  27632. });
  27633. </file>
  27634. </example>
  27635. */
  27636. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  27637. var BRACE = /{}/g,
  27638. IS_WHEN = /^when(Minus)?(.+)$/;
  27639. return {
  27640. link: function(scope, element, attr) {
  27641. var numberExp = attr.count,
  27642. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  27643. offset = attr.offset || 0,
  27644. whens = scope.$eval(whenExp) || {},
  27645. whensExpFns = {},
  27646. startSymbol = $interpolate.startSymbol(),
  27647. endSymbol = $interpolate.endSymbol(),
  27648. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  27649. watchRemover = angular.noop,
  27650. lastCount;
  27651. forEach(attr, function(expression, attributeName) {
  27652. var tmpMatch = IS_WHEN.exec(attributeName);
  27653. if (tmpMatch) {
  27654. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  27655. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  27656. }
  27657. });
  27658. forEach(whens, function(expression, key) {
  27659. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  27660. });
  27661. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  27662. var count = parseFloat(newVal);
  27663. var countIsNaN = isNumberNaN(count);
  27664. if (!countIsNaN && !(count in whens)) {
  27665. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  27666. // Otherwise, check it against pluralization rules in $locale service.
  27667. count = $locale.pluralCat(count - offset);
  27668. }
  27669. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  27670. // In JS `NaN !== NaN`, so we have to explicitly check.
  27671. if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
  27672. watchRemover();
  27673. var whenExpFn = whensExpFns[count];
  27674. if (isUndefined(whenExpFn)) {
  27675. if (newVal != null) {
  27676. $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
  27677. }
  27678. watchRemover = noop;
  27679. updateElementText();
  27680. } else {
  27681. watchRemover = scope.$watch(whenExpFn, updateElementText);
  27682. }
  27683. lastCount = count;
  27684. }
  27685. });
  27686. function updateElementText(newText) {
  27687. element.text(newText || '');
  27688. }
  27689. }
  27690. };
  27691. }];
  27692. /* exported ngRepeatDirective */
  27693. /**
  27694. * @ngdoc directive
  27695. * @name ngRepeat
  27696. * @multiElement
  27697. *
  27698. * @description
  27699. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  27700. * instance gets its own scope, where the given loop variable is set to the current collection item,
  27701. * and `$index` is set to the item index or key.
  27702. *
  27703. * Special properties are exposed on the local scope of each template instance, including:
  27704. *
  27705. * | Variable | Type | Details |
  27706. * |-----------|-----------------|-----------------------------------------------------------------------------|
  27707. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  27708. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  27709. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  27710. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  27711. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  27712. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  27713. *
  27714. * <div class="alert alert-info">
  27715. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  27716. * This may be useful when, for instance, nesting ngRepeats.
  27717. * </div>
  27718. *
  27719. *
  27720. * # Iterating over object properties
  27721. *
  27722. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  27723. * syntax:
  27724. *
  27725. * ```js
  27726. * <div ng-repeat="(key, value) in myObj"> ... </div>
  27727. * ```
  27728. *
  27729. * However, there are a few limitations compared to array iteration:
  27730. *
  27731. * - The JavaScript specification does not define the order of keys
  27732. * returned for an object, so Angular relies on the order returned by the browser
  27733. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  27734. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  27735. * and reinstated. See the
  27736. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  27737. *
  27738. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  27739. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  27740. *
  27741. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  27742. * objects, and will throw an error if used with one.
  27743. *
  27744. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  27745. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  27746. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  27747. * or implement a `$watch` on the object yourself.
  27748. *
  27749. *
  27750. * # Tracking and Duplicates
  27751. *
  27752. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  27753. * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:
  27754. *
  27755. * * When an item is added, a new instance of the template is added to the DOM.
  27756. * * When an item is removed, its template instance is removed from the DOM.
  27757. * * When items are reordered, their respective templates are reordered in the DOM.
  27758. *
  27759. * To minimize creation of DOM elements, `ngRepeat` uses a function
  27760. * to "keep track" of all items in the collection and their corresponding DOM elements.
  27761. * For example, if an item is added to the collection, `ngRepeat` will know that all other items
  27762. * already have DOM elements, and will not re-render them.
  27763. *
  27764. * The default tracking function (which tracks items by their identity) does not allow
  27765. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  27766. * to maintain a one-to-one mapping between collection items and DOM elements.
  27767. *
  27768. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  27769. * with your own using the `track by` expression.
  27770. *
  27771. * For example, you may track items by the index of each item in the collection, using the
  27772. * special scope property `$index`:
  27773. * ```html
  27774. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  27775. * {{n}}
  27776. * </div>
  27777. * ```
  27778. *
  27779. * You may also use arbitrary expressions in `track by`, including references to custom functions
  27780. * on the scope:
  27781. * ```html
  27782. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  27783. * {{n}}
  27784. * </div>
  27785. * ```
  27786. *
  27787. * <div class="alert alert-success">
  27788. * If you are working with objects that have a unique identifier property, you should track
  27789. * by this identifier instead of the object instance. Should you reload your data later, `ngRepeat`
  27790. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  27791. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  27792. * this significantly improves rendering performance. If you don't have a unique identifier,
  27793. * `track by $index` can also provide a performance boost.
  27794. * </div>
  27795. *
  27796. * ```html
  27797. * <div ng-repeat="model in collection track by model.id">
  27798. * {{model.name}}
  27799. * </div>
  27800. * ```
  27801. *
  27802. * <br />
  27803. * <div class="alert alert-warning">
  27804. * Avoid using `track by $index` when the repeated template contains
  27805. * {@link guide/expression#one-time-binding one-time bindings}. In such cases, the `nth` DOM
  27806. * element will always be matched with the `nth` item of the array, so the bindings on that element
  27807. * will not be updated even when the corresponding item changes, essentially causing the view to get
  27808. * out-of-sync with the underlying data.
  27809. * </div>
  27810. *
  27811. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  27812. * `$id` function, which tracks items by their identity:
  27813. * ```html
  27814. * <div ng-repeat="obj in collection track by $id(obj)">
  27815. * {{obj.prop}}
  27816. * </div>
  27817. * ```
  27818. *
  27819. * <br />
  27820. * <div class="alert alert-warning">
  27821. * **Note:** `track by` must always be the last expression:
  27822. * </div>
  27823. * ```
  27824. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  27825. * {{model.name}}
  27826. * </div>
  27827. * ```
  27828. *
  27829. *
  27830. * # Special repeat start and end points
  27831. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  27832. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  27833. * 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)
  27834. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  27835. *
  27836. * The example below makes use of this feature:
  27837. * ```html
  27838. * <header ng-repeat-start="item in items">
  27839. * Header {{ item }}
  27840. * </header>
  27841. * <div class="body">
  27842. * Body {{ item }}
  27843. * </div>
  27844. * <footer ng-repeat-end>
  27845. * Footer {{ item }}
  27846. * </footer>
  27847. * ```
  27848. *
  27849. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  27850. * ```html
  27851. * <header>
  27852. * Header A
  27853. * </header>
  27854. * <div class="body">
  27855. * Body A
  27856. * </div>
  27857. * <footer>
  27858. * Footer A
  27859. * </footer>
  27860. * <header>
  27861. * Header B
  27862. * </header>
  27863. * <div class="body">
  27864. * Body B
  27865. * </div>
  27866. * <footer>
  27867. * Footer B
  27868. * </footer>
  27869. * ```
  27870. *
  27871. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  27872. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  27873. *
  27874. * @animations
  27875. * | Animation | Occurs |
  27876. * |----------------------------------|-------------------------------------|
  27877. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  27878. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  27879. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  27880. *
  27881. * See the example below for defining CSS animations with ngRepeat.
  27882. *
  27883. * @element ANY
  27884. * @scope
  27885. * @priority 1000
  27886. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  27887. * formats are currently supported:
  27888. *
  27889. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  27890. * is a scope expression giving the collection to enumerate.
  27891. *
  27892. * For example: `album in artist.albums`.
  27893. *
  27894. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  27895. * and `expression` is the scope expression giving the collection to enumerate.
  27896. *
  27897. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  27898. *
  27899. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  27900. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  27901. * is specified, ng-repeat associates elements by identity. It is an error to have
  27902. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  27903. * mapped to the same DOM element, which is not possible.)
  27904. *
  27905. * Note that the tracking expression must come last, after any filters, and the alias expression.
  27906. *
  27907. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  27908. * will be associated by item identity in the array.
  27909. *
  27910. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  27911. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  27912. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  27913. * element in the same way in the DOM.
  27914. *
  27915. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  27916. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  27917. * property is same.
  27918. *
  27919. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  27920. * to items in conjunction with a tracking expression.
  27921. *
  27922. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  27923. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  27924. * when a filter is active on the repeater, but the filtered result set is empty.
  27925. *
  27926. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  27927. * the items have been processed through the filter.
  27928. *
  27929. * Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
  27930. * (and not as operator, inside an expression).
  27931. *
  27932. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  27933. *
  27934. * @example
  27935. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  27936. * results by name or by age. New (entering) and removed (leaving) items are animated.
  27937. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true" name="ng-repeat">
  27938. <file name="index.html">
  27939. <div ng-controller="repeatController">
  27940. I have {{friends.length}} friends. They are:
  27941. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  27942. <ul class="example-animate-container">
  27943. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  27944. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  27945. </li>
  27946. <li class="animate-repeat" ng-if="results.length === 0">
  27947. <strong>No results found...</strong>
  27948. </li>
  27949. </ul>
  27950. </div>
  27951. </file>
  27952. <file name="script.js">
  27953. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  27954. $scope.friends = [
  27955. {name:'John', age:25, gender:'boy'},
  27956. {name:'Jessie', age:30, gender:'girl'},
  27957. {name:'Johanna', age:28, gender:'girl'},
  27958. {name:'Joy', age:15, gender:'girl'},
  27959. {name:'Mary', age:28, gender:'girl'},
  27960. {name:'Peter', age:95, gender:'boy'},
  27961. {name:'Sebastian', age:50, gender:'boy'},
  27962. {name:'Erika', age:27, gender:'girl'},
  27963. {name:'Patrick', age:40, gender:'boy'},
  27964. {name:'Samantha', age:60, gender:'girl'}
  27965. ];
  27966. });
  27967. </file>
  27968. <file name="animations.css">
  27969. .example-animate-container {
  27970. background:white;
  27971. border:1px solid black;
  27972. list-style:none;
  27973. margin:0;
  27974. padding:0 10px;
  27975. }
  27976. .animate-repeat {
  27977. line-height:30px;
  27978. list-style:none;
  27979. box-sizing:border-box;
  27980. }
  27981. .animate-repeat.ng-move,
  27982. .animate-repeat.ng-enter,
  27983. .animate-repeat.ng-leave {
  27984. transition:all linear 0.5s;
  27985. }
  27986. .animate-repeat.ng-leave.ng-leave-active,
  27987. .animate-repeat.ng-move,
  27988. .animate-repeat.ng-enter {
  27989. opacity:0;
  27990. max-height:0;
  27991. }
  27992. .animate-repeat.ng-leave,
  27993. .animate-repeat.ng-move.ng-move-active,
  27994. .animate-repeat.ng-enter.ng-enter-active {
  27995. opacity:1;
  27996. max-height:30px;
  27997. }
  27998. </file>
  27999. <file name="protractor.js" type="protractor">
  28000. var friends = element.all(by.repeater('friend in friends'));
  28001. it('should render initial data set', function() {
  28002. expect(friends.count()).toBe(10);
  28003. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  28004. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  28005. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  28006. expect(element(by.binding('friends.length')).getText())
  28007. .toMatch("I have 10 friends. They are:");
  28008. });
  28009. it('should update repeater when filter predicate changes', function() {
  28010. expect(friends.count()).toBe(10);
  28011. element(by.model('q')).sendKeys('ma');
  28012. expect(friends.count()).toBe(2);
  28013. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  28014. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  28015. });
  28016. </file>
  28017. </example>
  28018. */
  28019. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  28020. var NG_REMOVED = '$$NG_REMOVED';
  28021. var ngRepeatMinErr = minErr('ngRepeat');
  28022. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  28023. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  28024. scope[valueIdentifier] = value;
  28025. if (keyIdentifier) scope[keyIdentifier] = key;
  28026. scope.$index = index;
  28027. scope.$first = (index === 0);
  28028. scope.$last = (index === (arrayLength - 1));
  28029. scope.$middle = !(scope.$first || scope.$last);
  28030. // eslint-disable-next-line no-bitwise
  28031. scope.$odd = !(scope.$even = (index & 1) === 0);
  28032. };
  28033. var getBlockStart = function(block) {
  28034. return block.clone[0];
  28035. };
  28036. var getBlockEnd = function(block) {
  28037. return block.clone[block.clone.length - 1];
  28038. };
  28039. return {
  28040. restrict: 'A',
  28041. multiElement: true,
  28042. transclude: 'element',
  28043. priority: 1000,
  28044. terminal: true,
  28045. $$tlb: true,
  28046. compile: function ngRepeatCompile($element, $attr) {
  28047. var expression = $attr.ngRepeat;
  28048. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  28049. 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*$/);
  28050. if (!match) {
  28051. throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
  28052. expression);
  28053. }
  28054. var lhs = match[1];
  28055. var rhs = match[2];
  28056. var aliasAs = match[3];
  28057. var trackByExp = match[4];
  28058. match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
  28059. if (!match) {
  28060. throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
  28061. lhs);
  28062. }
  28063. var valueIdentifier = match[3] || match[1];
  28064. var keyIdentifier = match[2];
  28065. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  28066. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  28067. throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
  28068. aliasAs);
  28069. }
  28070. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  28071. var hashFnLocals = {$id: hashKey};
  28072. if (trackByExp) {
  28073. trackByExpGetter = $parse(trackByExp);
  28074. } else {
  28075. trackByIdArrayFn = function(key, value) {
  28076. return hashKey(value);
  28077. };
  28078. trackByIdObjFn = function(key) {
  28079. return key;
  28080. };
  28081. }
  28082. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  28083. if (trackByExpGetter) {
  28084. trackByIdExpFn = function(key, value, index) {
  28085. // assign key, value, and $index to the locals so that they can be used in hash functions
  28086. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  28087. hashFnLocals[valueIdentifier] = value;
  28088. hashFnLocals.$index = index;
  28089. return trackByExpGetter($scope, hashFnLocals);
  28090. };
  28091. }
  28092. // Store a list of elements from previous run. This is a hash where key is the item from the
  28093. // iterator, and the value is objects with following properties.
  28094. // - scope: bound scope
  28095. // - element: previous element.
  28096. // - index: position
  28097. //
  28098. // We are using no-proto object so that we don't need to guard against inherited props via
  28099. // hasOwnProperty.
  28100. var lastBlockMap = createMap();
  28101. //watch props
  28102. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  28103. var index, length,
  28104. previousNode = $element[0], // node that cloned nodes should be inserted after
  28105. // initialized to the comment node anchor
  28106. nextNode,
  28107. // Same as lastBlockMap but it has the current state. It will become the
  28108. // lastBlockMap on the next iteration.
  28109. nextBlockMap = createMap(),
  28110. collectionLength,
  28111. key, value, // key/value of iteration
  28112. trackById,
  28113. trackByIdFn,
  28114. collectionKeys,
  28115. block, // last object information {scope, element, id}
  28116. nextBlockOrder,
  28117. elementsToRemove;
  28118. if (aliasAs) {
  28119. $scope[aliasAs] = collection;
  28120. }
  28121. if (isArrayLike(collection)) {
  28122. collectionKeys = collection;
  28123. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  28124. } else {
  28125. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  28126. // if object, extract keys, in enumeration order, unsorted
  28127. collectionKeys = [];
  28128. for (var itemKey in collection) {
  28129. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  28130. collectionKeys.push(itemKey);
  28131. }
  28132. }
  28133. }
  28134. collectionLength = collectionKeys.length;
  28135. nextBlockOrder = new Array(collectionLength);
  28136. // locate existing items
  28137. for (index = 0; index < collectionLength; index++) {
  28138. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28139. value = collection[key];
  28140. trackById = trackByIdFn(key, value, index);
  28141. if (lastBlockMap[trackById]) {
  28142. // found previously seen block
  28143. block = lastBlockMap[trackById];
  28144. delete lastBlockMap[trackById];
  28145. nextBlockMap[trackById] = block;
  28146. nextBlockOrder[index] = block;
  28147. } else if (nextBlockMap[trackById]) {
  28148. // if collision detected. restore lastBlockMap and throw an error
  28149. forEach(nextBlockOrder, function(block) {
  28150. if (block && block.scope) lastBlockMap[block.id] = block;
  28151. });
  28152. throw ngRepeatMinErr('dupes',
  28153. 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
  28154. expression, trackById, value);
  28155. } else {
  28156. // new never before seen block
  28157. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  28158. nextBlockMap[trackById] = true;
  28159. }
  28160. }
  28161. // remove leftover items
  28162. for (var blockKey in lastBlockMap) {
  28163. block = lastBlockMap[blockKey];
  28164. elementsToRemove = getBlockNodes(block.clone);
  28165. $animate.leave(elementsToRemove);
  28166. if (elementsToRemove[0].parentNode) {
  28167. // if the element was not removed yet because of pending animation, mark it as deleted
  28168. // so that we can ignore it later
  28169. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  28170. elementsToRemove[index][NG_REMOVED] = true;
  28171. }
  28172. }
  28173. block.scope.$destroy();
  28174. }
  28175. // we are not using forEach for perf reasons (trying to avoid #call)
  28176. for (index = 0; index < collectionLength; index++) {
  28177. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28178. value = collection[key];
  28179. block = nextBlockOrder[index];
  28180. if (block.scope) {
  28181. // if we have already seen this object, then we need to reuse the
  28182. // associated scope/element
  28183. nextNode = previousNode;
  28184. // skip nodes that are already pending removal via leave animation
  28185. do {
  28186. nextNode = nextNode.nextSibling;
  28187. } while (nextNode && nextNode[NG_REMOVED]);
  28188. if (getBlockStart(block) !== nextNode) {
  28189. // existing item which got moved
  28190. $animate.move(getBlockNodes(block.clone), null, previousNode);
  28191. }
  28192. previousNode = getBlockEnd(block);
  28193. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28194. } else {
  28195. // new item which we don't know about
  28196. $transclude(function ngRepeatTransclude(clone, scope) {
  28197. block.scope = scope;
  28198. // http://jsperf.com/clone-vs-createcomment
  28199. var endNode = ngRepeatEndComment.cloneNode(false);
  28200. clone[clone.length++] = endNode;
  28201. $animate.enter(clone, null, previousNode);
  28202. previousNode = endNode;
  28203. // Note: We only need the first/last node of the cloned nodes.
  28204. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  28205. // by a directive with templateUrl when its template arrives.
  28206. block.clone = clone;
  28207. nextBlockMap[block.id] = block;
  28208. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28209. });
  28210. }
  28211. }
  28212. lastBlockMap = nextBlockMap;
  28213. });
  28214. };
  28215. }
  28216. };
  28217. }];
  28218. var NG_HIDE_CLASS = 'ng-hide';
  28219. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  28220. /**
  28221. * @ngdoc directive
  28222. * @name ngShow
  28223. * @multiElement
  28224. *
  28225. * @description
  28226. * The `ngShow` directive shows or hides the given HTML element based on the expression provided to
  28227. * the `ngShow` attribute.
  28228. *
  28229. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  28230. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  28231. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  28232. * {@link ng.directive:ngCsp ngCsp}).
  28233. *
  28234. * ```html
  28235. * <!-- when $scope.myValue is truthy (element is visible) -->
  28236. * <div ng-show="myValue"></div>
  28237. *
  28238. * <!-- when $scope.myValue is falsy (element is hidden) -->
  28239. * <div ng-show="myValue" class="ng-hide"></div>
  28240. * ```
  28241. *
  28242. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added
  28243. * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide`
  28244. * CSS class is removed from the element causing the element not to appear hidden.
  28245. *
  28246. * ## Why is `!important` used?
  28247. *
  28248. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  28249. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  28250. * simple as changing the display style on a HTML list item would make hidden elements appear
  28251. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  28252. *
  28253. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  28254. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  28255. * developer chooses to override the styling to change how to hide an element then it is just a
  28256. * matter of using `!important` in their own CSS code.
  28257. *
  28258. * ### Overriding `.ng-hide`
  28259. *
  28260. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  28261. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  28262. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  28263. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  28264. *
  28265. * ```css
  28266. * .ng-hide:not(.ng-hide-animate) {
  28267. * /&#42; These are just alternative ways of hiding an element &#42;/
  28268. * display: block!important;
  28269. * position: absolute;
  28270. * top: -9999px;
  28271. * left: -9999px;
  28272. * }
  28273. * ```
  28274. *
  28275. * By default you don't need to override anything in CSS and the animations will work around the
  28276. * display style.
  28277. *
  28278. * ## A note about animations with `ngShow`
  28279. *
  28280. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  28281. * directive expression is true and false. This system works like the animation system present with
  28282. * `ngClass` except that you must also include the `!important` flag to override the display
  28283. * property so that the elements are not actually hidden during the animation.
  28284. *
  28285. * ```css
  28286. * /&#42; A working example can be found at the bottom of this page. &#42;/
  28287. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28288. * transition: all 0.5s linear;
  28289. * }
  28290. *
  28291. * .my-element.ng-hide-add { ... }
  28292. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  28293. * .my-element.ng-hide-remove { ... }
  28294. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  28295. * ```
  28296. *
  28297. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  28298. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  28299. *
  28300. * @animations
  28301. * | Animation | Occurs |
  28302. * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
  28303. * | {@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. |
  28304. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. |
  28305. *
  28306. * @element ANY
  28307. * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the
  28308. * element is shown/hidden respectively.
  28309. *
  28310. * @example
  28311. * A simple example, animating the element's opacity:
  28312. *
  28313. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-simple">
  28314. <file name="index.html">
  28315. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  28316. <div class="check-element animate-show-hide" ng-show="checked">
  28317. I show up when your checkbox is checked.
  28318. </div>
  28319. </file>
  28320. <file name="animations.css">
  28321. .animate-show-hide.ng-hide {
  28322. opacity: 0;
  28323. }
  28324. .animate-show-hide.ng-hide-add,
  28325. .animate-show-hide.ng-hide-remove {
  28326. transition: all linear 0.5s;
  28327. }
  28328. .check-element {
  28329. border: 1px solid black;
  28330. opacity: 1;
  28331. padding: 10px;
  28332. }
  28333. </file>
  28334. <file name="protractor.js" type="protractor">
  28335. it('should check ngShow', function() {
  28336. var checkbox = element(by.model('checked'));
  28337. var checkElem = element(by.css('.check-element'));
  28338. expect(checkElem.isDisplayed()).toBe(false);
  28339. checkbox.click();
  28340. expect(checkElem.isDisplayed()).toBe(true);
  28341. });
  28342. </file>
  28343. </example>
  28344. *
  28345. * <hr />
  28346. * @example
  28347. * A more complex example, featuring different show/hide animations:
  28348. *
  28349. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-complex">
  28350. <file name="index.html">
  28351. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  28352. <div class="check-element funky-show-hide" ng-show="checked">
  28353. I show up when your checkbox is checked.
  28354. </div>
  28355. </file>
  28356. <file name="animations.css">
  28357. body {
  28358. overflow: hidden;
  28359. perspective: 1000px;
  28360. }
  28361. .funky-show-hide.ng-hide-add {
  28362. transform: rotateZ(0);
  28363. transform-origin: right;
  28364. transition: all 0.5s ease-in-out;
  28365. }
  28366. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  28367. transform: rotateZ(-135deg);
  28368. }
  28369. .funky-show-hide.ng-hide-remove {
  28370. transform: rotateY(90deg);
  28371. transform-origin: left;
  28372. transition: all 0.5s ease;
  28373. }
  28374. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  28375. transform: rotateY(0);
  28376. }
  28377. .check-element {
  28378. border: 1px solid black;
  28379. opacity: 1;
  28380. padding: 10px;
  28381. }
  28382. </file>
  28383. <file name="protractor.js" type="protractor">
  28384. it('should check ngShow', function() {
  28385. var checkbox = element(by.model('checked'));
  28386. var checkElem = element(by.css('.check-element'));
  28387. expect(checkElem.isDisplayed()).toBe(false);
  28388. checkbox.click();
  28389. expect(checkElem.isDisplayed()).toBe(true);
  28390. });
  28391. </file>
  28392. </example>
  28393. */
  28394. var ngShowDirective = ['$animate', function($animate) {
  28395. return {
  28396. restrict: 'A',
  28397. multiElement: true,
  28398. link: function(scope, element, attr) {
  28399. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  28400. // we're adding a temporary, animation-specific class for ng-hide since this way
  28401. // we can control when the element is actually displayed on screen without having
  28402. // to have a global/greedy CSS selector that breaks when other animations are run.
  28403. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  28404. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  28405. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  28406. });
  28407. });
  28408. }
  28409. };
  28410. }];
  28411. /**
  28412. * @ngdoc directive
  28413. * @name ngHide
  28414. * @multiElement
  28415. *
  28416. * @description
  28417. * The `ngHide` directive shows or hides the given HTML element based on the expression provided to
  28418. * the `ngHide` attribute.
  28419. *
  28420. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  28421. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  28422. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  28423. * {@link ng.directive:ngCsp ngCsp}).
  28424. *
  28425. * ```html
  28426. * <!-- when $scope.myValue is truthy (element is hidden) -->
  28427. * <div ng-hide="myValue" class="ng-hide"></div>
  28428. *
  28429. * <!-- when $scope.myValue is falsy (element is visible) -->
  28430. * <div ng-hide="myValue"></div>
  28431. * ```
  28432. *
  28433. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added
  28434. * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide`
  28435. * CSS class is removed from the element causing the element not to appear hidden.
  28436. *
  28437. * ## Why is `!important` used?
  28438. *
  28439. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  28440. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  28441. * simple as changing the display style on a HTML list item would make hidden elements appear
  28442. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  28443. *
  28444. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  28445. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  28446. * developer chooses to override the styling to change how to hide an element then it is just a
  28447. * matter of using `!important` in their own CSS code.
  28448. *
  28449. * ### Overriding `.ng-hide`
  28450. *
  28451. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  28452. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  28453. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  28454. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  28455. *
  28456. * ```css
  28457. * .ng-hide:not(.ng-hide-animate) {
  28458. * /&#42; These are just alternative ways of hiding an element &#42;/
  28459. * display: block!important;
  28460. * position: absolute;
  28461. * top: -9999px;
  28462. * left: -9999px;
  28463. * }
  28464. * ```
  28465. *
  28466. * By default you don't need to override in CSS anything and the animations will work around the
  28467. * display style.
  28468. *
  28469. * ## A note about animations with `ngHide`
  28470. *
  28471. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  28472. * directive expression is true and false. This system works like the animation system present with
  28473. * `ngClass` except that you must also include the `!important` flag to override the display
  28474. * property so that the elements are not actually hidden during the animation.
  28475. *
  28476. * ```css
  28477. * /&#42; A working example can be found at the bottom of this page. &#42;/
  28478. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28479. * transition: all 0.5s linear;
  28480. * }
  28481. *
  28482. * .my-element.ng-hide-add { ... }
  28483. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  28484. * .my-element.ng-hide-remove { ... }
  28485. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  28486. * ```
  28487. *
  28488. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  28489. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  28490. *
  28491. * @animations
  28492. * | Animation | Occurs |
  28493. * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------|
  28494. * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. |
  28495. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. |
  28496. *
  28497. *
  28498. * @element ANY
  28499. * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the
  28500. * element is hidden/shown respectively.
  28501. *
  28502. * @example
  28503. * A simple example, animating the element's opacity:
  28504. *
  28505. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-simple">
  28506. <file name="index.html">
  28507. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  28508. <div class="check-element animate-show-hide" ng-hide="checked">
  28509. I hide when your checkbox is checked.
  28510. </div>
  28511. </file>
  28512. <file name="animations.css">
  28513. .animate-show-hide.ng-hide {
  28514. opacity: 0;
  28515. }
  28516. .animate-show-hide.ng-hide-add,
  28517. .animate-show-hide.ng-hide-remove {
  28518. transition: all linear 0.5s;
  28519. }
  28520. .check-element {
  28521. border: 1px solid black;
  28522. opacity: 1;
  28523. padding: 10px;
  28524. }
  28525. </file>
  28526. <file name="protractor.js" type="protractor">
  28527. it('should check ngHide', function() {
  28528. var checkbox = element(by.model('checked'));
  28529. var checkElem = element(by.css('.check-element'));
  28530. expect(checkElem.isDisplayed()).toBe(true);
  28531. checkbox.click();
  28532. expect(checkElem.isDisplayed()).toBe(false);
  28533. });
  28534. </file>
  28535. </example>
  28536. *
  28537. * <hr />
  28538. * @example
  28539. * A more complex example, featuring different show/hide animations:
  28540. *
  28541. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-complex">
  28542. <file name="index.html">
  28543. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  28544. <div class="check-element funky-show-hide" ng-hide="checked">
  28545. I hide when your checkbox is checked.
  28546. </div>
  28547. </file>
  28548. <file name="animations.css">
  28549. body {
  28550. overflow: hidden;
  28551. perspective: 1000px;
  28552. }
  28553. .funky-show-hide.ng-hide-add {
  28554. transform: rotateZ(0);
  28555. transform-origin: right;
  28556. transition: all 0.5s ease-in-out;
  28557. }
  28558. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  28559. transform: rotateZ(-135deg);
  28560. }
  28561. .funky-show-hide.ng-hide-remove {
  28562. transform: rotateY(90deg);
  28563. transform-origin: left;
  28564. transition: all 0.5s ease;
  28565. }
  28566. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  28567. transform: rotateY(0);
  28568. }
  28569. .check-element {
  28570. border: 1px solid black;
  28571. opacity: 1;
  28572. padding: 10px;
  28573. }
  28574. </file>
  28575. <file name="protractor.js" type="protractor">
  28576. it('should check ngHide', function() {
  28577. var checkbox = element(by.model('checked'));
  28578. var checkElem = element(by.css('.check-element'));
  28579. expect(checkElem.isDisplayed()).toBe(true);
  28580. checkbox.click();
  28581. expect(checkElem.isDisplayed()).toBe(false);
  28582. });
  28583. </file>
  28584. </example>
  28585. */
  28586. var ngHideDirective = ['$animate', function($animate) {
  28587. return {
  28588. restrict: 'A',
  28589. multiElement: true,
  28590. link: function(scope, element, attr) {
  28591. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  28592. // The comment inside of the ngShowDirective explains why we add and
  28593. // remove a temporary class for the show/hide animation
  28594. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  28595. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  28596. });
  28597. });
  28598. }
  28599. };
  28600. }];
  28601. /**
  28602. * @ngdoc directive
  28603. * @name ngStyle
  28604. * @restrict AC
  28605. *
  28606. * @description
  28607. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  28608. *
  28609. * @knownIssue
  28610. * You should not use {@link guide/interpolation interpolation} in the value of the `style`
  28611. * attribute, when using the `ngStyle` directive on the same element.
  28612. * See {@link guide/interpolation#known-issues here} for more info.
  28613. *
  28614. * @element ANY
  28615. * @param {expression} ngStyle
  28616. *
  28617. * {@link guide/expression Expression} which evals to an
  28618. * object whose keys are CSS style names and values are corresponding values for those CSS
  28619. * keys.
  28620. *
  28621. * Since some CSS style names are not valid keys for an object, they must be quoted.
  28622. * See the 'background-color' style in the example below.
  28623. *
  28624. * @example
  28625. <example name="ng-style">
  28626. <file name="index.html">
  28627. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  28628. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  28629. <input type="button" value="clear" ng-click="myStyle={}">
  28630. <br/>
  28631. <span ng-style="myStyle">Sample Text</span>
  28632. <pre>myStyle={{myStyle}}</pre>
  28633. </file>
  28634. <file name="style.css">
  28635. span {
  28636. color: black;
  28637. }
  28638. </file>
  28639. <file name="protractor.js" type="protractor">
  28640. var colorSpan = element(by.css('span'));
  28641. it('should check ng-style', function() {
  28642. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  28643. element(by.css('input[value=\'set color\']')).click();
  28644. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  28645. element(by.css('input[value=clear]')).click();
  28646. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  28647. });
  28648. </file>
  28649. </example>
  28650. */
  28651. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  28652. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  28653. if (oldStyles && (newStyles !== oldStyles)) {
  28654. forEach(oldStyles, function(val, style) { element.css(style, '');});
  28655. }
  28656. if (newStyles) element.css(newStyles);
  28657. }, true);
  28658. });
  28659. /**
  28660. * @ngdoc directive
  28661. * @name ngSwitch
  28662. * @restrict EA
  28663. *
  28664. * @description
  28665. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  28666. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  28667. * as specified in the template.
  28668. *
  28669. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  28670. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  28671. * matches the value obtained from the evaluated expression. In other words, you define a container element
  28672. * (where you place the directive), place an expression on the **`on="..."` attribute**
  28673. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  28674. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  28675. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  28676. * attribute is displayed.
  28677. *
  28678. * <div class="alert alert-info">
  28679. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  28680. * as literal string values to match against.
  28681. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  28682. * value of the expression `$scope.someVal`.
  28683. * </div>
  28684. * @animations
  28685. * | Animation | Occurs |
  28686. * |----------------------------------|-------------------------------------|
  28687. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  28688. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  28689. *
  28690. * @usage
  28691. *
  28692. * ```
  28693. * <ANY ng-switch="expression">
  28694. * <ANY ng-switch-when="matchValue1">...</ANY>
  28695. * <ANY ng-switch-when="matchValue2">...</ANY>
  28696. * <ANY ng-switch-default>...</ANY>
  28697. * </ANY>
  28698. * ```
  28699. *
  28700. *
  28701. * @scope
  28702. * @priority 1200
  28703. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  28704. * On child elements add:
  28705. *
  28706. * * `ngSwitchWhen`: the case statement to match against. If match then this
  28707. * case will be displayed. If the same match appears multiple times, all the
  28708. * elements will be displayed. It is possible to associate multiple values to
  28709. * the same `ngSwitchWhen` by defining the optional attribute
  28710. * `ngSwitchWhenSeparator`. The separator will be used to split the value of
  28711. * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
  28712. * if any of the `ngSwitch` evaluates to any of these tokens.
  28713. * * `ngSwitchDefault`: the default case when no other case match. If there
  28714. * are multiple default cases, all of them will be displayed when no other
  28715. * case match.
  28716. *
  28717. *
  28718. * @example
  28719. <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
  28720. <file name="index.html">
  28721. <div ng-controller="ExampleController">
  28722. <select ng-model="selection" ng-options="item for item in items">
  28723. </select>
  28724. <code>selection={{selection}}</code>
  28725. <hr/>
  28726. <div class="animate-switch-container"
  28727. ng-switch on="selection">
  28728. <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
  28729. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  28730. <div class="animate-switch" ng-switch-default>default</div>
  28731. </div>
  28732. </div>
  28733. </file>
  28734. <file name="script.js">
  28735. angular.module('switchExample', ['ngAnimate'])
  28736. .controller('ExampleController', ['$scope', function($scope) {
  28737. $scope.items = ['settings', 'home', 'options', 'other'];
  28738. $scope.selection = $scope.items[0];
  28739. }]);
  28740. </file>
  28741. <file name="animations.css">
  28742. .animate-switch-container {
  28743. position:relative;
  28744. background:white;
  28745. border:1px solid black;
  28746. height:40px;
  28747. overflow:hidden;
  28748. }
  28749. .animate-switch {
  28750. padding:10px;
  28751. }
  28752. .animate-switch.ng-animate {
  28753. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  28754. position:absolute;
  28755. top:0;
  28756. left:0;
  28757. right:0;
  28758. bottom:0;
  28759. }
  28760. .animate-switch.ng-leave.ng-leave-active,
  28761. .animate-switch.ng-enter {
  28762. top:-50px;
  28763. }
  28764. .animate-switch.ng-leave,
  28765. .animate-switch.ng-enter.ng-enter-active {
  28766. top:0;
  28767. }
  28768. </file>
  28769. <file name="protractor.js" type="protractor">
  28770. var switchElem = element(by.css('[ng-switch]'));
  28771. var select = element(by.model('selection'));
  28772. it('should start in settings', function() {
  28773. expect(switchElem.getText()).toMatch(/Settings Div/);
  28774. });
  28775. it('should change to home', function() {
  28776. select.all(by.css('option')).get(1).click();
  28777. expect(switchElem.getText()).toMatch(/Home Span/);
  28778. });
  28779. it('should change to settings via "options"', function() {
  28780. select.all(by.css('option')).get(2).click();
  28781. expect(switchElem.getText()).toMatch(/Settings Div/);
  28782. });
  28783. it('should select default', function() {
  28784. select.all(by.css('option')).get(3).click();
  28785. expect(switchElem.getText()).toMatch(/default/);
  28786. });
  28787. </file>
  28788. </example>
  28789. */
  28790. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  28791. return {
  28792. require: 'ngSwitch',
  28793. // asks for $scope to fool the BC controller module
  28794. controller: ['$scope', function NgSwitchController() {
  28795. this.cases = {};
  28796. }],
  28797. link: function(scope, element, attr, ngSwitchController) {
  28798. var watchExpr = attr.ngSwitch || attr.on,
  28799. selectedTranscludes = [],
  28800. selectedElements = [],
  28801. previousLeaveAnimations = [],
  28802. selectedScopes = [];
  28803. var spliceFactory = function(array, index) {
  28804. return function(response) {
  28805. if (response !== false) array.splice(index, 1);
  28806. };
  28807. };
  28808. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  28809. var i, ii;
  28810. // Start with the last, in case the array is modified during the loop
  28811. while (previousLeaveAnimations.length) {
  28812. $animate.cancel(previousLeaveAnimations.pop());
  28813. }
  28814. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  28815. var selected = getBlockNodes(selectedElements[i].clone);
  28816. selectedScopes[i].$destroy();
  28817. var runner = previousLeaveAnimations[i] = $animate.leave(selected);
  28818. runner.done(spliceFactory(previousLeaveAnimations, i));
  28819. }
  28820. selectedElements.length = 0;
  28821. selectedScopes.length = 0;
  28822. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  28823. forEach(selectedTranscludes, function(selectedTransclude) {
  28824. selectedTransclude.transclude(function(caseElement, selectedScope) {
  28825. selectedScopes.push(selectedScope);
  28826. var anchor = selectedTransclude.element;
  28827. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  28828. var block = { clone: caseElement };
  28829. selectedElements.push(block);
  28830. $animate.enter(caseElement, anchor.parent(), anchor);
  28831. });
  28832. });
  28833. }
  28834. });
  28835. }
  28836. };
  28837. }];
  28838. var ngSwitchWhenDirective = ngDirective({
  28839. transclude: 'element',
  28840. priority: 1200,
  28841. require: '^ngSwitch',
  28842. multiElement: true,
  28843. link: function(scope, element, attrs, ctrl, $transclude) {
  28844. var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
  28845. // Filter duplicate cases
  28846. function(element, index, array) { return array[index - 1] !== element; }
  28847. );
  28848. forEach(cases, function(whenCase) {
  28849. ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
  28850. ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
  28851. });
  28852. }
  28853. });
  28854. var ngSwitchDefaultDirective = ngDirective({
  28855. transclude: 'element',
  28856. priority: 1200,
  28857. require: '^ngSwitch',
  28858. multiElement: true,
  28859. link: function(scope, element, attr, ctrl, $transclude) {
  28860. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  28861. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  28862. }
  28863. });
  28864. /**
  28865. * @ngdoc directive
  28866. * @name ngTransclude
  28867. * @restrict EAC
  28868. *
  28869. * @description
  28870. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  28871. *
  28872. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  28873. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  28874. *
  28875. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  28876. * content of this element will be removed before the transcluded content is inserted.
  28877. * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback
  28878. * content in the case that no transcluded content is provided.
  28879. *
  28880. * @element ANY
  28881. *
  28882. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  28883. * or its value is the same as the name of the attribute then the default slot is used.
  28884. *
  28885. * @example
  28886. * ### Basic transclusion
  28887. * This example demonstrates basic transclusion of content into a component directive.
  28888. * <example name="simpleTranscludeExample" module="transcludeExample">
  28889. * <file name="index.html">
  28890. * <script>
  28891. * angular.module('transcludeExample', [])
  28892. * .directive('pane', function(){
  28893. * return {
  28894. * restrict: 'E',
  28895. * transclude: true,
  28896. * scope: { title:'@' },
  28897. * template: '<div style="border: 1px solid black;">' +
  28898. * '<div style="background-color: gray">{{title}}</div>' +
  28899. * '<ng-transclude></ng-transclude>' +
  28900. * '</div>'
  28901. * };
  28902. * })
  28903. * .controller('ExampleController', ['$scope', function($scope) {
  28904. * $scope.title = 'Lorem Ipsum';
  28905. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  28906. * }]);
  28907. * </script>
  28908. * <div ng-controller="ExampleController">
  28909. * <input ng-model="title" aria-label="title"> <br/>
  28910. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  28911. * <pane title="{{title}}"><span>{{text}}</span></pane>
  28912. * </div>
  28913. * </file>
  28914. * <file name="protractor.js" type="protractor">
  28915. * it('should have transcluded', function() {
  28916. * var titleElement = element(by.model('title'));
  28917. * titleElement.clear();
  28918. * titleElement.sendKeys('TITLE');
  28919. * var textElement = element(by.model('text'));
  28920. * textElement.clear();
  28921. * textElement.sendKeys('TEXT');
  28922. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  28923. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  28924. * });
  28925. * </file>
  28926. * </example>
  28927. *
  28928. * @example
  28929. * ### Transclude fallback content
  28930. * This example shows how to use `NgTransclude` with fallback content, that
  28931. * is displayed if no transcluded content is provided.
  28932. *
  28933. * <example module="transcludeFallbackContentExample" name="ng-transclude">
  28934. * <file name="index.html">
  28935. * <script>
  28936. * angular.module('transcludeFallbackContentExample', [])
  28937. * .directive('myButton', function(){
  28938. * return {
  28939. * restrict: 'E',
  28940. * transclude: true,
  28941. * scope: true,
  28942. * template: '<button style="cursor: pointer;">' +
  28943. * '<ng-transclude>' +
  28944. * '<b style="color: red;">Button1</b>' +
  28945. * '</ng-transclude>' +
  28946. * '</button>'
  28947. * };
  28948. * });
  28949. * </script>
  28950. * <!-- fallback button content -->
  28951. * <my-button id="fallback"></my-button>
  28952. * <!-- modified button content -->
  28953. * <my-button id="modified">
  28954. * <i style="color: green;">Button2</i>
  28955. * </my-button>
  28956. * </file>
  28957. * <file name="protractor.js" type="protractor">
  28958. * it('should have different transclude element content', function() {
  28959. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  28960. * expect(element(by.id('modified')).getText()).toBe('Button2');
  28961. * });
  28962. * </file>
  28963. * </example>
  28964. *
  28965. * @example
  28966. * ### Multi-slot transclusion
  28967. * This example demonstrates using multi-slot transclusion in a component directive.
  28968. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  28969. * <file name="index.html">
  28970. * <style>
  28971. * .title, .footer {
  28972. * background-color: gray
  28973. * }
  28974. * </style>
  28975. * <div ng-controller="ExampleController">
  28976. * <input ng-model="title" aria-label="title"> <br/>
  28977. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  28978. * <pane>
  28979. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  28980. * <pane-body><p>{{text}}</p></pane-body>
  28981. * </pane>
  28982. * </div>
  28983. * </file>
  28984. * <file name="app.js">
  28985. * angular.module('multiSlotTranscludeExample', [])
  28986. * .directive('pane', function() {
  28987. * return {
  28988. * restrict: 'E',
  28989. * transclude: {
  28990. * 'title': '?paneTitle',
  28991. * 'body': 'paneBody',
  28992. * 'footer': '?paneFooter'
  28993. * },
  28994. * template: '<div style="border: 1px solid black;">' +
  28995. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  28996. * '<div ng-transclude="body"></div>' +
  28997. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  28998. * '</div>'
  28999. * };
  29000. * })
  29001. * .controller('ExampleController', ['$scope', function($scope) {
  29002. * $scope.title = 'Lorem Ipsum';
  29003. * $scope.link = 'https://google.com';
  29004. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  29005. * }]);
  29006. * </file>
  29007. * <file name="protractor.js" type="protractor">
  29008. * it('should have transcluded the title and the body', function() {
  29009. * var titleElement = element(by.model('title'));
  29010. * titleElement.clear();
  29011. * titleElement.sendKeys('TITLE');
  29012. * var textElement = element(by.model('text'));
  29013. * textElement.clear();
  29014. * textElement.sendKeys('TEXT');
  29015. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  29016. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  29017. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  29018. * });
  29019. * </file>
  29020. * </example>
  29021. */
  29022. var ngTranscludeMinErr = minErr('ngTransclude');
  29023. var ngTranscludeDirective = ['$compile', function($compile) {
  29024. return {
  29025. restrict: 'EAC',
  29026. terminal: true,
  29027. compile: function ngTranscludeCompile(tElement) {
  29028. // Remove and cache any original content to act as a fallback
  29029. var fallbackLinkFn = $compile(tElement.contents());
  29030. tElement.empty();
  29031. return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
  29032. if (!$transclude) {
  29033. throw ngTranscludeMinErr('orphan',
  29034. 'Illegal use of ngTransclude directive in the template! ' +
  29035. 'No parent directive that requires a transclusion found. ' +
  29036. 'Element: {0}',
  29037. startingTag($element));
  29038. }
  29039. // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
  29040. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  29041. $attrs.ngTransclude = '';
  29042. }
  29043. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  29044. // If the slot is required and no transclusion content is provided then this call will throw an error
  29045. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  29046. // If the slot is optional and no transclusion content is provided then use the fallback content
  29047. if (slotName && !$transclude.isSlotFilled(slotName)) {
  29048. useFallbackContent();
  29049. }
  29050. function ngTranscludeCloneAttachFn(clone, transcludedScope) {
  29051. if (clone.length && notWhitespace(clone)) {
  29052. $element.append(clone);
  29053. } else {
  29054. useFallbackContent();
  29055. // There is nothing linked against the transcluded scope since no content was available,
  29056. // so it should be safe to clean up the generated scope.
  29057. transcludedScope.$destroy();
  29058. }
  29059. }
  29060. function useFallbackContent() {
  29061. // Since this is the fallback content rather than the transcluded content,
  29062. // we link against the scope of this directive rather than the transcluded scope
  29063. fallbackLinkFn($scope, function(clone) {
  29064. $element.append(clone);
  29065. });
  29066. }
  29067. function notWhitespace(nodes) {
  29068. for (var i = 0, ii = nodes.length; i < ii; i++) {
  29069. var node = nodes[i];
  29070. if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) {
  29071. return true;
  29072. }
  29073. }
  29074. }
  29075. };
  29076. }
  29077. };
  29078. }];
  29079. /**
  29080. * @ngdoc directive
  29081. * @name script
  29082. * @restrict E
  29083. *
  29084. * @description
  29085. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  29086. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  29087. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  29088. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  29089. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  29090. *
  29091. * @param {string} type Must be set to `'text/ng-template'`.
  29092. * @param {string} id Cache name of the template.
  29093. *
  29094. * @example
  29095. <example name="script-tag">
  29096. <file name="index.html">
  29097. <script type="text/ng-template" id="/tpl.html">
  29098. Content of the template.
  29099. </script>
  29100. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  29101. <div id="tpl-content" ng-include src="currentTpl"></div>
  29102. </file>
  29103. <file name="protractor.js" type="protractor">
  29104. it('should load template defined inside script tag', function() {
  29105. element(by.css('#tpl-link')).click();
  29106. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  29107. });
  29108. </file>
  29109. </example>
  29110. */
  29111. var scriptDirective = ['$templateCache', function($templateCache) {
  29112. return {
  29113. restrict: 'E',
  29114. terminal: true,
  29115. compile: function(element, attr) {
  29116. if (attr.type === 'text/ng-template') {
  29117. var templateUrl = attr.id,
  29118. text = element[0].text;
  29119. $templateCache.put(templateUrl, text);
  29120. }
  29121. }
  29122. };
  29123. }];
  29124. /* exported selectDirective, optionDirective */
  29125. var noopNgModelController = { $setViewValue: noop, $render: noop };
  29126. /**
  29127. * @ngdoc type
  29128. * @name select.SelectController
  29129. * @description
  29130. * The controller for the `<select>` directive. This provides support for reading
  29131. * and writing the selected value(s) of the control and also coordinates dynamically
  29132. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  29133. */
  29134. var SelectController =
  29135. ['$element', '$scope', /** @this */ function($element, $scope) {
  29136. var self = this,
  29137. optionsMap = new NgMap();
  29138. self.selectValueMap = {}; // Keys are the hashed values, values the original values
  29139. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  29140. self.ngModelCtrl = noopNgModelController;
  29141. self.multiple = false;
  29142. // The "unknown" option is one that is prepended to the list if the viewValue
  29143. // does not match any of the options. When it is rendered the value of the unknown
  29144. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  29145. //
  29146. // We can't just jqLite('<option>') since jqLite is not smart enough
  29147. // to create it in <select> and IE barfs otherwise.
  29148. self.unknownOption = jqLite(window.document.createElement('option'));
  29149. // The empty option is an option with the value '' that te application developer can
  29150. // provide inside the select. When the model changes to a value that doesn't match an option,
  29151. // it is selected - so if an empty option is provided, no unknown option is generated.
  29152. // However, the empty option is not removed when the model matches an option. It is always selectable
  29153. // and indicates that a "null" selection has been made.
  29154. self.hasEmptyOption = false;
  29155. self.emptyOption = undefined;
  29156. self.renderUnknownOption = function(val) {
  29157. var unknownVal = self.generateUnknownOptionValue(val);
  29158. self.unknownOption.val(unknownVal);
  29159. $element.prepend(self.unknownOption);
  29160. setOptionAsSelected(self.unknownOption);
  29161. $element.val(unknownVal);
  29162. };
  29163. self.updateUnknownOption = function(val) {
  29164. var unknownVal = self.generateUnknownOptionValue(val);
  29165. self.unknownOption.val(unknownVal);
  29166. setOptionAsSelected(self.unknownOption);
  29167. $element.val(unknownVal);
  29168. };
  29169. self.generateUnknownOptionValue = function(val) {
  29170. return '? ' + hashKey(val) + ' ?';
  29171. };
  29172. self.removeUnknownOption = function() {
  29173. if (self.unknownOption.parent()) self.unknownOption.remove();
  29174. };
  29175. self.selectEmptyOption = function() {
  29176. if (self.emptyOption) {
  29177. $element.val('');
  29178. setOptionAsSelected(self.emptyOption);
  29179. }
  29180. };
  29181. self.unselectEmptyOption = function() {
  29182. if (self.hasEmptyOption) {
  29183. self.emptyOption.removeAttr('selected');
  29184. }
  29185. };
  29186. $scope.$on('$destroy', function() {
  29187. // disable unknown option so that we don't do work when the whole select is being destroyed
  29188. self.renderUnknownOption = noop;
  29189. });
  29190. // Read the value of the select control, the implementation of this changes depending
  29191. // upon whether the select can have multiple values and whether ngOptions is at work.
  29192. self.readValue = function readSingleValue() {
  29193. var val = $element.val();
  29194. // ngValue added option values are stored in the selectValueMap, normal interpolations are not
  29195. var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;
  29196. if (self.hasOption(realVal)) {
  29197. return realVal;
  29198. }
  29199. return null;
  29200. };
  29201. // Write the value to the select control, the implementation of this changes depending
  29202. // upon whether the select can have multiple values and whether ngOptions is at work.
  29203. self.writeValue = function writeSingleValue(value) {
  29204. // Make sure to remove the selected attribute from the previously selected option
  29205. // Otherwise, screen readers might get confused
  29206. var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];
  29207. if (currentlySelectedOption) currentlySelectedOption.removeAttribute('selected');
  29208. if (self.hasOption(value)) {
  29209. self.removeUnknownOption();
  29210. var hashedVal = hashKey(value);
  29211. $element.val(hashedVal in self.selectValueMap ? hashedVal : value);
  29212. // Set selected attribute and property on selected option for screen readers
  29213. var selectedOption = $element[0].options[$element[0].selectedIndex];
  29214. setOptionAsSelected(jqLite(selectedOption));
  29215. } else {
  29216. if (value == null && self.emptyOption) {
  29217. self.removeUnknownOption();
  29218. self.selectEmptyOption();
  29219. } else if (self.unknownOption.parent().length) {
  29220. self.updateUnknownOption(value);
  29221. } else {
  29222. self.renderUnknownOption(value);
  29223. }
  29224. }
  29225. };
  29226. // Tell the select control that an option, with the given value, has been added
  29227. self.addOption = function(value, element) {
  29228. // Skip comment nodes, as they only pollute the `optionsMap`
  29229. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  29230. assertNotHasOwnProperty(value, '"option value"');
  29231. if (value === '') {
  29232. self.hasEmptyOption = true;
  29233. self.emptyOption = element;
  29234. }
  29235. var count = optionsMap.get(value) || 0;
  29236. optionsMap.set(value, count + 1);
  29237. // Only render at the end of a digest. This improves render performance when many options
  29238. // are added during a digest and ensures all relevant options are correctly marked as selected
  29239. scheduleRender();
  29240. };
  29241. // Tell the select control that an option, with the given value, has been removed
  29242. self.removeOption = function(value) {
  29243. var count = optionsMap.get(value);
  29244. if (count) {
  29245. if (count === 1) {
  29246. optionsMap.delete(value);
  29247. if (value === '') {
  29248. self.hasEmptyOption = false;
  29249. self.emptyOption = undefined;
  29250. }
  29251. } else {
  29252. optionsMap.set(value, count - 1);
  29253. }
  29254. }
  29255. };
  29256. // Check whether the select control has an option matching the given value
  29257. self.hasOption = function(value) {
  29258. return !!optionsMap.get(value);
  29259. };
  29260. var renderScheduled = false;
  29261. function scheduleRender() {
  29262. if (renderScheduled) return;
  29263. renderScheduled = true;
  29264. $scope.$$postDigest(function() {
  29265. renderScheduled = false;
  29266. self.ngModelCtrl.$render();
  29267. });
  29268. }
  29269. var updateScheduled = false;
  29270. function scheduleViewValueUpdate(renderAfter) {
  29271. if (updateScheduled) return;
  29272. updateScheduled = true;
  29273. $scope.$$postDigest(function() {
  29274. if ($scope.$$destroyed) return;
  29275. updateScheduled = false;
  29276. self.ngModelCtrl.$setViewValue(self.readValue());
  29277. if (renderAfter) self.ngModelCtrl.$render();
  29278. });
  29279. }
  29280. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  29281. if (optionAttrs.$attr.ngValue) {
  29282. // The value attribute is set by ngValue
  29283. var oldVal, hashedVal = NaN;
  29284. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29285. var removal;
  29286. var previouslySelected = optionElement.prop('selected');
  29287. if (isDefined(hashedVal)) {
  29288. self.removeOption(oldVal);
  29289. delete self.selectValueMap[hashedVal];
  29290. removal = true;
  29291. }
  29292. hashedVal = hashKey(newVal);
  29293. oldVal = newVal;
  29294. self.selectValueMap[hashedVal] = newVal;
  29295. self.addOption(newVal, optionElement);
  29296. // Set the attribute directly instead of using optionAttrs.$set - this stops the observer
  29297. // from firing a second time. Other $observers on value will also get the result of the
  29298. // ngValue expression, not the hashed value
  29299. optionElement.attr('value', hashedVal);
  29300. if (removal && previouslySelected) {
  29301. scheduleViewValueUpdate();
  29302. }
  29303. });
  29304. } else if (interpolateValueFn) {
  29305. // The value attribute is interpolated
  29306. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29307. // This method is overwritten in ngOptions and has side-effects!
  29308. self.readValue();
  29309. var removal;
  29310. var previouslySelected = optionElement.prop('selected');
  29311. if (isDefined(oldVal)) {
  29312. self.removeOption(oldVal);
  29313. removal = true;
  29314. }
  29315. oldVal = newVal;
  29316. self.addOption(newVal, optionElement);
  29317. if (removal && previouslySelected) {
  29318. scheduleViewValueUpdate();
  29319. }
  29320. });
  29321. } else if (interpolateTextFn) {
  29322. // The text content is interpolated
  29323. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  29324. optionAttrs.$set('value', newVal);
  29325. var previouslySelected = optionElement.prop('selected');
  29326. if (oldVal !== newVal) {
  29327. self.removeOption(oldVal);
  29328. }
  29329. self.addOption(newVal, optionElement);
  29330. if (oldVal && previouslySelected) {
  29331. scheduleViewValueUpdate();
  29332. }
  29333. });
  29334. } else {
  29335. // The value attribute is static
  29336. self.addOption(optionAttrs.value, optionElement);
  29337. }
  29338. optionAttrs.$observe('disabled', function(newVal) {
  29339. // Since model updates will also select disabled options (like ngOptions),
  29340. // we only have to handle options becoming disabled, not enabled
  29341. if (newVal === 'true' || newVal && optionElement.prop('selected')) {
  29342. if (self.multiple) {
  29343. scheduleViewValueUpdate(true);
  29344. } else {
  29345. self.ngModelCtrl.$setViewValue(null);
  29346. self.ngModelCtrl.$render();
  29347. }
  29348. }
  29349. });
  29350. optionElement.on('$destroy', function() {
  29351. var currentValue = self.readValue();
  29352. var removeValue = optionAttrs.value;
  29353. self.removeOption(removeValue);
  29354. scheduleRender();
  29355. if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
  29356. currentValue === removeValue
  29357. ) {
  29358. // When multiple (selected) options are destroyed at the same time, we don't want
  29359. // to run a model update for each of them. Instead, run a single update in the $$postDigest
  29360. scheduleViewValueUpdate(true);
  29361. }
  29362. });
  29363. };
  29364. function setOptionAsSelected(optionEl) {
  29365. optionEl.prop('selected', true); // needed for IE
  29366. optionEl.attr('selected', true);
  29367. }
  29368. }];
  29369. /**
  29370. * @ngdoc directive
  29371. * @name select
  29372. * @restrict E
  29373. *
  29374. * @description
  29375. * HTML `select` element with angular data-binding.
  29376. *
  29377. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  29378. * between the scope and the `<select>` control (including setting default values).
  29379. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  29380. * {@link ngOptions `ngOptions`} directives.
  29381. *
  29382. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  29383. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  29384. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  29385. * Value and textContent can be interpolated.
  29386. *
  29387. * ## Matching model and option values
  29388. *
  29389. * In general, the match between the model and an option is evaluated by strictly comparing the model
  29390. * value against the value of the available options.
  29391. *
  29392. * If you are setting the option value with the option's `value` attribute, or textContent, the
  29393. * value will always be a `string` which means that the model value must also be a string.
  29394. * Otherwise the `select` directive cannot match them correctly.
  29395. *
  29396. * To bind the model to a non-string value, you can use one of the following strategies:
  29397. * - the {@link ng.ngOptions `ngOptions`} directive
  29398. * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value})
  29399. * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be
  29400. * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example})
  29401. * - model $parsers / $formatters to convert the string value
  29402. * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example})
  29403. *
  29404. * If the viewValue of `ngModel` does not match any of the options, then the control
  29405. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  29406. *
  29407. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  29408. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  29409. * option. See example below for demonstration.
  29410. *
  29411. * ## Choosing between `ngRepeat` and `ngOptions`
  29412. *
  29413. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  29414. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits:
  29415. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  29416. * comprehension expression
  29417. * - reduced memory consumption by not creating a new scope for each repeated instance
  29418. * - increased render speed by creating the options in a documentFragment instead of individually
  29419. *
  29420. * Specifically, select with repeated options slows down significantly starting at 2000 options in
  29421. * Chrome and Internet Explorer / Edge.
  29422. *
  29423. *
  29424. * @param {string} ngModel Assignable angular expression to data-bind to.
  29425. * @param {string=} name Property name of the form under which the control is published.
  29426. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  29427. * bound to the model as an array.
  29428. * @param {string=} required Sets `required` validation error key if the value is not entered.
  29429. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  29430. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  29431. * when you want to data-bind to the required attribute.
  29432. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  29433. * interaction with the select element.
  29434. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  29435. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  29436. *
  29437. * @example
  29438. * ### Simple `select` elements with static options
  29439. *
  29440. * <example name="static-select" module="staticSelect">
  29441. * <file name="index.html">
  29442. * <div ng-controller="ExampleController">
  29443. * <form name="myForm">
  29444. * <label for="singleSelect"> Single select: </label><br>
  29445. * <select name="singleSelect" ng-model="data.singleSelect">
  29446. * <option value="option-1">Option 1</option>
  29447. * <option value="option-2">Option 2</option>
  29448. * </select><br>
  29449. *
  29450. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  29451. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  29452. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  29453. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  29454. * <option value="option-2">Option 2</option>
  29455. * </select><br>
  29456. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  29457. * <tt>singleSelect = {{data.singleSelect}}</tt>
  29458. *
  29459. * <hr>
  29460. * <label for="multipleSelect"> Multiple select: </label><br>
  29461. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  29462. * <option value="option-1">Option 1</option>
  29463. * <option value="option-2">Option 2</option>
  29464. * <option value="option-3">Option 3</option>
  29465. * </select><br>
  29466. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  29467. * </form>
  29468. * </div>
  29469. * </file>
  29470. * <file name="app.js">
  29471. * angular.module('staticSelect', [])
  29472. * .controller('ExampleController', ['$scope', function($scope) {
  29473. * $scope.data = {
  29474. * singleSelect: null,
  29475. * multipleSelect: [],
  29476. * option1: 'option-1'
  29477. * };
  29478. *
  29479. * $scope.forceUnknownOption = function() {
  29480. * $scope.data.singleSelect = 'nonsense';
  29481. * };
  29482. * }]);
  29483. * </file>
  29484. *</example>
  29485. *
  29486. * ### Using `ngRepeat` to generate `select` options
  29487. * <example name="select-ngrepeat" module="ngrepeatSelect">
  29488. * <file name="index.html">
  29489. * <div ng-controller="ExampleController">
  29490. * <form name="myForm">
  29491. * <label for="repeatSelect"> Repeat select: </label>
  29492. * <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  29493. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  29494. * </select>
  29495. * </form>
  29496. * <hr>
  29497. * <tt>model = {{data.model}}</tt><br/>
  29498. * </div>
  29499. * </file>
  29500. * <file name="app.js">
  29501. * angular.module('ngrepeatSelect', [])
  29502. * .controller('ExampleController', ['$scope', function($scope) {
  29503. * $scope.data = {
  29504. * model: null,
  29505. * availableOptions: [
  29506. * {id: '1', name: 'Option A'},
  29507. * {id: '2', name: 'Option B'},
  29508. * {id: '3', name: 'Option C'}
  29509. * ]
  29510. * };
  29511. * }]);
  29512. * </file>
  29513. *</example>
  29514. *
  29515. * ### Using `ngValue` to bind the model to an array of objects
  29516. * <example name="select-ngvalue" module="ngvalueSelect">
  29517. * <file name="index.html">
  29518. * <div ng-controller="ExampleController">
  29519. * <form name="myForm">
  29520. * <label for="ngvalueselect"> ngvalue select: </label>
  29521. * <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
  29522. * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
  29523. * </select>
  29524. * </form>
  29525. * <hr>
  29526. * <pre>model = {{data.model | json}}</pre><br/>
  29527. * </div>
  29528. * </file>
  29529. * <file name="app.js">
  29530. * angular.module('ngvalueSelect', [])
  29531. * .controller('ExampleController', ['$scope', function($scope) {
  29532. * $scope.data = {
  29533. * model: null,
  29534. * availableOptions: [
  29535. {value: 'myString', name: 'string'},
  29536. {value: 1, name: 'integer'},
  29537. {value: true, name: 'boolean'},
  29538. {value: null, name: 'null'},
  29539. {value: {prop: 'value'}, name: 'object'},
  29540. {value: ['a'], name: 'array'}
  29541. * ]
  29542. * };
  29543. * }]);
  29544. * </file>
  29545. *</example>
  29546. *
  29547. * ### Using `select` with `ngOptions` and setting a default value
  29548. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  29549. *
  29550. * <example name="select-with-default-values" module="defaultValueSelect">
  29551. * <file name="index.html">
  29552. * <div ng-controller="ExampleController">
  29553. * <form name="myForm">
  29554. * <label for="mySelect">Make a choice:</label>
  29555. * <select name="mySelect" id="mySelect"
  29556. * ng-options="option.name for option in data.availableOptions track by option.id"
  29557. * ng-model="data.selectedOption"></select>
  29558. * </form>
  29559. * <hr>
  29560. * <tt>option = {{data.selectedOption}}</tt><br/>
  29561. * </div>
  29562. * </file>
  29563. * <file name="app.js">
  29564. * angular.module('defaultValueSelect', [])
  29565. * .controller('ExampleController', ['$scope', function($scope) {
  29566. * $scope.data = {
  29567. * availableOptions: [
  29568. * {id: '1', name: 'Option A'},
  29569. * {id: '2', name: 'Option B'},
  29570. * {id: '3', name: 'Option C'}
  29571. * ],
  29572. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  29573. * };
  29574. * }]);
  29575. * </file>
  29576. *</example>
  29577. *
  29578. *
  29579. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  29580. *
  29581. * <example name="select-with-non-string-options" module="nonStringSelect">
  29582. * <file name="index.html">
  29583. * <select ng-model="model.id" convert-to-number>
  29584. * <option value="0">Zero</option>
  29585. * <option value="1">One</option>
  29586. * <option value="2">Two</option>
  29587. * </select>
  29588. * {{ model }}
  29589. * </file>
  29590. * <file name="app.js">
  29591. * angular.module('nonStringSelect', [])
  29592. * .run(function($rootScope) {
  29593. * $rootScope.model = { id: 2 };
  29594. * })
  29595. * .directive('convertToNumber', function() {
  29596. * return {
  29597. * require: 'ngModel',
  29598. * link: function(scope, element, attrs, ngModel) {
  29599. * ngModel.$parsers.push(function(val) {
  29600. * return parseInt(val, 10);
  29601. * });
  29602. * ngModel.$formatters.push(function(val) {
  29603. * return '' + val;
  29604. * });
  29605. * }
  29606. * };
  29607. * });
  29608. * </file>
  29609. * <file name="protractor.js" type="protractor">
  29610. * it('should initialize to model', function() {
  29611. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  29612. * });
  29613. * </file>
  29614. * </example>
  29615. *
  29616. */
  29617. var selectDirective = function() {
  29618. return {
  29619. restrict: 'E',
  29620. require: ['select', '?ngModel'],
  29621. controller: SelectController,
  29622. priority: 1,
  29623. link: {
  29624. pre: selectPreLink,
  29625. post: selectPostLink
  29626. }
  29627. };
  29628. function selectPreLink(scope, element, attr, ctrls) {
  29629. var selectCtrl = ctrls[0];
  29630. var ngModelCtrl = ctrls[1];
  29631. // if ngModel is not defined, we don't need to do anything but set the registerOption
  29632. // function to noop, so options don't get added internally
  29633. if (!ngModelCtrl) {
  29634. selectCtrl.registerOption = noop;
  29635. return;
  29636. }
  29637. selectCtrl.ngModelCtrl = ngModelCtrl;
  29638. // When the selected item(s) changes we delegate getting the value of the select control
  29639. // to the `readValue` method, which can be changed if the select can have multiple
  29640. // selected values or if the options are being generated by `ngOptions`
  29641. element.on('change', function() {
  29642. selectCtrl.removeUnknownOption();
  29643. scope.$apply(function() {
  29644. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  29645. });
  29646. });
  29647. // If the select allows multiple values then we need to modify how we read and write
  29648. // values from and to the control; also what it means for the value to be empty and
  29649. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  29650. // doesn't trigger rendering if only an item in the array changes.
  29651. if (attr.multiple) {
  29652. selectCtrl.multiple = true;
  29653. // Read value now needs to check each option to see if it is selected
  29654. selectCtrl.readValue = function readMultipleValue() {
  29655. var array = [];
  29656. forEach(element.find('option'), function(option) {
  29657. if (option.selected && !option.disabled) {
  29658. var val = option.value;
  29659. array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
  29660. }
  29661. });
  29662. return array;
  29663. };
  29664. // Write value now needs to set the selected property of each matching option
  29665. selectCtrl.writeValue = function writeMultipleValue(value) {
  29666. forEach(element.find('option'), function(option) {
  29667. option.selected = !!value && (includes(value, option.value) ||
  29668. includes(value, selectCtrl.selectValueMap[option.value]));
  29669. });
  29670. };
  29671. // we have to do it on each watch since ngModel watches reference, but
  29672. // we need to work of an array, so we need to see if anything was inserted/removed
  29673. var lastView, lastViewRef = NaN;
  29674. scope.$watch(function selectMultipleWatch() {
  29675. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  29676. lastView = shallowCopy(ngModelCtrl.$viewValue);
  29677. ngModelCtrl.$render();
  29678. }
  29679. lastViewRef = ngModelCtrl.$viewValue;
  29680. });
  29681. // If we are a multiple select then value is now a collection
  29682. // so the meaning of $isEmpty changes
  29683. ngModelCtrl.$isEmpty = function(value) {
  29684. return !value || value.length === 0;
  29685. };
  29686. }
  29687. }
  29688. function selectPostLink(scope, element, attrs, ctrls) {
  29689. // if ngModel is not defined, we don't need to do anything
  29690. var ngModelCtrl = ctrls[1];
  29691. if (!ngModelCtrl) return;
  29692. var selectCtrl = ctrls[0];
  29693. // We delegate rendering to the `writeValue` method, which can be changed
  29694. // if the select can have multiple selected values or if the options are being
  29695. // generated by `ngOptions`.
  29696. // This must be done in the postLink fn to prevent $render to be called before
  29697. // all nodes have been linked correctly.
  29698. ngModelCtrl.$render = function() {
  29699. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  29700. };
  29701. }
  29702. };
  29703. // The option directive is purely designed to communicate the existence (or lack of)
  29704. // of dynamically created (and destroyed) option elements to their containing select
  29705. // directive via its controller.
  29706. var optionDirective = ['$interpolate', function($interpolate) {
  29707. return {
  29708. restrict: 'E',
  29709. priority: 100,
  29710. compile: function(element, attr) {
  29711. var interpolateValueFn, interpolateTextFn;
  29712. if (isDefined(attr.ngValue)) {
  29713. // Will be handled by registerOption
  29714. } else if (isDefined(attr.value)) {
  29715. // If the value attribute is defined, check if it contains an interpolation
  29716. interpolateValueFn = $interpolate(attr.value, true);
  29717. } else {
  29718. // If the value attribute is not defined then we fall back to the
  29719. // text content of the option element, which may be interpolated
  29720. interpolateTextFn = $interpolate(element.text(), true);
  29721. if (!interpolateTextFn) {
  29722. attr.$set('value', element.text());
  29723. }
  29724. }
  29725. return function(scope, element, attr) {
  29726. // This is an optimization over using ^^ since we don't want to have to search
  29727. // all the way to the root of the DOM for every single option element
  29728. var selectCtrlName = '$selectController',
  29729. parent = element.parent(),
  29730. selectCtrl = parent.data(selectCtrlName) ||
  29731. parent.parent().data(selectCtrlName); // in case we are in optgroup
  29732. if (selectCtrl) {
  29733. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  29734. }
  29735. };
  29736. }
  29737. };
  29738. }];
  29739. /**
  29740. * @ngdoc directive
  29741. * @name ngRequired
  29742. * @restrict A
  29743. *
  29744. * @description
  29745. *
  29746. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29747. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  29748. * applied to custom controls.
  29749. *
  29750. * The directive sets the `required` attribute on the element if the Angular expression inside
  29751. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  29752. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  29753. * for more info.
  29754. *
  29755. * The validator will set the `required` error key to true if the `required` attribute is set and
  29756. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  29757. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  29758. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  29759. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  29760. *
  29761. * @example
  29762. * <example name="ngRequiredDirective" module="ngRequiredExample">
  29763. * <file name="index.html">
  29764. * <script>
  29765. * angular.module('ngRequiredExample', [])
  29766. * .controller('ExampleController', ['$scope', function($scope) {
  29767. * $scope.required = true;
  29768. * }]);
  29769. * </script>
  29770. * <div ng-controller="ExampleController">
  29771. * <form name="form">
  29772. * <label for="required">Toggle required: </label>
  29773. * <input type="checkbox" ng-model="required" id="required" />
  29774. * <br>
  29775. * <label for="input">This input must be filled if `required` is true: </label>
  29776. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  29777. * <hr>
  29778. * required error set? = <code>{{form.input.$error.required}}</code><br>
  29779. * model = <code>{{model}}</code>
  29780. * </form>
  29781. * </div>
  29782. * </file>
  29783. * <file name="protractor.js" type="protractor">
  29784. var required = element(by.binding('form.input.$error.required'));
  29785. var model = element(by.binding('model'));
  29786. var input = element(by.id('input'));
  29787. it('should set the required error', function() {
  29788. expect(required.getText()).toContain('true');
  29789. input.sendKeys('123');
  29790. expect(required.getText()).not.toContain('true');
  29791. expect(model.getText()).toContain('123');
  29792. });
  29793. * </file>
  29794. * </example>
  29795. */
  29796. var requiredDirective = function() {
  29797. return {
  29798. restrict: 'A',
  29799. require: '?ngModel',
  29800. link: function(scope, elm, attr, ctrl) {
  29801. if (!ctrl) return;
  29802. attr.required = true; // force truthy in case we are on non input element
  29803. ctrl.$validators.required = function(modelValue, viewValue) {
  29804. return !attr.required || !ctrl.$isEmpty(viewValue);
  29805. };
  29806. attr.$observe('required', function() {
  29807. ctrl.$validate();
  29808. });
  29809. }
  29810. };
  29811. };
  29812. /**
  29813. * @ngdoc directive
  29814. * @name ngPattern
  29815. *
  29816. * @description
  29817. *
  29818. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29819. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  29820. *
  29821. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  29822. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  29823. * `ngPattern` attribute value:
  29824. * * If the expression evaluates to a RegExp object, then this is used directly.
  29825. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  29826. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  29827. *
  29828. * <div class="alert alert-info">
  29829. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  29830. * start at the index of the last search's match, thus not taking the whole input value into
  29831. * account.
  29832. * </div>
  29833. *
  29834. * <div class="alert alert-info">
  29835. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  29836. * differences:
  29837. * <ol>
  29838. * <li>
  29839. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  29840. * not available.
  29841. * </li>
  29842. * <li>
  29843. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  29844. * interpolated.
  29845. * </li>
  29846. * </ol>
  29847. * </div>
  29848. *
  29849. * @example
  29850. * <example name="ngPatternDirective" module="ngPatternExample">
  29851. * <file name="index.html">
  29852. * <script>
  29853. * angular.module('ngPatternExample', [])
  29854. * .controller('ExampleController', ['$scope', function($scope) {
  29855. * $scope.regex = '\\d+';
  29856. * }]);
  29857. * </script>
  29858. * <div ng-controller="ExampleController">
  29859. * <form name="form">
  29860. * <label for="regex">Set a pattern (regex string): </label>
  29861. * <input type="text" ng-model="regex" id="regex" />
  29862. * <br>
  29863. * <label for="input">This input is restricted by the current pattern: </label>
  29864. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  29865. * <hr>
  29866. * input valid? = <code>{{form.input.$valid}}</code><br>
  29867. * model = <code>{{model}}</code>
  29868. * </form>
  29869. * </div>
  29870. * </file>
  29871. * <file name="protractor.js" type="protractor">
  29872. var model = element(by.binding('model'));
  29873. var input = element(by.id('input'));
  29874. it('should validate the input with the default pattern', function() {
  29875. input.sendKeys('aaa');
  29876. expect(model.getText()).not.toContain('aaa');
  29877. input.clear().then(function() {
  29878. input.sendKeys('123');
  29879. expect(model.getText()).toContain('123');
  29880. });
  29881. });
  29882. * </file>
  29883. * </example>
  29884. */
  29885. var patternDirective = function() {
  29886. return {
  29887. restrict: 'A',
  29888. require: '?ngModel',
  29889. link: function(scope, elm, attr, ctrl) {
  29890. if (!ctrl) return;
  29891. var regexp, patternExp = attr.ngPattern || attr.pattern;
  29892. attr.$observe('pattern', function(regex) {
  29893. if (isString(regex) && regex.length > 0) {
  29894. regex = new RegExp('^' + regex + '$');
  29895. }
  29896. if (regex && !regex.test) {
  29897. throw minErr('ngPattern')('noregexp',
  29898. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  29899. regex, startingTag(elm));
  29900. }
  29901. regexp = regex || undefined;
  29902. ctrl.$validate();
  29903. });
  29904. ctrl.$validators.pattern = function(modelValue, viewValue) {
  29905. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  29906. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  29907. };
  29908. }
  29909. };
  29910. };
  29911. /**
  29912. * @ngdoc directive
  29913. * @name ngMaxlength
  29914. *
  29915. * @description
  29916. *
  29917. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29918. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  29919. *
  29920. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  29921. * is longer than the integer obtained by evaluating the Angular expression given in the
  29922. * `ngMaxlength` attribute value.
  29923. *
  29924. * <div class="alert alert-info">
  29925. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  29926. * differences:
  29927. * <ol>
  29928. * <li>
  29929. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  29930. * validation is not available.
  29931. * </li>
  29932. * <li>
  29933. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  29934. * interpolated.
  29935. * </li>
  29936. * </ol>
  29937. * </div>
  29938. *
  29939. * @example
  29940. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  29941. * <file name="index.html">
  29942. * <script>
  29943. * angular.module('ngMaxlengthExample', [])
  29944. * .controller('ExampleController', ['$scope', function($scope) {
  29945. * $scope.maxlength = 5;
  29946. * }]);
  29947. * </script>
  29948. * <div ng-controller="ExampleController">
  29949. * <form name="form">
  29950. * <label for="maxlength">Set a maxlength: </label>
  29951. * <input type="number" ng-model="maxlength" id="maxlength" />
  29952. * <br>
  29953. * <label for="input">This input is restricted by the current maxlength: </label>
  29954. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  29955. * <hr>
  29956. * input valid? = <code>{{form.input.$valid}}</code><br>
  29957. * model = <code>{{model}}</code>
  29958. * </form>
  29959. * </div>
  29960. * </file>
  29961. * <file name="protractor.js" type="protractor">
  29962. var model = element(by.binding('model'));
  29963. var input = element(by.id('input'));
  29964. it('should validate the input with the default maxlength', function() {
  29965. input.sendKeys('abcdef');
  29966. expect(model.getText()).not.toContain('abcdef');
  29967. input.clear().then(function() {
  29968. input.sendKeys('abcde');
  29969. expect(model.getText()).toContain('abcde');
  29970. });
  29971. });
  29972. * </file>
  29973. * </example>
  29974. */
  29975. var maxlengthDirective = function() {
  29976. return {
  29977. restrict: 'A',
  29978. require: '?ngModel',
  29979. link: function(scope, elm, attr, ctrl) {
  29980. if (!ctrl) return;
  29981. var maxlength = -1;
  29982. attr.$observe('maxlength', function(value) {
  29983. var intVal = toInt(value);
  29984. maxlength = isNumberNaN(intVal) ? -1 : intVal;
  29985. ctrl.$validate();
  29986. });
  29987. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  29988. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  29989. };
  29990. }
  29991. };
  29992. };
  29993. /**
  29994. * @ngdoc directive
  29995. * @name ngMinlength
  29996. *
  29997. * @description
  29998. *
  29999. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30000. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30001. *
  30002. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30003. * is shorter than the integer obtained by evaluating the Angular expression given in the
  30004. * `ngMinlength` attribute value.
  30005. *
  30006. * <div class="alert alert-info">
  30007. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  30008. * differences:
  30009. * <ol>
  30010. * <li>
  30011. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  30012. * validation is not available.
  30013. * </li>
  30014. * <li>
  30015. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  30016. * interpolated.
  30017. * </li>
  30018. * </ol>
  30019. * </div>
  30020. *
  30021. * @example
  30022. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  30023. * <file name="index.html">
  30024. * <script>
  30025. * angular.module('ngMinlengthExample', [])
  30026. * .controller('ExampleController', ['$scope', function($scope) {
  30027. * $scope.minlength = 3;
  30028. * }]);
  30029. * </script>
  30030. * <div ng-controller="ExampleController">
  30031. * <form name="form">
  30032. * <label for="minlength">Set a minlength: </label>
  30033. * <input type="number" ng-model="minlength" id="minlength" />
  30034. * <br>
  30035. * <label for="input">This input is restricted by the current minlength: </label>
  30036. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  30037. * <hr>
  30038. * input valid? = <code>{{form.input.$valid}}</code><br>
  30039. * model = <code>{{model}}</code>
  30040. * </form>
  30041. * </div>
  30042. * </file>
  30043. * <file name="protractor.js" type="protractor">
  30044. var model = element(by.binding('model'));
  30045. var input = element(by.id('input'));
  30046. it('should validate the input with the default minlength', function() {
  30047. input.sendKeys('ab');
  30048. expect(model.getText()).not.toContain('ab');
  30049. input.sendKeys('abc');
  30050. expect(model.getText()).toContain('abc');
  30051. });
  30052. * </file>
  30053. * </example>
  30054. */
  30055. var minlengthDirective = function() {
  30056. return {
  30057. restrict: 'A',
  30058. require: '?ngModel',
  30059. link: function(scope, elm, attr, ctrl) {
  30060. if (!ctrl) return;
  30061. var minlength = 0;
  30062. attr.$observe('minlength', function(value) {
  30063. minlength = toInt(value) || 0;
  30064. ctrl.$validate();
  30065. });
  30066. ctrl.$validators.minlength = function(modelValue, viewValue) {
  30067. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  30068. };
  30069. }
  30070. };
  30071. };
  30072. if (window.angular.bootstrap) {
  30073. // AngularJS is already loaded, so we can return here...
  30074. if (window.console) {
  30075. console.log('WARNING: Tried to load angular more than once.');
  30076. }
  30077. return;
  30078. }
  30079. // try to bind to jquery now so that one can write jqLite(fn)
  30080. // but we will rebind on bootstrap again.
  30081. bindJQuery();
  30082. publishExternalAPI(angular);
  30083. angular.module("ngLocale", [], ["$provide", function($provide) {
  30084. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  30085. function getDecimals(n) {
  30086. n = n + '';
  30087. var i = n.indexOf('.');
  30088. return (i == -1) ? 0 : n.length - i - 1;
  30089. }
  30090. function getVF(n, opt_precision) {
  30091. var v = opt_precision;
  30092. if (undefined === v) {
  30093. v = Math.min(getDecimals(n), 3);
  30094. }
  30095. var base = Math.pow(10, v);
  30096. var f = ((n * base) | 0) % base;
  30097. return {v: v, f: f};
  30098. }
  30099. $provide.value("$locale", {
  30100. "DATETIME_FORMATS": {
  30101. "AMPMS": [
  30102. "AM",
  30103. "PM"
  30104. ],
  30105. "DAY": [
  30106. "Sunday",
  30107. "Monday",
  30108. "Tuesday",
  30109. "Wednesday",
  30110. "Thursday",
  30111. "Friday",
  30112. "Saturday"
  30113. ],
  30114. "ERANAMES": [
  30115. "Before Christ",
  30116. "Anno Domini"
  30117. ],
  30118. "ERAS": [
  30119. "BC",
  30120. "AD"
  30121. ],
  30122. "FIRSTDAYOFWEEK": 6,
  30123. "MONTH": [
  30124. "January",
  30125. "February",
  30126. "March",
  30127. "April",
  30128. "May",
  30129. "June",
  30130. "July",
  30131. "August",
  30132. "September",
  30133. "October",
  30134. "November",
  30135. "December"
  30136. ],
  30137. "SHORTDAY": [
  30138. "Sun",
  30139. "Mon",
  30140. "Tue",
  30141. "Wed",
  30142. "Thu",
  30143. "Fri",
  30144. "Sat"
  30145. ],
  30146. "SHORTMONTH": [
  30147. "Jan",
  30148. "Feb",
  30149. "Mar",
  30150. "Apr",
  30151. "May",
  30152. "Jun",
  30153. "Jul",
  30154. "Aug",
  30155. "Sep",
  30156. "Oct",
  30157. "Nov",
  30158. "Dec"
  30159. ],
  30160. "STANDALONEMONTH": [
  30161. "January",
  30162. "February",
  30163. "March",
  30164. "April",
  30165. "May",
  30166. "June",
  30167. "July",
  30168. "August",
  30169. "September",
  30170. "October",
  30171. "November",
  30172. "December"
  30173. ],
  30174. "WEEKENDRANGE": [
  30175. 5,
  30176. 6
  30177. ],
  30178. "fullDate": "EEEE, MMMM d, y",
  30179. "longDate": "MMMM d, y",
  30180. "medium": "MMM d, y h:mm:ss a",
  30181. "mediumDate": "MMM d, y",
  30182. "mediumTime": "h:mm:ss a",
  30183. "short": "M/d/yy h:mm a",
  30184. "shortDate": "M/d/yy",
  30185. "shortTime": "h:mm a"
  30186. },
  30187. "NUMBER_FORMATS": {
  30188. "CURRENCY_SYM": "$",
  30189. "DECIMAL_SEP": ".",
  30190. "GROUP_SEP": ",",
  30191. "PATTERNS": [
  30192. {
  30193. "gSize": 3,
  30194. "lgSize": 3,
  30195. "maxFrac": 3,
  30196. "minFrac": 0,
  30197. "minInt": 1,
  30198. "negPre": "-",
  30199. "negSuf": "",
  30200. "posPre": "",
  30201. "posSuf": ""
  30202. },
  30203. {
  30204. "gSize": 3,
  30205. "lgSize": 3,
  30206. "maxFrac": 2,
  30207. "minFrac": 2,
  30208. "minInt": 1,
  30209. "negPre": "-\u00a4",
  30210. "negSuf": "",
  30211. "posPre": "\u00a4",
  30212. "posSuf": ""
  30213. }
  30214. ]
  30215. },
  30216. "id": "en-us",
  30217. "localeID": "en_US",
  30218. "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;}
  30219. });
  30220. }]);
  30221. jqLite(function() {
  30222. angularInit(window.document, bootstrap);
  30223. });
  30224. })(window);
  30225. !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>');