angular.js 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221
  1. /**
  2. * @license AngularJS v1.7.5
  3. * (c) 2010-2018 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window) {'use strict';
  7. /* exported
  8. minErrConfig,
  9. errorHandlingConfig,
  10. isValidObjectMaxDepth
  11. */
  12. var minErrConfig = {
  13. objectMaxDepth: 5,
  14. urlErrorParamsEnabled: true
  15. };
  16. /**
  17. * @ngdoc function
  18. * @name angular.errorHandlingConfig
  19. * @module ng
  20. * @kind function
  21. *
  22. * @description
  23. * Configure several aspects of error handling in AngularJS if used as a setter or return the
  24. * current configuration if used as a getter. The following options are supported:
  25. *
  26. * - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages.
  27. *
  28. * Omitted or undefined options will leave the corresponding configuration values unchanged.
  29. *
  30. * @param {Object=} config - The configuration object. May only contain the options that need to be
  31. * updated. Supported keys:
  32. *
  33. * * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a
  34. * non-positive or non-numeric value, removes the max depth limit.
  35. * Default: 5
  36. *
  37. * * `urlErrorParamsEnabled` **{Boolean}** - Specifies wether the generated error url will
  38. * contain the parameters of the thrown error. Disabling the parameters can be useful if the
  39. * generated error url is very long.
  40. *
  41. * Default: true. When used without argument, it returns the current value.
  42. */
  43. function errorHandlingConfig(config) {
  44. if (isObject(config)) {
  45. if (isDefined(config.objectMaxDepth)) {
  46. minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN;
  47. }
  48. if (isDefined(config.urlErrorParamsEnabled) && isBoolean(config.urlErrorParamsEnabled)) {
  49. minErrConfig.urlErrorParamsEnabled = config.urlErrorParamsEnabled;
  50. }
  51. } else {
  52. return minErrConfig;
  53. }
  54. }
  55. /**
  56. * @private
  57. * @param {Number} maxDepth
  58. * @return {boolean}
  59. */
  60. function isValidObjectMaxDepth(maxDepth) {
  61. return isNumber(maxDepth) && maxDepth > 0;
  62. }
  63. /**
  64. * @description
  65. *
  66. * This object provides a utility for producing rich Error messages within
  67. * AngularJS. It can be called as follows:
  68. *
  69. * var exampleMinErr = minErr('example');
  70. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  71. *
  72. * The above creates an instance of minErr in the example namespace. The
  73. * resulting error will have a namespaced error code of example.one. The
  74. * resulting error will replace {0} with the value of foo, and {1} with the
  75. * value of bar. The object is not restricted in the number of arguments it can
  76. * take.
  77. *
  78. * If fewer arguments are specified than necessary for interpolation, the extra
  79. * interpolation markers will be preserved in the final string.
  80. *
  81. * Since data will be parsed statically during a build step, some restrictions
  82. * are applied with respect to how minErr instances are created and called.
  83. * Instances should have names of the form namespaceMinErr for a minErr created
  84. * using minErr('namespace') . Error codes, namespaces and template strings
  85. * should all be static strings, not variables or general expressions.
  86. *
  87. * @param {string} module The namespace to use for the new minErr instance.
  88. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  89. * error from returned function, for cases when a particular type of error is useful.
  90. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  91. */
  92. function minErr(module, ErrorConstructor) {
  93. ErrorConstructor = ErrorConstructor || Error;
  94. var url = 'https://errors.angularjs.org/1.7.5/';
  95. var regex = url.replace('.', '\\.') + '[\\s\\S]*';
  96. var errRegExp = new RegExp(regex, 'g');
  97. return function() {
  98. var code = arguments[0],
  99. template = arguments[1],
  100. message = '[' + (module ? module + ':' : '') + code + '] ',
  101. templateArgs = sliceArgs(arguments, 2).map(function(arg) {
  102. return toDebugString(arg, minErrConfig.objectMaxDepth);
  103. }),
  104. paramPrefix, i;
  105. // A minErr message has two parts: the message itself and the url that contains the
  106. // encoded message.
  107. // The message's parameters can contain other error messages which also include error urls.
  108. // To prevent the messages from getting too long, we strip the error urls from the parameters.
  109. message += template.replace(/\{\d+\}/g, function(match) {
  110. var index = +match.slice(1, -1);
  111. if (index < templateArgs.length) {
  112. return templateArgs[index].replace(errRegExp, '');
  113. }
  114. return match;
  115. });
  116. message += '\n' + url + (module ? module + '/' : '') + code;
  117. if (minErrConfig.urlErrorParamsEnabled) {
  118. for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  119. message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]);
  120. }
  121. }
  122. return new ErrorConstructor(message);
  123. };
  124. }
  125. /* We need to tell ESLint what variables are being exported */
  126. /* exported
  127. angular,
  128. msie,
  129. jqLite,
  130. jQuery,
  131. slice,
  132. splice,
  133. push,
  134. toString,
  135. minErrConfig,
  136. errorHandlingConfig,
  137. isValidObjectMaxDepth,
  138. ngMinErr,
  139. angularModule,
  140. uid,
  141. REGEX_STRING_REGEXP,
  142. VALIDITY_STATE_PROPERTY,
  143. lowercase,
  144. uppercase,
  145. nodeName_,
  146. isArrayLike,
  147. forEach,
  148. forEachSorted,
  149. reverseParams,
  150. nextUid,
  151. setHashKey,
  152. extend,
  153. toInt,
  154. inherit,
  155. merge,
  156. noop,
  157. identity,
  158. valueFn,
  159. isUndefined,
  160. isDefined,
  161. isObject,
  162. isBlankObject,
  163. isString,
  164. isNumber,
  165. isNumberNaN,
  166. isDate,
  167. isError,
  168. isArray,
  169. isFunction,
  170. isRegExp,
  171. isWindow,
  172. isScope,
  173. isFile,
  174. isFormData,
  175. isBlob,
  176. isBoolean,
  177. isPromiseLike,
  178. trim,
  179. escapeForRegexp,
  180. isElement,
  181. makeMap,
  182. includes,
  183. arrayRemove,
  184. copy,
  185. simpleCompare,
  186. equals,
  187. csp,
  188. jq,
  189. concat,
  190. sliceArgs,
  191. bind,
  192. toJsonReplacer,
  193. toJson,
  194. fromJson,
  195. convertTimezoneToLocal,
  196. timezoneToOffset,
  197. addDateMinutes,
  198. startingTag,
  199. tryDecodeURIComponent,
  200. parseKeyValue,
  201. toKeyValue,
  202. encodeUriSegment,
  203. encodeUriQuery,
  204. angularInit,
  205. bootstrap,
  206. getTestability,
  207. snake_case,
  208. bindJQuery,
  209. assertArg,
  210. assertArgFn,
  211. assertNotHasOwnProperty,
  212. getter,
  213. getBlockNodes,
  214. hasOwnProperty,
  215. createMap,
  216. stringify,
  217. NODE_TYPE_ELEMENT,
  218. NODE_TYPE_ATTRIBUTE,
  219. NODE_TYPE_TEXT,
  220. NODE_TYPE_COMMENT,
  221. NODE_TYPE_DOCUMENT,
  222. NODE_TYPE_DOCUMENT_FRAGMENT
  223. */
  224. ////////////////////////////////////
  225. /**
  226. * @ngdoc module
  227. * @name ng
  228. * @module ng
  229. * @installation
  230. * @description
  231. *
  232. * The ng module is loaded by default when an AngularJS application is started. The module itself
  233. * contains the essential components for an AngularJS application to function. The table below
  234. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  235. * components available within this core module.
  236. *
  237. */
  238. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  239. // The name of a form control's ValidityState property.
  240. // This is used so that it's possible for internal tests to create mock ValidityStates.
  241. var VALIDITY_STATE_PROPERTY = 'validity';
  242. var hasOwnProperty = Object.prototype.hasOwnProperty;
  243. /**
  244. * @private
  245. *
  246. * @description Converts the specified string to lowercase.
  247. * @param {string} string String to be converted to lowercase.
  248. * @returns {string} Lowercased string.
  249. */
  250. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  251. /**
  252. * @private
  253. *
  254. * @description Converts the specified string to uppercase.
  255. * @param {string} string String to be converted to uppercase.
  256. * @returns {string} Uppercased string.
  257. */
  258. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  259. var
  260. msie, // holds major version number for IE, or NaN if UA is not IE.
  261. jqLite, // delay binding since jQuery could be loaded after us.
  262. jQuery, // delay binding
  263. slice = [].slice,
  264. splice = [].splice,
  265. push = [].push,
  266. toString = Object.prototype.toString,
  267. getPrototypeOf = Object.getPrototypeOf,
  268. ngMinErr = minErr('ng'),
  269. /** @name angular */
  270. angular = window.angular || (window.angular = {}),
  271. angularModule,
  272. uid = 0;
  273. // Support: IE 9-11 only
  274. /**
  275. * documentMode is an IE-only property
  276. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  277. */
  278. msie = window.document.documentMode;
  279. /**
  280. * @private
  281. * @param {*} obj
  282. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  283. * String ...)
  284. */
  285. function isArrayLike(obj) {
  286. // `null`, `undefined` and `window` are not array-like
  287. if (obj == null || isWindow(obj)) return false;
  288. // arrays, strings and jQuery/jqLite objects are array like
  289. // * jqLite is either the jQuery or jqLite constructor function
  290. // * we have to check the existence of jqLite first as this method is called
  291. // via the forEach method when constructing the jqLite object in the first place
  292. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  293. // Support: iOS 8.2 (not reproducible in simulator)
  294. // "length" in obj used to prevent JIT error (gh-11508)
  295. var length = 'length' in Object(obj) && obj.length;
  296. // NodeList objects (with `item` method) and
  297. // other objects with suitable length characteristics are array-like
  298. return isNumber(length) && (length >= 0 && (length - 1) in obj || typeof obj.item === 'function');
  299. }
  300. /**
  301. * @ngdoc function
  302. * @name angular.forEach
  303. * @module ng
  304. * @kind function
  305. *
  306. * @description
  307. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  308. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  309. * is the value of an object property or an array element, `key` is the object property key or
  310. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  311. *
  312. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  313. * using the `hasOwnProperty` method.
  314. *
  315. * Unlike ES262's
  316. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  317. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  318. * return the value provided.
  319. *
  320. ```js
  321. var values = {name: 'misko', gender: 'male'};
  322. var log = [];
  323. angular.forEach(values, function(value, key) {
  324. this.push(key + ': ' + value);
  325. }, log);
  326. expect(log).toEqual(['name: misko', 'gender: male']);
  327. ```
  328. *
  329. * @param {Object|Array} obj Object to iterate over.
  330. * @param {Function} iterator Iterator function.
  331. * @param {Object=} context Object to become context (`this`) for the iterator function.
  332. * @returns {Object|Array} Reference to `obj`.
  333. */
  334. function forEach(obj, iterator, context) {
  335. var key, length;
  336. if (obj) {
  337. if (isFunction(obj)) {
  338. for (key in obj) {
  339. if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
  340. iterator.call(context, obj[key], key, obj);
  341. }
  342. }
  343. } else if (isArray(obj) || isArrayLike(obj)) {
  344. var isPrimitive = typeof obj !== 'object';
  345. for (key = 0, length = obj.length; key < length; key++) {
  346. if (isPrimitive || key in obj) {
  347. iterator.call(context, obj[key], key, obj);
  348. }
  349. }
  350. } else if (obj.forEach && obj.forEach !== forEach) {
  351. obj.forEach(iterator, context, obj);
  352. } else if (isBlankObject(obj)) {
  353. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  354. for (key in obj) {
  355. iterator.call(context, obj[key], key, obj);
  356. }
  357. } else if (typeof obj.hasOwnProperty === 'function') {
  358. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  359. for (key in obj) {
  360. if (obj.hasOwnProperty(key)) {
  361. iterator.call(context, obj[key], key, obj);
  362. }
  363. }
  364. } else {
  365. // Slow path for objects which do not have a method `hasOwnProperty`
  366. for (key in obj) {
  367. if (hasOwnProperty.call(obj, key)) {
  368. iterator.call(context, obj[key], key, obj);
  369. }
  370. }
  371. }
  372. }
  373. return obj;
  374. }
  375. function forEachSorted(obj, iterator, context) {
  376. var keys = Object.keys(obj).sort();
  377. for (var i = 0; i < keys.length; i++) {
  378. iterator.call(context, obj[keys[i]], keys[i]);
  379. }
  380. return keys;
  381. }
  382. /**
  383. * when using forEach the params are value, key, but it is often useful to have key, value.
  384. * @param {function(string, *)} iteratorFn
  385. * @returns {function(*, string)}
  386. */
  387. function reverseParams(iteratorFn) {
  388. return function(value, key) {iteratorFn(key, value);};
  389. }
  390. /**
  391. * A consistent way of creating unique IDs in angular.
  392. *
  393. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  394. * we hit number precision issues in JavaScript.
  395. *
  396. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  397. *
  398. * @returns {number} an unique alpha-numeric string
  399. */
  400. function nextUid() {
  401. return ++uid;
  402. }
  403. /**
  404. * Set or clear the hashkey for an object.
  405. * @param obj object
  406. * @param h the hashkey (!truthy to delete the hashkey)
  407. */
  408. function setHashKey(obj, h) {
  409. if (h) {
  410. obj.$$hashKey = h;
  411. } else {
  412. delete obj.$$hashKey;
  413. }
  414. }
  415. function baseExtend(dst, objs, deep) {
  416. var h = dst.$$hashKey;
  417. for (var i = 0, ii = objs.length; i < ii; ++i) {
  418. var obj = objs[i];
  419. if (!isObject(obj) && !isFunction(obj)) continue;
  420. var keys = Object.keys(obj);
  421. for (var j = 0, jj = keys.length; j < jj; j++) {
  422. var key = keys[j];
  423. var src = obj[key];
  424. if (deep && isObject(src)) {
  425. if (isDate(src)) {
  426. dst[key] = new Date(src.valueOf());
  427. } else if (isRegExp(src)) {
  428. dst[key] = new RegExp(src);
  429. } else if (src.nodeName) {
  430. dst[key] = src.cloneNode(true);
  431. } else if (isElement(src)) {
  432. dst[key] = src.clone();
  433. } else {
  434. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  435. baseExtend(dst[key], [src], true);
  436. }
  437. } else {
  438. dst[key] = src;
  439. }
  440. }
  441. }
  442. setHashKey(dst, h);
  443. return dst;
  444. }
  445. /**
  446. * @ngdoc function
  447. * @name angular.extend
  448. * @module ng
  449. * @kind function
  450. *
  451. * @description
  452. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  453. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  454. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  455. *
  456. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  457. * {@link angular.merge} for this.
  458. *
  459. * @param {Object} dst Destination object.
  460. * @param {...Object} src Source object(s).
  461. * @returns {Object} Reference to `dst`.
  462. */
  463. function extend(dst) {
  464. return baseExtend(dst, slice.call(arguments, 1), false);
  465. }
  466. /**
  467. * @ngdoc function
  468. * @name angular.merge
  469. * @module ng
  470. * @kind function
  471. *
  472. * @description
  473. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  474. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  475. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  476. *
  477. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  478. * objects, performing a deep copy.
  479. *
  480. * @deprecated
  481. * sinceVersion="1.6.5"
  482. * This function is deprecated, but will not be removed in the 1.x lifecycle.
  483. * There are edge cases (see {@link angular.merge#known-issues known issues}) that are not
  484. * supported by this function. We suggest
  485. * using [lodash's merge()](https://lodash.com/docs/4.17.4#merge) instead.
  486. *
  487. * @knownIssue
  488. * This is a list of (known) object types that are not handled correctly by this function:
  489. * - [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob)
  490. * - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream)
  491. * - [`CanvasGradient`](https://developer.mozilla.org/docs/Web/API/CanvasGradient)
  492. * - AngularJS {@link $rootScope.Scope scopes};
  493. *
  494. * @param {Object} dst Destination object.
  495. * @param {...Object} src Source object(s).
  496. * @returns {Object} Reference to `dst`.
  497. */
  498. function merge(dst) {
  499. return baseExtend(dst, slice.call(arguments, 1), true);
  500. }
  501. function toInt(str) {
  502. return parseInt(str, 10);
  503. }
  504. var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
  505. // eslint-disable-next-line no-self-compare
  506. return num !== num;
  507. };
  508. function inherit(parent, extra) {
  509. return extend(Object.create(parent), extra);
  510. }
  511. /**
  512. * @ngdoc function
  513. * @name angular.noop
  514. * @module ng
  515. * @kind function
  516. *
  517. * @description
  518. * A function that performs no operations. This function can be useful when writing code in the
  519. * functional style.
  520. ```js
  521. function foo(callback) {
  522. var result = calculateResult();
  523. (callback || angular.noop)(result);
  524. }
  525. ```
  526. */
  527. function noop() {}
  528. noop.$inject = [];
  529. /**
  530. * @ngdoc function
  531. * @name angular.identity
  532. * @module ng
  533. * @kind function
  534. *
  535. * @description
  536. * A function that returns its first argument. This function is useful when writing code in the
  537. * functional style.
  538. *
  539. ```js
  540. function transformer(transformationFn, value) {
  541. return (transformationFn || angular.identity)(value);
  542. };
  543. // E.g.
  544. function getResult(fn, input) {
  545. return (fn || angular.identity)(input);
  546. };
  547. getResult(function(n) { return n * 2; }, 21); // returns 42
  548. getResult(null, 21); // returns 21
  549. getResult(undefined, 21); // returns 21
  550. ```
  551. *
  552. * @param {*} value to be returned.
  553. * @returns {*} the value passed in.
  554. */
  555. function identity($) {return $;}
  556. identity.$inject = [];
  557. function valueFn(value) {return function valueRef() {return value;};}
  558. function hasCustomToString(obj) {
  559. return isFunction(obj.toString) && obj.toString !== toString;
  560. }
  561. /**
  562. * @ngdoc function
  563. * @name angular.isUndefined
  564. * @module ng
  565. * @kind function
  566. *
  567. * @description
  568. * Determines if a reference is undefined.
  569. *
  570. * @param {*} value Reference to check.
  571. * @returns {boolean} True if `value` is undefined.
  572. */
  573. function isUndefined(value) {return typeof value === 'undefined';}
  574. /**
  575. * @ngdoc function
  576. * @name angular.isDefined
  577. * @module ng
  578. * @kind function
  579. *
  580. * @description
  581. * Determines if a reference is defined.
  582. *
  583. * @param {*} value Reference to check.
  584. * @returns {boolean} True if `value` is defined.
  585. */
  586. function isDefined(value) {return typeof value !== 'undefined';}
  587. /**
  588. * @ngdoc function
  589. * @name angular.isObject
  590. * @module ng
  591. * @kind function
  592. *
  593. * @description
  594. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  595. * considered to be objects. Note that JavaScript arrays are objects.
  596. *
  597. * @param {*} value Reference to check.
  598. * @returns {boolean} True if `value` is an `Object` but not `null`.
  599. */
  600. function isObject(value) {
  601. // http://jsperf.com/isobject4
  602. return value !== null && typeof value === 'object';
  603. }
  604. /**
  605. * Determine if a value is an object with a null prototype
  606. *
  607. * @returns {boolean} True if `value` is an `Object` with a null prototype
  608. */
  609. function isBlankObject(value) {
  610. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  611. }
  612. /**
  613. * @ngdoc function
  614. * @name angular.isString
  615. * @module ng
  616. * @kind function
  617. *
  618. * @description
  619. * Determines if a reference is a `String`.
  620. *
  621. * @param {*} value Reference to check.
  622. * @returns {boolean} True if `value` is a `String`.
  623. */
  624. function isString(value) {return typeof value === 'string';}
  625. /**
  626. * @ngdoc function
  627. * @name angular.isNumber
  628. * @module ng
  629. * @kind function
  630. *
  631. * @description
  632. * Determines if a reference is a `Number`.
  633. *
  634. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  635. *
  636. * If you wish to exclude these then you can use the native
  637. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  638. * method.
  639. *
  640. * @param {*} value Reference to check.
  641. * @returns {boolean} True if `value` is a `Number`.
  642. */
  643. function isNumber(value) {return typeof value === 'number';}
  644. /**
  645. * @ngdoc function
  646. * @name angular.isDate
  647. * @module ng
  648. * @kind function
  649. *
  650. * @description
  651. * Determines if a value is a date.
  652. *
  653. * @param {*} value Reference to check.
  654. * @returns {boolean} True if `value` is a `Date`.
  655. */
  656. function isDate(value) {
  657. return toString.call(value) === '[object Date]';
  658. }
  659. /**
  660. * @ngdoc function
  661. * @name angular.isArray
  662. * @module ng
  663. * @kind function
  664. *
  665. * @description
  666. * Determines if a reference is an `Array`.
  667. *
  668. * @param {*} value Reference to check.
  669. * @returns {boolean} True if `value` is an `Array`.
  670. */
  671. function isArray(arr) {
  672. return Array.isArray(arr) || arr instanceof Array;
  673. }
  674. /**
  675. * @description
  676. * Determines if a reference is an `Error`.
  677. * Loosely based on https://www.npmjs.com/package/iserror
  678. *
  679. * @param {*} value Reference to check.
  680. * @returns {boolean} True if `value` is an `Error`.
  681. */
  682. function isError(value) {
  683. var tag = toString.call(value);
  684. switch (tag) {
  685. case '[object Error]': return true;
  686. case '[object Exception]': return true;
  687. case '[object DOMException]': return true;
  688. default: return value instanceof Error;
  689. }
  690. }
  691. /**
  692. * @ngdoc function
  693. * @name angular.isFunction
  694. * @module ng
  695. * @kind function
  696. *
  697. * @description
  698. * Determines if a reference is a `Function`.
  699. *
  700. * @param {*} value Reference to check.
  701. * @returns {boolean} True if `value` is a `Function`.
  702. */
  703. function isFunction(value) {return typeof value === 'function';}
  704. /**
  705. * Determines if a value is a regular expression object.
  706. *
  707. * @private
  708. * @param {*} value Reference to check.
  709. * @returns {boolean} True if `value` is a `RegExp`.
  710. */
  711. function isRegExp(value) {
  712. return toString.call(value) === '[object RegExp]';
  713. }
  714. /**
  715. * Checks if `obj` is a window object.
  716. *
  717. * @private
  718. * @param {*} obj Object to check
  719. * @returns {boolean} True if `obj` is a window obj.
  720. */
  721. function isWindow(obj) {
  722. return obj && obj.window === obj;
  723. }
  724. function isScope(obj) {
  725. return obj && obj.$evalAsync && obj.$watch;
  726. }
  727. function isFile(obj) {
  728. return toString.call(obj) === '[object File]';
  729. }
  730. function isFormData(obj) {
  731. return toString.call(obj) === '[object FormData]';
  732. }
  733. function isBlob(obj) {
  734. return toString.call(obj) === '[object Blob]';
  735. }
  736. function isBoolean(value) {
  737. return typeof value === 'boolean';
  738. }
  739. function isPromiseLike(obj) {
  740. return obj && isFunction(obj.then);
  741. }
  742. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
  743. function isTypedArray(value) {
  744. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  745. }
  746. function isArrayBuffer(obj) {
  747. return toString.call(obj) === '[object ArrayBuffer]';
  748. }
  749. var trim = function(value) {
  750. return isString(value) ? value.trim() : value;
  751. };
  752. // Copied from:
  753. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  754. // Prereq: s is a string.
  755. var escapeForRegexp = function(s) {
  756. return s
  757. .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
  758. // eslint-disable-next-line no-control-regex
  759. .replace(/\x08/g, '\\x08');
  760. };
  761. /**
  762. * @ngdoc function
  763. * @name angular.isElement
  764. * @module ng
  765. * @kind function
  766. *
  767. * @description
  768. * Determines if a reference is a DOM element (or wrapped jQuery element).
  769. *
  770. * @param {*} value Reference to check.
  771. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  772. */
  773. function isElement(node) {
  774. return !!(node &&
  775. (node.nodeName // We are a direct element.
  776. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  777. }
  778. /**
  779. * @param str 'key1,key2,...'
  780. * @returns {object} in the form of {key1:true, key2:true, ...}
  781. */
  782. function makeMap(str) {
  783. var obj = {}, items = str.split(','), i;
  784. for (i = 0; i < items.length; i++) {
  785. obj[items[i]] = true;
  786. }
  787. return obj;
  788. }
  789. function nodeName_(element) {
  790. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  791. }
  792. function includes(array, obj) {
  793. return Array.prototype.indexOf.call(array, obj) !== -1;
  794. }
  795. function arrayRemove(array, value) {
  796. var index = array.indexOf(value);
  797. if (index >= 0) {
  798. array.splice(index, 1);
  799. }
  800. return index;
  801. }
  802. /**
  803. * @ngdoc function
  804. * @name angular.copy
  805. * @module ng
  806. * @kind function
  807. *
  808. * @description
  809. * Creates a deep copy of `source`, which should be an object or an array.
  810. *
  811. * * If no destination is supplied, a copy of the object or array is created.
  812. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  813. * are deleted and then all elements/properties from the source are copied to it.
  814. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  815. * * If `source` is identical to `destination` an exception will be thrown.
  816. *
  817. * <br />
  818. *
  819. * <div class="alert alert-warning">
  820. * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
  821. * and on `destination`) will be ignored.
  822. * </div>
  823. *
  824. * @param {*} source The source that will be used to make a copy. Can be any type, including
  825. * primitives, `null`, and `undefined`.
  826. * @param {(Object|Array)=} destination Destination into which the source is copied. If provided,
  827. * must be of the same type as `source`.
  828. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  829. *
  830. * @example
  831. <example module="copyExample" name="angular-copy">
  832. <file name="index.html">
  833. <div ng-controller="ExampleController">
  834. <form novalidate class="simple-form">
  835. <label>Name: <input type="text" ng-model="user.name" /></label><br />
  836. <label>Age: <input type="number" ng-model="user.age" /></label><br />
  837. Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
  838. <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
  839. <button ng-click="reset()">RESET</button>
  840. <button ng-click="update(user)">SAVE</button>
  841. </form>
  842. <pre>form = {{user | json}}</pre>
  843. <pre>leader = {{leader | json}}</pre>
  844. </div>
  845. </file>
  846. <file name="script.js">
  847. // Module: copyExample
  848. angular.
  849. module('copyExample', []).
  850. controller('ExampleController', ['$scope', function($scope) {
  851. $scope.leader = {};
  852. $scope.reset = function() {
  853. // Example with 1 argument
  854. $scope.user = angular.copy($scope.leader);
  855. };
  856. $scope.update = function(user) {
  857. // Example with 2 arguments
  858. angular.copy(user, $scope.leader);
  859. };
  860. $scope.reset();
  861. }]);
  862. </file>
  863. </example>
  864. */
  865. function copy(source, destination, maxDepth) {
  866. var stackSource = [];
  867. var stackDest = [];
  868. maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN;
  869. if (destination) {
  870. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  871. throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
  872. }
  873. if (source === destination) {
  874. throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
  875. }
  876. // Empty the destination object
  877. if (isArray(destination)) {
  878. destination.length = 0;
  879. } else {
  880. forEach(destination, function(value, key) {
  881. if (key !== '$$hashKey') {
  882. delete destination[key];
  883. }
  884. });
  885. }
  886. stackSource.push(source);
  887. stackDest.push(destination);
  888. return copyRecurse(source, destination, maxDepth);
  889. }
  890. return copyElement(source, maxDepth);
  891. function copyRecurse(source, destination, maxDepth) {
  892. maxDepth--;
  893. if (maxDepth < 0) {
  894. return '...';
  895. }
  896. var h = destination.$$hashKey;
  897. var key;
  898. if (isArray(source)) {
  899. for (var i = 0, ii = source.length; i < ii; i++) {
  900. destination.push(copyElement(source[i], maxDepth));
  901. }
  902. } else if (isBlankObject(source)) {
  903. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  904. for (key in source) {
  905. destination[key] = copyElement(source[key], maxDepth);
  906. }
  907. } else if (source && typeof source.hasOwnProperty === 'function') {
  908. // Slow path, which must rely on hasOwnProperty
  909. for (key in source) {
  910. if (source.hasOwnProperty(key)) {
  911. destination[key] = copyElement(source[key], maxDepth);
  912. }
  913. }
  914. } else {
  915. // Slowest path --- hasOwnProperty can't be called as a method
  916. for (key in source) {
  917. if (hasOwnProperty.call(source, key)) {
  918. destination[key] = copyElement(source[key], maxDepth);
  919. }
  920. }
  921. }
  922. setHashKey(destination, h);
  923. return destination;
  924. }
  925. function copyElement(source, maxDepth) {
  926. // Simple values
  927. if (!isObject(source)) {
  928. return source;
  929. }
  930. // Already copied values
  931. var index = stackSource.indexOf(source);
  932. if (index !== -1) {
  933. return stackDest[index];
  934. }
  935. if (isWindow(source) || isScope(source)) {
  936. throw ngMinErr('cpws',
  937. 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
  938. }
  939. var needsRecurse = false;
  940. var destination = copyType(source);
  941. if (destination === undefined) {
  942. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  943. needsRecurse = true;
  944. }
  945. stackSource.push(source);
  946. stackDest.push(destination);
  947. return needsRecurse
  948. ? copyRecurse(source, destination, maxDepth)
  949. : destination;
  950. }
  951. function copyType(source) {
  952. switch (toString.call(source)) {
  953. case '[object Int8Array]':
  954. case '[object Int16Array]':
  955. case '[object Int32Array]':
  956. case '[object Float32Array]':
  957. case '[object Float64Array]':
  958. case '[object Uint8Array]':
  959. case '[object Uint8ClampedArray]':
  960. case '[object Uint16Array]':
  961. case '[object Uint32Array]':
  962. return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
  963. case '[object ArrayBuffer]':
  964. // Support: IE10
  965. if (!source.slice) {
  966. // If we're in this case we know the environment supports ArrayBuffer
  967. /* eslint-disable no-undef */
  968. var copied = new ArrayBuffer(source.byteLength);
  969. new Uint8Array(copied).set(new Uint8Array(source));
  970. /* eslint-enable */
  971. return copied;
  972. }
  973. return source.slice(0);
  974. case '[object Boolean]':
  975. case '[object Number]':
  976. case '[object String]':
  977. case '[object Date]':
  978. return new source.constructor(source.valueOf());
  979. case '[object RegExp]':
  980. var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
  981. re.lastIndex = source.lastIndex;
  982. return re;
  983. case '[object Blob]':
  984. return new source.constructor([source], {type: source.type});
  985. }
  986. if (isFunction(source.cloneNode)) {
  987. return source.cloneNode(true);
  988. }
  989. }
  990. }
  991. // eslint-disable-next-line no-self-compare
  992. function simpleCompare(a, b) { return a === b || (a !== a && b !== b); }
  993. /**
  994. * @ngdoc function
  995. * @name angular.equals
  996. * @module ng
  997. * @kind function
  998. *
  999. * @description
  1000. * Determines if two objects or two values are equivalent. Supports value types, regular
  1001. * expressions, arrays and objects.
  1002. *
  1003. * Two objects or values are considered equivalent if at least one of the following is true:
  1004. *
  1005. * * Both objects or values pass `===` comparison.
  1006. * * Both objects or values are of the same type and all of their properties are equal by
  1007. * comparing them with `angular.equals`.
  1008. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  1009. * * Both values represent the same regular expression (In JavaScript,
  1010. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  1011. * representation matches).
  1012. *
  1013. * During a property comparison, properties of `function` type and properties with names
  1014. * that begin with `$` are ignored.
  1015. *
  1016. * Scope and DOMWindow objects are being compared only by identify (`===`).
  1017. *
  1018. * @param {*} o1 Object or value to compare.
  1019. * @param {*} o2 Object or value to compare.
  1020. * @returns {boolean} True if arguments are equal.
  1021. *
  1022. * @example
  1023. <example module="equalsExample" name="equalsExample">
  1024. <file name="index.html">
  1025. <div ng-controller="ExampleController">
  1026. <form novalidate>
  1027. <h3>User 1</h3>
  1028. Name: <input type="text" ng-model="user1.name">
  1029. Age: <input type="number" ng-model="user1.age">
  1030. <h3>User 2</h3>
  1031. Name: <input type="text" ng-model="user2.name">
  1032. Age: <input type="number" ng-model="user2.age">
  1033. <div>
  1034. <br/>
  1035. <input type="button" value="Compare" ng-click="compare()">
  1036. </div>
  1037. User 1: <pre>{{user1 | json}}</pre>
  1038. User 2: <pre>{{user2 | json}}</pre>
  1039. Equal: <pre>{{result}}</pre>
  1040. </form>
  1041. </div>
  1042. </file>
  1043. <file name="script.js">
  1044. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  1045. $scope.user1 = {};
  1046. $scope.user2 = {};
  1047. $scope.compare = function() {
  1048. $scope.result = angular.equals($scope.user1, $scope.user2);
  1049. };
  1050. }]);
  1051. </file>
  1052. </example>
  1053. */
  1054. function equals(o1, o2) {
  1055. if (o1 === o2) return true;
  1056. if (o1 === null || o2 === null) return false;
  1057. // eslint-disable-next-line no-self-compare
  1058. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  1059. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  1060. if (t1 === t2 && t1 === 'object') {
  1061. if (isArray(o1)) {
  1062. if (!isArray(o2)) return false;
  1063. if ((length = o1.length) === o2.length) {
  1064. for (key = 0; key < length; key++) {
  1065. if (!equals(o1[key], o2[key])) return false;
  1066. }
  1067. return true;
  1068. }
  1069. } else if (isDate(o1)) {
  1070. if (!isDate(o2)) return false;
  1071. return simpleCompare(o1.getTime(), o2.getTime());
  1072. } else if (isRegExp(o1)) {
  1073. if (!isRegExp(o2)) return false;
  1074. return o1.toString() === o2.toString();
  1075. } else {
  1076. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  1077. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  1078. keySet = createMap();
  1079. for (key in o1) {
  1080. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  1081. if (!equals(o1[key], o2[key])) return false;
  1082. keySet[key] = true;
  1083. }
  1084. for (key in o2) {
  1085. if (!(key in keySet) &&
  1086. key.charAt(0) !== '$' &&
  1087. isDefined(o2[key]) &&
  1088. !isFunction(o2[key])) return false;
  1089. }
  1090. return true;
  1091. }
  1092. }
  1093. return false;
  1094. }
  1095. var csp = function() {
  1096. if (!isDefined(csp.rules)) {
  1097. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  1098. window.document.querySelector('[data-ng-csp]'));
  1099. if (ngCspElement) {
  1100. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  1101. ngCspElement.getAttribute('data-ng-csp');
  1102. csp.rules = {
  1103. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  1104. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  1105. };
  1106. } else {
  1107. csp.rules = {
  1108. noUnsafeEval: noUnsafeEval(),
  1109. noInlineStyle: false
  1110. };
  1111. }
  1112. }
  1113. return csp.rules;
  1114. function noUnsafeEval() {
  1115. try {
  1116. // eslint-disable-next-line no-new, no-new-func
  1117. new Function('');
  1118. return false;
  1119. } catch (e) {
  1120. return true;
  1121. }
  1122. }
  1123. };
  1124. /**
  1125. * @ngdoc directive
  1126. * @module ng
  1127. * @name ngJq
  1128. *
  1129. * @element ANY
  1130. * @param {string=} ngJq the name of the library available under `window`
  1131. * to be used for angular.element
  1132. * @description
  1133. * Use this directive to force the angular.element library. This should be
  1134. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1135. * the jquery variable under window (eg. jQuery).
  1136. *
  1137. * Since AngularJS looks for this directive when it is loaded (doesn't wait for the
  1138. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1139. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1140. * others ignored.
  1141. *
  1142. * @example
  1143. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1144. ```html
  1145. <!doctype html>
  1146. <html ng-app ng-jq>
  1147. ...
  1148. ...
  1149. </html>
  1150. ```
  1151. * @example
  1152. * This example shows how to use a jQuery based library of a different name.
  1153. * The library name must be available at the top most 'window'.
  1154. ```html
  1155. <!doctype html>
  1156. <html ng-app ng-jq="jQueryLib">
  1157. ...
  1158. ...
  1159. </html>
  1160. ```
  1161. */
  1162. var jq = function() {
  1163. if (isDefined(jq.name_)) return jq.name_;
  1164. var el;
  1165. var i, ii = ngAttrPrefixes.length, prefix, name;
  1166. for (i = 0; i < ii; ++i) {
  1167. prefix = ngAttrPrefixes[i];
  1168. el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
  1169. if (el) {
  1170. name = el.getAttribute(prefix + 'jq');
  1171. break;
  1172. }
  1173. }
  1174. return (jq.name_ = name);
  1175. };
  1176. function concat(array1, array2, index) {
  1177. return array1.concat(slice.call(array2, index));
  1178. }
  1179. function sliceArgs(args, startIndex) {
  1180. return slice.call(args, startIndex || 0);
  1181. }
  1182. /**
  1183. * @ngdoc function
  1184. * @name angular.bind
  1185. * @module ng
  1186. * @kind function
  1187. *
  1188. * @description
  1189. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1190. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1191. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1192. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1193. *
  1194. * @param {Object} self Context which `fn` should be evaluated in.
  1195. * @param {function()} fn Function to be bound.
  1196. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1197. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1198. */
  1199. function bind(self, fn) {
  1200. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1201. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1202. return curryArgs.length
  1203. ? function() {
  1204. return arguments.length
  1205. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1206. : fn.apply(self, curryArgs);
  1207. }
  1208. : function() {
  1209. return arguments.length
  1210. ? fn.apply(self, arguments)
  1211. : fn.call(self);
  1212. };
  1213. } else {
  1214. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1215. return fn;
  1216. }
  1217. }
  1218. function toJsonReplacer(key, value) {
  1219. var val = value;
  1220. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1221. val = undefined;
  1222. } else if (isWindow(value)) {
  1223. val = '$WINDOW';
  1224. } else if (value && window.document === value) {
  1225. val = '$DOCUMENT';
  1226. } else if (isScope(value)) {
  1227. val = '$SCOPE';
  1228. }
  1229. return val;
  1230. }
  1231. /**
  1232. * @ngdoc function
  1233. * @name angular.toJson
  1234. * @module ng
  1235. * @kind function
  1236. *
  1237. * @description
  1238. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1239. * stripped since AngularJS uses this notation internally.
  1240. *
  1241. * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
  1242. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1243. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1244. * @returns {string|undefined} JSON-ified string representing `obj`.
  1245. * @knownIssue
  1246. *
  1247. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1248. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1249. * `Date.prototype.toJSON` method as follows:
  1250. *
  1251. * ```
  1252. * var _DatetoJSON = Date.prototype.toJSON;
  1253. * Date.prototype.toJSON = function() {
  1254. * try {
  1255. * return _DatetoJSON.call(this);
  1256. * } catch(e) {
  1257. * if (e instanceof RangeError) {
  1258. * return null;
  1259. * }
  1260. * throw e;
  1261. * }
  1262. * };
  1263. * ```
  1264. *
  1265. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1266. */
  1267. function toJson(obj, pretty) {
  1268. if (isUndefined(obj)) return undefined;
  1269. if (!isNumber(pretty)) {
  1270. pretty = pretty ? 2 : null;
  1271. }
  1272. return JSON.stringify(obj, toJsonReplacer, pretty);
  1273. }
  1274. /**
  1275. * @ngdoc function
  1276. * @name angular.fromJson
  1277. * @module ng
  1278. * @kind function
  1279. *
  1280. * @description
  1281. * Deserializes a JSON string.
  1282. *
  1283. * @param {string} json JSON string to deserialize.
  1284. * @returns {Object|Array|string|number} Deserialized JSON string.
  1285. */
  1286. function fromJson(json) {
  1287. return isString(json)
  1288. ? JSON.parse(json)
  1289. : json;
  1290. }
  1291. var ALL_COLONS = /:/g;
  1292. function timezoneToOffset(timezone, fallback) {
  1293. // Support: IE 9-11 only, Edge 13-15+
  1294. // IE/Edge do not "understand" colon (`:`) in timezone
  1295. timezone = timezone.replace(ALL_COLONS, '');
  1296. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1297. return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1298. }
  1299. function addDateMinutes(date, minutes) {
  1300. date = new Date(date.getTime());
  1301. date.setMinutes(date.getMinutes() + minutes);
  1302. return date;
  1303. }
  1304. function convertTimezoneToLocal(date, timezone, reverse) {
  1305. reverse = reverse ? -1 : 1;
  1306. var dateTimezoneOffset = date.getTimezoneOffset();
  1307. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1308. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1309. }
  1310. /**
  1311. * @returns {string} Returns the string representation of the element.
  1312. */
  1313. function startingTag(element) {
  1314. element = jqLite(element).clone().empty();
  1315. var elemHtml = jqLite('<div></div>').append(element).html();
  1316. try {
  1317. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1318. elemHtml.
  1319. match(/^(<[^>]+>)/)[1].
  1320. replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1321. } catch (e) {
  1322. return lowercase(elemHtml);
  1323. }
  1324. }
  1325. /////////////////////////////////////////////////
  1326. /**
  1327. * Tries to decode the URI component without throwing an exception.
  1328. *
  1329. * @private
  1330. * @param str value potential URI component to check.
  1331. * @returns {boolean} True if `value` can be decoded
  1332. * with the decodeURIComponent function.
  1333. */
  1334. function tryDecodeURIComponent(value) {
  1335. try {
  1336. return decodeURIComponent(value);
  1337. } catch (e) {
  1338. // Ignore any invalid uri component.
  1339. }
  1340. }
  1341. /**
  1342. * Parses an escaped url query string into key-value pairs.
  1343. * @returns {Object.<string,boolean|Array>}
  1344. */
  1345. function parseKeyValue(/**string*/keyValue) {
  1346. var obj = {};
  1347. forEach((keyValue || '').split('&'), function(keyValue) {
  1348. var splitPoint, key, val;
  1349. if (keyValue) {
  1350. key = keyValue = keyValue.replace(/\+/g,'%20');
  1351. splitPoint = keyValue.indexOf('=');
  1352. if (splitPoint !== -1) {
  1353. key = keyValue.substring(0, splitPoint);
  1354. val = keyValue.substring(splitPoint + 1);
  1355. }
  1356. key = tryDecodeURIComponent(key);
  1357. if (isDefined(key)) {
  1358. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1359. if (!hasOwnProperty.call(obj, key)) {
  1360. obj[key] = val;
  1361. } else if (isArray(obj[key])) {
  1362. obj[key].push(val);
  1363. } else {
  1364. obj[key] = [obj[key],val];
  1365. }
  1366. }
  1367. }
  1368. });
  1369. return obj;
  1370. }
  1371. function toKeyValue(obj) {
  1372. var parts = [];
  1373. forEach(obj, function(value, key) {
  1374. if (isArray(value)) {
  1375. forEach(value, function(arrayValue) {
  1376. parts.push(encodeUriQuery(key, true) +
  1377. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1378. });
  1379. } else {
  1380. parts.push(encodeUriQuery(key, true) +
  1381. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1382. }
  1383. });
  1384. return parts.length ? parts.join('&') : '';
  1385. }
  1386. /**
  1387. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1388. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1389. * segments:
  1390. * segment = *pchar
  1391. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1392. * pct-encoded = "%" HEXDIG HEXDIG
  1393. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1394. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1395. * / "*" / "+" / "," / ";" / "="
  1396. */
  1397. function encodeUriSegment(val) {
  1398. return encodeUriQuery(val, true).
  1399. replace(/%26/gi, '&').
  1400. replace(/%3D/gi, '=').
  1401. replace(/%2B/gi, '+');
  1402. }
  1403. /**
  1404. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1405. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1406. * encoded per http://tools.ietf.org/html/rfc3986:
  1407. * query = *( pchar / "/" / "?" )
  1408. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1409. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1410. * pct-encoded = "%" HEXDIG HEXDIG
  1411. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1412. * / "*" / "+" / "," / ";" / "="
  1413. */
  1414. function encodeUriQuery(val, pctEncodeSpaces) {
  1415. return encodeURIComponent(val).
  1416. replace(/%40/gi, '@').
  1417. replace(/%3A/gi, ':').
  1418. replace(/%24/g, '$').
  1419. replace(/%2C/gi, ',').
  1420. replace(/%3B/gi, ';').
  1421. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1422. }
  1423. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1424. function getNgAttribute(element, ngAttr) {
  1425. var attr, i, ii = ngAttrPrefixes.length;
  1426. for (i = 0; i < ii; ++i) {
  1427. attr = ngAttrPrefixes[i] + ngAttr;
  1428. if (isString(attr = element.getAttribute(attr))) {
  1429. return attr;
  1430. }
  1431. }
  1432. return null;
  1433. }
  1434. function allowAutoBootstrap(document) {
  1435. var script = document.currentScript;
  1436. if (!script) {
  1437. // Support: IE 9-11 only
  1438. // IE does not have `document.currentScript`
  1439. return true;
  1440. }
  1441. // If the `currentScript` property has been clobbered just return false, since this indicates a probable attack
  1442. if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) {
  1443. return false;
  1444. }
  1445. var attributes = script.attributes;
  1446. var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')];
  1447. return srcs.every(function(src) {
  1448. if (!src) {
  1449. return true;
  1450. }
  1451. if (!src.value) {
  1452. return false;
  1453. }
  1454. var link = document.createElement('a');
  1455. link.href = src.value;
  1456. if (document.location.origin === link.origin) {
  1457. // Same-origin resources are always allowed, even for non-whitelisted schemes.
  1458. return true;
  1459. }
  1460. // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
  1461. // This is to prevent angular.js bundled with browser extensions from being used to bypass the
  1462. // content security policy in web pages and other browser extensions.
  1463. switch (link.protocol) {
  1464. case 'http:':
  1465. case 'https:':
  1466. case 'ftp:':
  1467. case 'blob:':
  1468. case 'file:':
  1469. case 'data:':
  1470. return true;
  1471. default:
  1472. return false;
  1473. }
  1474. });
  1475. }
  1476. // Cached as it has to run during loading so that document.currentScript is available.
  1477. var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
  1478. /**
  1479. * @ngdoc directive
  1480. * @name ngApp
  1481. * @module ng
  1482. *
  1483. * @element ANY
  1484. * @param {angular.Module} ngApp an optional application
  1485. * {@link angular.module module} name to load.
  1486. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1487. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1488. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1489. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1490. * tracking down the root of these bugs.
  1491. *
  1492. * @description
  1493. *
  1494. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1495. * designates the **root element** of the application and is typically placed near the root element
  1496. * of the page - e.g. on the `<body>` or `<html>` tags.
  1497. *
  1498. * There are a few things to keep in mind when using `ngApp`:
  1499. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1500. * found in the document will be used to define the root element to auto-bootstrap as an
  1501. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1502. * {@link angular.bootstrap} instead.
  1503. * - AngularJS applications cannot be nested within each other.
  1504. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1505. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1506. * {@link ngRoute.ngView `ngView`}.
  1507. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1508. * causing animations to stop working and making the injector inaccessible from outside the app.
  1509. *
  1510. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1511. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1512. * should contain the application code needed or have dependencies on other modules that will
  1513. * contain the code. See {@link angular.module} for more information.
  1514. *
  1515. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1516. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1517. * would not be resolved to `3`.
  1518. *
  1519. * @example
  1520. *
  1521. * ### Simple Usage
  1522. *
  1523. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1524. *
  1525. <example module="ngAppDemo" name="ng-app">
  1526. <file name="index.html">
  1527. <div ng-controller="ngAppDemoController">
  1528. I can add: {{a}} + {{b}} = {{ a+b }}
  1529. </div>
  1530. </file>
  1531. <file name="script.js">
  1532. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1533. $scope.a = 1;
  1534. $scope.b = 2;
  1535. });
  1536. </file>
  1537. </example>
  1538. *
  1539. * @example
  1540. *
  1541. * ### With `ngStrictDi`
  1542. *
  1543. * Using `ngStrictDi`, you would see something like this:
  1544. *
  1545. <example ng-app-included="true" name="strict-di">
  1546. <file name="index.html">
  1547. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1548. <div ng-controller="GoodController1">
  1549. I can add: {{a}} + {{b}} = {{ a+b }}
  1550. <p>This renders because the controller does not fail to
  1551. instantiate, by using explicit annotation style (see
  1552. script.js for details)
  1553. </p>
  1554. </div>
  1555. <div ng-controller="GoodController2">
  1556. Name: <input ng-model="name"><br />
  1557. Hello, {{name}}!
  1558. <p>This renders because the controller does not fail to
  1559. instantiate, by using explicit annotation style
  1560. (see script.js for details)
  1561. </p>
  1562. </div>
  1563. <div ng-controller="BadController">
  1564. I can add: {{a}} + {{b}} = {{ a+b }}
  1565. <p>The controller could not be instantiated, due to relying
  1566. on automatic function annotations (which are disabled in
  1567. strict mode). As such, the content of this section is not
  1568. interpolated, and there should be an error in your web console.
  1569. </p>
  1570. </div>
  1571. </div>
  1572. </file>
  1573. <file name="script.js">
  1574. angular.module('ngAppStrictDemo', [])
  1575. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1576. // rather than an explicit annotation
  1577. .controller('BadController', function($scope) {
  1578. $scope.a = 1;
  1579. $scope.b = 2;
  1580. })
  1581. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1582. // due to using explicit annotations using the array style and $inject property, respectively.
  1583. .controller('GoodController1', ['$scope', function($scope) {
  1584. $scope.a = 1;
  1585. $scope.b = 2;
  1586. }])
  1587. .controller('GoodController2', GoodController2);
  1588. function GoodController2($scope) {
  1589. $scope.name = 'World';
  1590. }
  1591. GoodController2.$inject = ['$scope'];
  1592. </file>
  1593. <file name="style.css">
  1594. div[ng-controller] {
  1595. margin-bottom: 1em;
  1596. -webkit-border-radius: 4px;
  1597. border-radius: 4px;
  1598. border: 1px solid;
  1599. padding: .5em;
  1600. }
  1601. div[ng-controller^=Good] {
  1602. border-color: #d6e9c6;
  1603. background-color: #dff0d8;
  1604. color: #3c763d;
  1605. }
  1606. div[ng-controller^=Bad] {
  1607. border-color: #ebccd1;
  1608. background-color: #f2dede;
  1609. color: #a94442;
  1610. margin-bottom: 0;
  1611. }
  1612. </file>
  1613. </example>
  1614. */
  1615. function angularInit(element, bootstrap) {
  1616. var appElement,
  1617. module,
  1618. config = {};
  1619. // The element `element` has priority over any other element.
  1620. forEach(ngAttrPrefixes, function(prefix) {
  1621. var name = prefix + 'app';
  1622. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1623. appElement = element;
  1624. module = element.getAttribute(name);
  1625. }
  1626. });
  1627. forEach(ngAttrPrefixes, function(prefix) {
  1628. var name = prefix + 'app';
  1629. var candidate;
  1630. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1631. appElement = candidate;
  1632. module = candidate.getAttribute(name);
  1633. }
  1634. });
  1635. if (appElement) {
  1636. if (!isAutoBootstrapAllowed) {
  1637. try {
  1638. window.console.error('AngularJS: disabling automatic bootstrap. <script> protocol indicates ' +
  1639. 'an extension, document.location.href does not match.');
  1640. } catch (e) {
  1641. // Support: Safari 11 w/ Webdriver
  1642. // The console.error will throw and make the test fail
  1643. }
  1644. return;
  1645. }
  1646. config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
  1647. bootstrap(appElement, module ? [module] : [], config);
  1648. }
  1649. }
  1650. /**
  1651. * @ngdoc function
  1652. * @name angular.bootstrap
  1653. * @module ng
  1654. * @description
  1655. * Use this function to manually start up AngularJS application.
  1656. *
  1657. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1658. *
  1659. * AngularJS will detect if it has been loaded into the browser more than once and only allow the
  1660. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1661. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1662. * multiple instances of AngularJS try to work on the DOM.
  1663. *
  1664. * <div class="alert alert-warning">
  1665. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1666. * They must use {@link ng.directive:ngApp ngApp}.
  1667. * </div>
  1668. *
  1669. * <div class="alert alert-warning">
  1670. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1671. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1672. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1673. * causing animations to stop working and making the injector inaccessible from outside the app.
  1674. * </div>
  1675. *
  1676. * ```html
  1677. * <!doctype html>
  1678. * <html>
  1679. * <body>
  1680. * <div ng-controller="WelcomeController">
  1681. * {{greeting}}
  1682. * </div>
  1683. *
  1684. * <script src="angular.js"></script>
  1685. * <script>
  1686. * var app = angular.module('demo', [])
  1687. * .controller('WelcomeController', function($scope) {
  1688. * $scope.greeting = 'Welcome!';
  1689. * });
  1690. * angular.bootstrap(document, ['demo']);
  1691. * </script>
  1692. * </body>
  1693. * </html>
  1694. * ```
  1695. *
  1696. * @param {DOMElement} element DOM element which is the root of AngularJS application.
  1697. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1698. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1699. * function that will be invoked by the injector as a `config` block.
  1700. * See: {@link angular.module modules}
  1701. * @param {Object=} config an object for defining configuration options for the application. The
  1702. * following keys are supported:
  1703. *
  1704. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1705. * assist in finding bugs which break minified code. Defaults to `false`.
  1706. *
  1707. * @returns {auto.$injector} Returns the newly created injector for this app.
  1708. */
  1709. function bootstrap(element, modules, config) {
  1710. if (!isObject(config)) config = {};
  1711. var defaultConfig = {
  1712. strictDi: false
  1713. };
  1714. config = extend(defaultConfig, config);
  1715. var doBootstrap = function() {
  1716. element = jqLite(element);
  1717. if (element.injector()) {
  1718. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1719. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1720. throw ngMinErr(
  1721. 'btstrpd',
  1722. 'App already bootstrapped with this element \'{0}\'',
  1723. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1724. }
  1725. modules = modules || [];
  1726. modules.unshift(['$provide', function($provide) {
  1727. $provide.value('$rootElement', element);
  1728. }]);
  1729. if (config.debugInfoEnabled) {
  1730. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1731. modules.push(['$compileProvider', function($compileProvider) {
  1732. $compileProvider.debugInfoEnabled(true);
  1733. }]);
  1734. }
  1735. modules.unshift('ng');
  1736. var injector = createInjector(modules, config.strictDi);
  1737. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1738. function bootstrapApply(scope, element, compile, injector) {
  1739. scope.$apply(function() {
  1740. element.data('$injector', injector);
  1741. compile(element)(scope);
  1742. });
  1743. }]
  1744. );
  1745. return injector;
  1746. };
  1747. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1748. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1749. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1750. config.debugInfoEnabled = true;
  1751. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1752. }
  1753. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1754. return doBootstrap();
  1755. }
  1756. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1757. angular.resumeBootstrap = function(extraModules) {
  1758. forEach(extraModules, function(module) {
  1759. modules.push(module);
  1760. });
  1761. return doBootstrap();
  1762. };
  1763. if (isFunction(angular.resumeDeferredBootstrap)) {
  1764. angular.resumeDeferredBootstrap();
  1765. }
  1766. }
  1767. /**
  1768. * @ngdoc function
  1769. * @name angular.reloadWithDebugInfo
  1770. * @module ng
  1771. * @description
  1772. * Use this function to reload the current application with debug information turned on.
  1773. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1774. *
  1775. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1776. */
  1777. function reloadWithDebugInfo() {
  1778. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1779. window.location.reload();
  1780. }
  1781. /**
  1782. * @name angular.getTestability
  1783. * @module ng
  1784. * @description
  1785. * Get the testability service for the instance of AngularJS on the given
  1786. * element.
  1787. * @param {DOMElement} element DOM element which is the root of AngularJS application.
  1788. */
  1789. function getTestability(rootElement) {
  1790. var injector = angular.element(rootElement).injector();
  1791. if (!injector) {
  1792. throw ngMinErr('test',
  1793. 'no injector found for element argument to getTestability');
  1794. }
  1795. return injector.get('$$testability');
  1796. }
  1797. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1798. function snake_case(name, separator) {
  1799. separator = separator || '_';
  1800. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1801. return (pos ? separator : '') + letter.toLowerCase();
  1802. });
  1803. }
  1804. var bindJQueryFired = false;
  1805. function bindJQuery() {
  1806. var originalCleanData;
  1807. if (bindJQueryFired) {
  1808. return;
  1809. }
  1810. // bind to jQuery if present;
  1811. var jqName = jq();
  1812. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1813. !jqName ? undefined : // use jqLite
  1814. window[jqName]; // use jQuery specified by `ngJq`
  1815. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1816. // AngularJS 1.2+ requires jQuery 1.7+ for on()/off() support.
  1817. // AngularJS 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1818. // versions. It will not work for sure with jQuery <1.7, though.
  1819. if (jQuery && jQuery.fn.on) {
  1820. jqLite = jQuery;
  1821. extend(jQuery.fn, {
  1822. scope: JQLitePrototype.scope,
  1823. isolateScope: JQLitePrototype.isolateScope,
  1824. controller: /** @type {?} */ (JQLitePrototype).controller,
  1825. injector: JQLitePrototype.injector,
  1826. inheritedData: JQLitePrototype.inheritedData
  1827. });
  1828. } else {
  1829. jqLite = JQLite;
  1830. }
  1831. // All nodes removed from the DOM via various jqLite/jQuery APIs like .remove()
  1832. // are passed through jqLite/jQuery.cleanData. Monkey-patch this method to fire
  1833. // the $destroy event on all removed nodes.
  1834. originalCleanData = jqLite.cleanData;
  1835. jqLite.cleanData = function(elems) {
  1836. var events;
  1837. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1838. events = (jqLite._data(elem) || {}).events;
  1839. if (events && events.$destroy) {
  1840. jqLite(elem).triggerHandler('$destroy');
  1841. }
  1842. }
  1843. originalCleanData(elems);
  1844. };
  1845. angular.element = jqLite;
  1846. // Prevent double-proxying.
  1847. bindJQueryFired = true;
  1848. }
  1849. /**
  1850. * throw error if the argument is falsy.
  1851. */
  1852. function assertArg(arg, name, reason) {
  1853. if (!arg) {
  1854. throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
  1855. }
  1856. return arg;
  1857. }
  1858. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1859. if (acceptArrayAnnotation && isArray(arg)) {
  1860. arg = arg[arg.length - 1];
  1861. }
  1862. assertArg(isFunction(arg), name, 'not a function, got ' +
  1863. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1864. return arg;
  1865. }
  1866. /**
  1867. * throw error if the name given is hasOwnProperty
  1868. * @param {String} name the name to test
  1869. * @param {String} context the context in which the name is used, such as module or directive
  1870. */
  1871. function assertNotHasOwnProperty(name, context) {
  1872. if (name === 'hasOwnProperty') {
  1873. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1874. }
  1875. }
  1876. /**
  1877. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1878. * @param {Object} obj starting object
  1879. * @param {String} path path to traverse
  1880. * @param {boolean} [bindFnToScope=true]
  1881. * @returns {Object} value as accessible by path
  1882. */
  1883. //TODO(misko): this function needs to be removed
  1884. function getter(obj, path, bindFnToScope) {
  1885. if (!path) return obj;
  1886. var keys = path.split('.');
  1887. var key;
  1888. var lastInstance = obj;
  1889. var len = keys.length;
  1890. for (var i = 0; i < len; i++) {
  1891. key = keys[i];
  1892. if (obj) {
  1893. obj = (lastInstance = obj)[key];
  1894. }
  1895. }
  1896. if (!bindFnToScope && isFunction(obj)) {
  1897. return bind(lastInstance, obj);
  1898. }
  1899. return obj;
  1900. }
  1901. /**
  1902. * Return the DOM siblings between the first and last node in the given array.
  1903. * @param {Array} array like object
  1904. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1905. */
  1906. function getBlockNodes(nodes) {
  1907. // TODO(perf): update `nodes` instead of creating a new object?
  1908. var node = nodes[0];
  1909. var endNode = nodes[nodes.length - 1];
  1910. var blockNodes;
  1911. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1912. if (blockNodes || nodes[i] !== node) {
  1913. if (!blockNodes) {
  1914. blockNodes = jqLite(slice.call(nodes, 0, i));
  1915. }
  1916. blockNodes.push(node);
  1917. }
  1918. }
  1919. return blockNodes || nodes;
  1920. }
  1921. /**
  1922. * Creates a new object without a prototype. This object is useful for lookup without having to
  1923. * guard against prototypically inherited properties via hasOwnProperty.
  1924. *
  1925. * Related micro-benchmarks:
  1926. * - http://jsperf.com/object-create2
  1927. * - http://jsperf.com/proto-map-lookup/2
  1928. * - http://jsperf.com/for-in-vs-object-keys2
  1929. *
  1930. * @returns {Object}
  1931. */
  1932. function createMap() {
  1933. return Object.create(null);
  1934. }
  1935. function stringify(value) {
  1936. if (value == null) { // null || undefined
  1937. return '';
  1938. }
  1939. switch (typeof value) {
  1940. case 'string':
  1941. break;
  1942. case 'number':
  1943. value = '' + value;
  1944. break;
  1945. default:
  1946. if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
  1947. value = value.toString();
  1948. } else {
  1949. value = toJson(value);
  1950. }
  1951. }
  1952. return value;
  1953. }
  1954. var NODE_TYPE_ELEMENT = 1;
  1955. var NODE_TYPE_ATTRIBUTE = 2;
  1956. var NODE_TYPE_TEXT = 3;
  1957. var NODE_TYPE_COMMENT = 8;
  1958. var NODE_TYPE_DOCUMENT = 9;
  1959. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1960. /**
  1961. * @ngdoc type
  1962. * @name angular.Module
  1963. * @module ng
  1964. * @description
  1965. *
  1966. * Interface for configuring AngularJS {@link angular.module modules}.
  1967. */
  1968. function setupModuleLoader(window) {
  1969. var $injectorMinErr = minErr('$injector');
  1970. var ngMinErr = minErr('ng');
  1971. function ensure(obj, name, factory) {
  1972. return obj[name] || (obj[name] = factory());
  1973. }
  1974. var angular = ensure(window, 'angular', Object);
  1975. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1976. angular.$$minErr = angular.$$minErr || minErr;
  1977. return ensure(angular, 'module', function() {
  1978. /** @type {Object.<string, angular.Module>} */
  1979. var modules = {};
  1980. /**
  1981. * @ngdoc function
  1982. * @name angular.module
  1983. * @module ng
  1984. * @description
  1985. *
  1986. * The `angular.module` is a global place for creating, registering and retrieving AngularJS
  1987. * modules.
  1988. * All modules (AngularJS core or 3rd party) that should be available to an application must be
  1989. * registered using this mechanism.
  1990. *
  1991. * Passing one argument retrieves an existing {@link angular.Module},
  1992. * whereas passing more than one argument creates a new {@link angular.Module}
  1993. *
  1994. *
  1995. * # Module
  1996. *
  1997. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1998. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1999. *
  2000. * ```js
  2001. * // Create a new module
  2002. * var myModule = angular.module('myModule', []);
  2003. *
  2004. * // register a new service
  2005. * myModule.value('appName', 'MyCoolApp');
  2006. *
  2007. * // configure existing services inside initialization blocks.
  2008. * myModule.config(['$locationProvider', function($locationProvider) {
  2009. * // Configure existing providers
  2010. * $locationProvider.hashPrefix('!');
  2011. * }]);
  2012. * ```
  2013. *
  2014. * Then you can create an injector and load your modules like this:
  2015. *
  2016. * ```js
  2017. * var injector = angular.injector(['ng', 'myModule'])
  2018. * ```
  2019. *
  2020. * However it's more likely that you'll just use
  2021. * {@link ng.directive:ngApp ngApp} or
  2022. * {@link angular.bootstrap} to simplify this process for you.
  2023. *
  2024. * @param {!string} name The name of the module to create or retrieve.
  2025. * @param {!Array.<string>=} requires If specified then new module is being created. If
  2026. * unspecified then the module is being retrieved for further configuration.
  2027. * @param {Function=} configFn Optional configuration function for the module. Same as
  2028. * {@link angular.Module#config Module#config()}.
  2029. * @returns {angular.Module} new module with the {@link angular.Module} api.
  2030. */
  2031. return function module(name, requires, configFn) {
  2032. var info = {};
  2033. var assertNotHasOwnProperty = function(name, context) {
  2034. if (name === 'hasOwnProperty') {
  2035. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  2036. }
  2037. };
  2038. assertNotHasOwnProperty(name, 'module');
  2039. if (requires && modules.hasOwnProperty(name)) {
  2040. modules[name] = null;
  2041. }
  2042. return ensure(modules, name, function() {
  2043. if (!requires) {
  2044. throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
  2045. 'the module name or forgot to load it. If registering a module ensure that you ' +
  2046. 'specify the dependencies as the second argument.', name);
  2047. }
  2048. /** @type {!Array.<Array.<*>>} */
  2049. var invokeQueue = [];
  2050. /** @type {!Array.<Function>} */
  2051. var configBlocks = [];
  2052. /** @type {!Array.<Function>} */
  2053. var runBlocks = [];
  2054. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  2055. /** @type {angular.Module} */
  2056. var moduleInstance = {
  2057. // Private state
  2058. _invokeQueue: invokeQueue,
  2059. _configBlocks: configBlocks,
  2060. _runBlocks: runBlocks,
  2061. /**
  2062. * @ngdoc method
  2063. * @name angular.Module#info
  2064. * @module ng
  2065. *
  2066. * @param {Object=} info Information about the module
  2067. * @returns {Object|Module} The current info object for this module if called as a getter,
  2068. * or `this` if called as a setter.
  2069. *
  2070. * @description
  2071. * Read and write custom information about this module.
  2072. * For example you could put the version of the module in here.
  2073. *
  2074. * ```js
  2075. * angular.module('myModule', []).info({ version: '1.0.0' });
  2076. * ```
  2077. *
  2078. * The version could then be read back out by accessing the module elsewhere:
  2079. *
  2080. * ```
  2081. * var version = angular.module('myModule').info().version;
  2082. * ```
  2083. *
  2084. * You can also retrieve this information during runtime via the
  2085. * {@link $injector#modules `$injector.modules`} property:
  2086. *
  2087. * ```js
  2088. * var version = $injector.modules['myModule'].info().version;
  2089. * ```
  2090. */
  2091. info: function(value) {
  2092. if (isDefined(value)) {
  2093. if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value');
  2094. info = value;
  2095. return this;
  2096. }
  2097. return info;
  2098. },
  2099. /**
  2100. * @ngdoc property
  2101. * @name angular.Module#requires
  2102. * @module ng
  2103. *
  2104. * @description
  2105. * Holds the list of modules which the injector will load before the current module is
  2106. * loaded.
  2107. */
  2108. requires: requires,
  2109. /**
  2110. * @ngdoc property
  2111. * @name angular.Module#name
  2112. * @module ng
  2113. *
  2114. * @description
  2115. * Name of the module.
  2116. */
  2117. name: name,
  2118. /**
  2119. * @ngdoc method
  2120. * @name angular.Module#provider
  2121. * @module ng
  2122. * @param {string} name service name
  2123. * @param {Function} providerType Construction function for creating new instance of the
  2124. * service.
  2125. * @description
  2126. * See {@link auto.$provide#provider $provide.provider()}.
  2127. */
  2128. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  2129. /**
  2130. * @ngdoc method
  2131. * @name angular.Module#factory
  2132. * @module ng
  2133. * @param {string} name service name
  2134. * @param {Function} providerFunction Function for creating new instance of the service.
  2135. * @description
  2136. * See {@link auto.$provide#factory $provide.factory()}.
  2137. */
  2138. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  2139. /**
  2140. * @ngdoc method
  2141. * @name angular.Module#service
  2142. * @module ng
  2143. * @param {string} name service name
  2144. * @param {Function} constructor A constructor function that will be instantiated.
  2145. * @description
  2146. * See {@link auto.$provide#service $provide.service()}.
  2147. */
  2148. service: invokeLaterAndSetModuleName('$provide', 'service'),
  2149. /**
  2150. * @ngdoc method
  2151. * @name angular.Module#value
  2152. * @module ng
  2153. * @param {string} name service name
  2154. * @param {*} object Service instance object.
  2155. * @description
  2156. * See {@link auto.$provide#value $provide.value()}.
  2157. */
  2158. value: invokeLater('$provide', 'value'),
  2159. /**
  2160. * @ngdoc method
  2161. * @name angular.Module#constant
  2162. * @module ng
  2163. * @param {string} name constant name
  2164. * @param {*} object Constant value.
  2165. * @description
  2166. * Because the constants are fixed, they get applied before other provide methods.
  2167. * See {@link auto.$provide#constant $provide.constant()}.
  2168. */
  2169. constant: invokeLater('$provide', 'constant', 'unshift'),
  2170. /**
  2171. * @ngdoc method
  2172. * @name angular.Module#decorator
  2173. * @module ng
  2174. * @param {string} name The name of the service to decorate.
  2175. * @param {Function} decorFn This function will be invoked when the service needs to be
  2176. * instantiated and should return the decorated service instance.
  2177. * @description
  2178. * See {@link auto.$provide#decorator $provide.decorator()}.
  2179. */
  2180. decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
  2181. /**
  2182. * @ngdoc method
  2183. * @name angular.Module#animation
  2184. * @module ng
  2185. * @param {string} name animation name
  2186. * @param {Function} animationFactory Factory function for creating new instance of an
  2187. * animation.
  2188. * @description
  2189. *
  2190. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  2191. *
  2192. *
  2193. * Defines an animation hook that can be later used with
  2194. * {@link $animate $animate} service and directives that use this service.
  2195. *
  2196. * ```js
  2197. * module.animation('.animation-name', function($inject1, $inject2) {
  2198. * return {
  2199. * eventName : function(element, done) {
  2200. * //code to run the animation
  2201. * //once complete, then run done()
  2202. * return function cancellationFunction(element) {
  2203. * //code to cancel the animation
  2204. * }
  2205. * }
  2206. * }
  2207. * })
  2208. * ```
  2209. *
  2210. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  2211. * {@link ngAnimate ngAnimate module} for more information.
  2212. */
  2213. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  2214. /**
  2215. * @ngdoc method
  2216. * @name angular.Module#filter
  2217. * @module ng
  2218. * @param {string} name Filter name - this must be a valid AngularJS expression identifier
  2219. * @param {Function} filterFactory Factory function for creating new instance of filter.
  2220. * @description
  2221. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  2222. *
  2223. * <div class="alert alert-warning">
  2224. * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.
  2225. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  2226. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  2227. * (`myapp_subsection_filterx`).
  2228. * </div>
  2229. */
  2230. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  2231. /**
  2232. * @ngdoc method
  2233. * @name angular.Module#controller
  2234. * @module ng
  2235. * @param {string|Object} name Controller name, or an object map of controllers where the
  2236. * keys are the names and the values are the constructors.
  2237. * @param {Function} constructor Controller constructor function.
  2238. * @description
  2239. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2240. */
  2241. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2242. /**
  2243. * @ngdoc method
  2244. * @name angular.Module#directive
  2245. * @module ng
  2246. * @param {string|Object} name Directive name, or an object map of directives where the
  2247. * keys are the names and the values are the factories.
  2248. * @param {Function} directiveFactory Factory function for creating new instance of
  2249. * directives.
  2250. * @description
  2251. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2252. */
  2253. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2254. /**
  2255. * @ngdoc method
  2256. * @name angular.Module#component
  2257. * @module ng
  2258. * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`),
  2259. * or an object map of components where the keys are the names and the values are the component definition objects.
  2260. * @param {Object} options Component definition object (a simplified
  2261. * {@link ng.$compile#directive-definition-object directive definition object})
  2262. *
  2263. * @description
  2264. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2265. */
  2266. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2267. /**
  2268. * @ngdoc method
  2269. * @name angular.Module#config
  2270. * @module ng
  2271. * @param {Function} configFn Execute this function on module load. Useful for service
  2272. * configuration.
  2273. * @description
  2274. * Use this method to configure services by injecting their
  2275. * {@link angular.Module#provider `providers`}, e.g. for adding routes to the
  2276. * {@link ngRoute.$routeProvider $routeProvider}.
  2277. *
  2278. * Note that you can only inject {@link angular.Module#provider `providers`} and
  2279. * {@link angular.Module#constant `constants`} into this function.
  2280. *
  2281. * For more about how to configure services, see
  2282. * {@link providers#provider-recipe Provider Recipe}.
  2283. */
  2284. config: config,
  2285. /**
  2286. * @ngdoc method
  2287. * @name angular.Module#run
  2288. * @module ng
  2289. * @param {Function} initializationFn Execute this function after injector creation.
  2290. * Useful for application initialization.
  2291. * @description
  2292. * Use this method to register work which should be performed when the injector is done
  2293. * loading all modules.
  2294. */
  2295. run: function(block) {
  2296. runBlocks.push(block);
  2297. return this;
  2298. }
  2299. };
  2300. if (configFn) {
  2301. config(configFn);
  2302. }
  2303. return moduleInstance;
  2304. /**
  2305. * @param {string} provider
  2306. * @param {string} method
  2307. * @param {String=} insertMethod
  2308. * @returns {angular.Module}
  2309. */
  2310. function invokeLater(provider, method, insertMethod, queue) {
  2311. if (!queue) queue = invokeQueue;
  2312. return function() {
  2313. queue[insertMethod || 'push']([provider, method, arguments]);
  2314. return moduleInstance;
  2315. };
  2316. }
  2317. /**
  2318. * @param {string} provider
  2319. * @param {string} method
  2320. * @returns {angular.Module}
  2321. */
  2322. function invokeLaterAndSetModuleName(provider, method, queue) {
  2323. if (!queue) queue = invokeQueue;
  2324. return function(recipeName, factoryFunction) {
  2325. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2326. queue.push([provider, method, arguments]);
  2327. return moduleInstance;
  2328. };
  2329. }
  2330. });
  2331. };
  2332. });
  2333. }
  2334. /* global shallowCopy: true */
  2335. /**
  2336. * Creates a shallow copy of an object, an array or a primitive.
  2337. *
  2338. * Assumes that there are no proto properties for objects.
  2339. */
  2340. function shallowCopy(src, dst) {
  2341. if (isArray(src)) {
  2342. dst = dst || [];
  2343. for (var i = 0, ii = src.length; i < ii; i++) {
  2344. dst[i] = src[i];
  2345. }
  2346. } else if (isObject(src)) {
  2347. dst = dst || {};
  2348. for (var key in src) {
  2349. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2350. dst[key] = src[key];
  2351. }
  2352. }
  2353. }
  2354. return dst || src;
  2355. }
  2356. /* exported toDebugString */
  2357. function serializeObject(obj, maxDepth) {
  2358. var seen = [];
  2359. // There is no direct way to stringify object until reaching a specific depth
  2360. // and a very deep object can cause a performance issue, so we copy the object
  2361. // based on this specific depth and then stringify it.
  2362. if (isValidObjectMaxDepth(maxDepth)) {
  2363. // This file is also included in `angular-loader`, so `copy()` might not always be available in
  2364. // the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed.
  2365. obj = angular.copy(obj, null, maxDepth);
  2366. }
  2367. return JSON.stringify(obj, function(key, val) {
  2368. val = toJsonReplacer(key, val);
  2369. if (isObject(val)) {
  2370. if (seen.indexOf(val) >= 0) return '...';
  2371. seen.push(val);
  2372. }
  2373. return val;
  2374. });
  2375. }
  2376. function toDebugString(obj, maxDepth) {
  2377. if (typeof obj === 'function') {
  2378. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2379. } else if (isUndefined(obj)) {
  2380. return 'undefined';
  2381. } else if (typeof obj !== 'string') {
  2382. return serializeObject(obj, maxDepth);
  2383. }
  2384. return obj;
  2385. }
  2386. /* global angularModule: true,
  2387. version: true,
  2388. $CompileProvider,
  2389. htmlAnchorDirective,
  2390. inputDirective,
  2391. inputDirective,
  2392. formDirective,
  2393. scriptDirective,
  2394. selectDirective,
  2395. optionDirective,
  2396. ngBindDirective,
  2397. ngBindHtmlDirective,
  2398. ngBindTemplateDirective,
  2399. ngClassDirective,
  2400. ngClassEvenDirective,
  2401. ngClassOddDirective,
  2402. ngCloakDirective,
  2403. ngControllerDirective,
  2404. ngFormDirective,
  2405. ngHideDirective,
  2406. ngIfDirective,
  2407. ngIncludeDirective,
  2408. ngIncludeFillContentDirective,
  2409. ngInitDirective,
  2410. ngNonBindableDirective,
  2411. ngPluralizeDirective,
  2412. ngRefDirective,
  2413. ngRepeatDirective,
  2414. ngShowDirective,
  2415. ngStyleDirective,
  2416. ngSwitchDirective,
  2417. ngSwitchWhenDirective,
  2418. ngSwitchDefaultDirective,
  2419. ngOptionsDirective,
  2420. ngTranscludeDirective,
  2421. ngModelDirective,
  2422. ngListDirective,
  2423. ngChangeDirective,
  2424. patternDirective,
  2425. patternDirective,
  2426. requiredDirective,
  2427. requiredDirective,
  2428. minlengthDirective,
  2429. minlengthDirective,
  2430. maxlengthDirective,
  2431. maxlengthDirective,
  2432. ngValueDirective,
  2433. ngModelOptionsDirective,
  2434. ngAttributeAliasDirectives,
  2435. ngEventDirectives,
  2436. $AnchorScrollProvider,
  2437. $AnimateProvider,
  2438. $CoreAnimateCssProvider,
  2439. $$CoreAnimateJsProvider,
  2440. $$CoreAnimateQueueProvider,
  2441. $$AnimateRunnerFactoryProvider,
  2442. $$AnimateAsyncRunFactoryProvider,
  2443. $BrowserProvider,
  2444. $CacheFactoryProvider,
  2445. $ControllerProvider,
  2446. $DateProvider,
  2447. $DocumentProvider,
  2448. $$IsDocumentHiddenProvider,
  2449. $ExceptionHandlerProvider,
  2450. $FilterProvider,
  2451. $$ForceReflowProvider,
  2452. $InterpolateProvider,
  2453. $$IntervalFactoryProvider,
  2454. $IntervalProvider,
  2455. $HttpProvider,
  2456. $HttpParamSerializerProvider,
  2457. $HttpParamSerializerJQLikeProvider,
  2458. $HttpBackendProvider,
  2459. $xhrFactoryProvider,
  2460. $jsonpCallbacksProvider,
  2461. $LocationProvider,
  2462. $LogProvider,
  2463. $$MapProvider,
  2464. $ParseProvider,
  2465. $RootScopeProvider,
  2466. $QProvider,
  2467. $$QProvider,
  2468. $$SanitizeUriProvider,
  2469. $SceProvider,
  2470. $SceDelegateProvider,
  2471. $SnifferProvider,
  2472. $$TaskTrackerFactoryProvider,
  2473. $TemplateCacheProvider,
  2474. $TemplateRequestProvider,
  2475. $$TestabilityProvider,
  2476. $TimeoutProvider,
  2477. $$RAFProvider,
  2478. $WindowProvider,
  2479. $$jqLiteProvider,
  2480. $$CookieReaderProvider
  2481. */
  2482. /**
  2483. * @ngdoc object
  2484. * @name angular.version
  2485. * @module ng
  2486. * @description
  2487. * An object that contains information about the current AngularJS version.
  2488. *
  2489. * This object has the following properties:
  2490. *
  2491. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2492. * - `major` – `{number}` – Major version number, such as "0".
  2493. * - `minor` – `{number}` – Minor version number, such as "9".
  2494. * - `dot` – `{number}` – Dot version number, such as "18".
  2495. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2496. */
  2497. var version = {
  2498. // These placeholder strings will be replaced by grunt's `build` task.
  2499. // They need to be double- or single-quoted.
  2500. full: '1.7.5',
  2501. major: 1,
  2502. minor: 7,
  2503. dot: 5,
  2504. codeName: 'anti-prettification'
  2505. };
  2506. function publishExternalAPI(angular) {
  2507. extend(angular, {
  2508. 'errorHandlingConfig': errorHandlingConfig,
  2509. 'bootstrap': bootstrap,
  2510. 'copy': copy,
  2511. 'extend': extend,
  2512. 'merge': merge,
  2513. 'equals': equals,
  2514. 'element': jqLite,
  2515. 'forEach': forEach,
  2516. 'injector': createInjector,
  2517. 'noop': noop,
  2518. 'bind': bind,
  2519. 'toJson': toJson,
  2520. 'fromJson': fromJson,
  2521. 'identity': identity,
  2522. 'isUndefined': isUndefined,
  2523. 'isDefined': isDefined,
  2524. 'isString': isString,
  2525. 'isFunction': isFunction,
  2526. 'isObject': isObject,
  2527. 'isNumber': isNumber,
  2528. 'isElement': isElement,
  2529. 'isArray': isArray,
  2530. 'version': version,
  2531. 'isDate': isDate,
  2532. 'callbacks': {$$counter: 0},
  2533. 'getTestability': getTestability,
  2534. 'reloadWithDebugInfo': reloadWithDebugInfo,
  2535. '$$minErr': minErr,
  2536. '$$csp': csp,
  2537. '$$encodeUriSegment': encodeUriSegment,
  2538. '$$encodeUriQuery': encodeUriQuery,
  2539. '$$lowercase': lowercase,
  2540. '$$stringify': stringify,
  2541. '$$uppercase': uppercase
  2542. });
  2543. angularModule = setupModuleLoader(window);
  2544. angularModule('ng', ['ngLocale'], ['$provide',
  2545. function ngModule($provide) {
  2546. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2547. $provide.provider({
  2548. $$sanitizeUri: $$SanitizeUriProvider
  2549. });
  2550. $provide.provider('$compile', $CompileProvider).
  2551. directive({
  2552. a: htmlAnchorDirective,
  2553. input: inputDirective,
  2554. textarea: inputDirective,
  2555. form: formDirective,
  2556. script: scriptDirective,
  2557. select: selectDirective,
  2558. option: optionDirective,
  2559. ngBind: ngBindDirective,
  2560. ngBindHtml: ngBindHtmlDirective,
  2561. ngBindTemplate: ngBindTemplateDirective,
  2562. ngClass: ngClassDirective,
  2563. ngClassEven: ngClassEvenDirective,
  2564. ngClassOdd: ngClassOddDirective,
  2565. ngCloak: ngCloakDirective,
  2566. ngController: ngControllerDirective,
  2567. ngForm: ngFormDirective,
  2568. ngHide: ngHideDirective,
  2569. ngIf: ngIfDirective,
  2570. ngInclude: ngIncludeDirective,
  2571. ngInit: ngInitDirective,
  2572. ngNonBindable: ngNonBindableDirective,
  2573. ngPluralize: ngPluralizeDirective,
  2574. ngRef: ngRefDirective,
  2575. ngRepeat: ngRepeatDirective,
  2576. ngShow: ngShowDirective,
  2577. ngStyle: ngStyleDirective,
  2578. ngSwitch: ngSwitchDirective,
  2579. ngSwitchWhen: ngSwitchWhenDirective,
  2580. ngSwitchDefault: ngSwitchDefaultDirective,
  2581. ngOptions: ngOptionsDirective,
  2582. ngTransclude: ngTranscludeDirective,
  2583. ngModel: ngModelDirective,
  2584. ngList: ngListDirective,
  2585. ngChange: ngChangeDirective,
  2586. pattern: patternDirective,
  2587. ngPattern: patternDirective,
  2588. required: requiredDirective,
  2589. ngRequired: requiredDirective,
  2590. minlength: minlengthDirective,
  2591. ngMinlength: minlengthDirective,
  2592. maxlength: maxlengthDirective,
  2593. ngMaxlength: maxlengthDirective,
  2594. ngValue: ngValueDirective,
  2595. ngModelOptions: ngModelOptionsDirective
  2596. }).
  2597. directive({
  2598. ngInclude: ngIncludeFillContentDirective
  2599. }).
  2600. directive(ngAttributeAliasDirectives).
  2601. directive(ngEventDirectives);
  2602. $provide.provider({
  2603. $anchorScroll: $AnchorScrollProvider,
  2604. $animate: $AnimateProvider,
  2605. $animateCss: $CoreAnimateCssProvider,
  2606. $$animateJs: $$CoreAnimateJsProvider,
  2607. $$animateQueue: $$CoreAnimateQueueProvider,
  2608. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2609. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2610. $browser: $BrowserProvider,
  2611. $cacheFactory: $CacheFactoryProvider,
  2612. $controller: $ControllerProvider,
  2613. $document: $DocumentProvider,
  2614. $$isDocumentHidden: $$IsDocumentHiddenProvider,
  2615. $exceptionHandler: $ExceptionHandlerProvider,
  2616. $filter: $FilterProvider,
  2617. $$forceReflow: $$ForceReflowProvider,
  2618. $interpolate: $InterpolateProvider,
  2619. $interval: $IntervalProvider,
  2620. $$intervalFactory: $$IntervalFactoryProvider,
  2621. $http: $HttpProvider,
  2622. $httpParamSerializer: $HttpParamSerializerProvider,
  2623. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2624. $httpBackend: $HttpBackendProvider,
  2625. $xhrFactory: $xhrFactoryProvider,
  2626. $jsonpCallbacks: $jsonpCallbacksProvider,
  2627. $location: $LocationProvider,
  2628. $log: $LogProvider,
  2629. $parse: $ParseProvider,
  2630. $rootScope: $RootScopeProvider,
  2631. $q: $QProvider,
  2632. $$q: $$QProvider,
  2633. $sce: $SceProvider,
  2634. $sceDelegate: $SceDelegateProvider,
  2635. $sniffer: $SnifferProvider,
  2636. $$taskTrackerFactory: $$TaskTrackerFactoryProvider,
  2637. $templateCache: $TemplateCacheProvider,
  2638. $templateRequest: $TemplateRequestProvider,
  2639. $$testability: $$TestabilityProvider,
  2640. $timeout: $TimeoutProvider,
  2641. $window: $WindowProvider,
  2642. $$rAF: $$RAFProvider,
  2643. $$jqLite: $$jqLiteProvider,
  2644. $$Map: $$MapProvider,
  2645. $$cookieReader: $$CookieReaderProvider
  2646. });
  2647. }
  2648. ])
  2649. .info({ angularVersion: '1.7.5' });
  2650. }
  2651. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2652. * Any commits to this file should be reviewed with security in mind. *
  2653. * Changes to this file can potentially create security vulnerabilities. *
  2654. * An approval from 2 Core members with history of modifying *
  2655. * this file is required. *
  2656. * *
  2657. * Does the change somehow allow for arbitrary javascript to be executed? *
  2658. * Or allows for someone to change the prototype of built-in objects? *
  2659. * Or gives undesired access to variables likes document or window? *
  2660. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2661. /* global
  2662. JQLitePrototype: true,
  2663. BOOLEAN_ATTR: true,
  2664. ALIASED_ATTR: true
  2665. */
  2666. //////////////////////////////////
  2667. //JQLite
  2668. //////////////////////////////////
  2669. /**
  2670. * @ngdoc function
  2671. * @name angular.element
  2672. * @module ng
  2673. * @kind function
  2674. *
  2675. * @description
  2676. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2677. *
  2678. * If jQuery is available, `angular.element` is an alias for the
  2679. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2680. * delegates to AngularJS's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2681. *
  2682. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2683. * AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2684. * commonly needed functionality with the goal of having a very small footprint.
  2685. *
  2686. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2687. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2688. * specific version of jQuery if multiple versions exist on the page.
  2689. *
  2690. * <div class="alert alert-info">**Note:** All element references in AngularJS are always wrapped with jQuery or
  2691. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2692. *
  2693. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2694. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2695. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2696. *
  2697. * ## AngularJS's jqLite
  2698. * jqLite provides only the following jQuery methods:
  2699. *
  2700. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2701. * - [`after()`](http://api.jquery.com/after/)
  2702. * - [`append()`](http://api.jquery.com/append/) - Contrary to jQuery, this doesn't clone elements
  2703. * so will not work correctly when invoked on a jqLite object containing more than one DOM node
  2704. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2705. * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
  2706. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2707. * - [`clone()`](http://api.jquery.com/clone/)
  2708. * - [`contents()`](http://api.jquery.com/contents/)
  2709. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2710. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2711. * - [`data()`](http://api.jquery.com/data/)
  2712. * - [`detach()`](http://api.jquery.com/detach/)
  2713. * - [`empty()`](http://api.jquery.com/empty/)
  2714. * - [`eq()`](http://api.jquery.com/eq/)
  2715. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2716. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2717. * - [`html()`](http://api.jquery.com/html/)
  2718. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2719. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2720. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2721. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2722. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2723. * - [`prepend()`](http://api.jquery.com/prepend/)
  2724. * - [`prop()`](http://api.jquery.com/prop/)
  2725. * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
  2726. * - [`remove()`](http://api.jquery.com/remove/)
  2727. * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
  2728. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2729. * - [`removeData()`](http://api.jquery.com/removeData/)
  2730. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2731. * - [`text()`](http://api.jquery.com/text/)
  2732. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2733. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2734. * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
  2735. * - [`val()`](http://api.jquery.com/val/)
  2736. * - [`wrap()`](http://api.jquery.com/wrap/)
  2737. *
  2738. * ## jQuery/jqLite Extras
  2739. * AngularJS also provides the following additional methods and events to both jQuery and jqLite:
  2740. *
  2741. * ### Events
  2742. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2743. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2744. * element before it is removed.
  2745. *
  2746. * ### Methods
  2747. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2748. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2749. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2750. * `'ngModel'`).
  2751. * - `injector()` - retrieves the injector of the current element or its parent.
  2752. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2753. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2754. * be enabled.
  2755. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2756. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2757. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2758. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2759. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2760. * parent element is reached.
  2761. *
  2762. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2763. * https://github.com/angular/angular.js/issues/14251 for more information.
  2764. *
  2765. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2766. * @returns {Object} jQuery object.
  2767. */
  2768. JQLite.expando = 'ng339';
  2769. var jqCache = JQLite.cache = {},
  2770. jqId = 1;
  2771. /*
  2772. * !!! This is an undocumented "private" function !!!
  2773. */
  2774. JQLite._data = function(node) {
  2775. //jQuery always returns an object on cache miss
  2776. return this.cache[node[this.expando]] || {};
  2777. };
  2778. function jqNextId() { return ++jqId; }
  2779. var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
  2780. var MS_HACK_REGEXP = /^-ms-/;
  2781. var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
  2782. var jqLiteMinErr = minErr('jqLite');
  2783. /**
  2784. * Converts kebab-case to camelCase.
  2785. * There is also a special case for the ms prefix starting with a lowercase letter.
  2786. * @param name Name to normalize
  2787. */
  2788. function cssKebabToCamel(name) {
  2789. return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
  2790. }
  2791. function fnCamelCaseReplace(all, letter) {
  2792. return letter.toUpperCase();
  2793. }
  2794. /**
  2795. * Converts kebab-case to camelCase.
  2796. * @param name Name to normalize
  2797. */
  2798. function kebabToCamel(name) {
  2799. return name
  2800. .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
  2801. }
  2802. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2803. var HTML_REGEXP = /<|&#?\w+;/;
  2804. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2805. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2806. var wrapMap = {
  2807. 'option': [1, '<select multiple="multiple">', '</select>'],
  2808. 'thead': [1, '<table>', '</table>'],
  2809. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2810. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2811. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2812. '_default': [0, '', '']
  2813. };
  2814. wrapMap.optgroup = wrapMap.option;
  2815. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2816. wrapMap.th = wrapMap.td;
  2817. function jqLiteIsTextNode(html) {
  2818. return !HTML_REGEXP.test(html);
  2819. }
  2820. function jqLiteAcceptsData(node) {
  2821. // The window object can accept data but has no nodeType
  2822. // Otherwise we are only interested in elements (1) and documents (9)
  2823. var nodeType = node.nodeType;
  2824. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2825. }
  2826. function jqLiteHasData(node) {
  2827. for (var key in jqCache[node.ng339]) {
  2828. return true;
  2829. }
  2830. return false;
  2831. }
  2832. function jqLiteBuildFragment(html, context) {
  2833. var tmp, tag, wrap,
  2834. fragment = context.createDocumentFragment(),
  2835. nodes = [], i;
  2836. if (jqLiteIsTextNode(html)) {
  2837. // Convert non-html into a text node
  2838. nodes.push(context.createTextNode(html));
  2839. } else {
  2840. // Convert html into DOM nodes
  2841. tmp = fragment.appendChild(context.createElement('div'));
  2842. tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
  2843. wrap = wrapMap[tag] || wrapMap._default;
  2844. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
  2845. // Descend through wrappers to the right content
  2846. i = wrap[0];
  2847. while (i--) {
  2848. tmp = tmp.lastChild;
  2849. }
  2850. nodes = concat(nodes, tmp.childNodes);
  2851. tmp = fragment.firstChild;
  2852. tmp.textContent = '';
  2853. }
  2854. // Remove wrapper from fragment
  2855. fragment.textContent = '';
  2856. fragment.innerHTML = ''; // Clear inner HTML
  2857. forEach(nodes, function(node) {
  2858. fragment.appendChild(node);
  2859. });
  2860. return fragment;
  2861. }
  2862. function jqLiteParseHTML(html, context) {
  2863. context = context || window.document;
  2864. var parsed;
  2865. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2866. return [context.createElement(parsed[1])];
  2867. }
  2868. if ((parsed = jqLiteBuildFragment(html, context))) {
  2869. return parsed.childNodes;
  2870. }
  2871. return [];
  2872. }
  2873. function jqLiteWrapNode(node, wrapper) {
  2874. var parent = node.parentNode;
  2875. if (parent) {
  2876. parent.replaceChild(wrapper, node);
  2877. }
  2878. wrapper.appendChild(node);
  2879. }
  2880. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2881. var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
  2882. // eslint-disable-next-line no-bitwise
  2883. return !!(this.compareDocumentPosition(arg) & 16);
  2884. };
  2885. /////////////////////////////////////////////
  2886. function JQLite(element) {
  2887. if (element instanceof JQLite) {
  2888. return element;
  2889. }
  2890. var argIsString;
  2891. if (isString(element)) {
  2892. element = trim(element);
  2893. argIsString = true;
  2894. }
  2895. if (!(this instanceof JQLite)) {
  2896. if (argIsString && element.charAt(0) !== '<') {
  2897. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2898. }
  2899. return new JQLite(element);
  2900. }
  2901. if (argIsString) {
  2902. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2903. } else if (isFunction(element)) {
  2904. jqLiteReady(element);
  2905. } else {
  2906. jqLiteAddNodes(this, element);
  2907. }
  2908. }
  2909. function jqLiteClone(element) {
  2910. return element.cloneNode(true);
  2911. }
  2912. function jqLiteDealoc(element, onlyDescendants) {
  2913. if (!onlyDescendants && jqLiteAcceptsData(element)) jqLite.cleanData([element]);
  2914. if (element.querySelectorAll) {
  2915. jqLite.cleanData(element.querySelectorAll('*'));
  2916. }
  2917. }
  2918. function isEmptyObject(obj) {
  2919. var name;
  2920. for (name in obj) {
  2921. return false;
  2922. }
  2923. return true;
  2924. }
  2925. function removeIfEmptyData(element) {
  2926. var expandoId = element.ng339;
  2927. var expandoStore = expandoId && jqCache[expandoId];
  2928. var events = expandoStore && expandoStore.events;
  2929. var data = expandoStore && expandoStore.data;
  2930. if ((!data || isEmptyObject(data)) && (!events || isEmptyObject(events))) {
  2931. delete jqCache[expandoId];
  2932. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2933. }
  2934. }
  2935. function jqLiteOff(element, type, fn, unsupported) {
  2936. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2937. var expandoStore = jqLiteExpandoStore(element);
  2938. var events = expandoStore && expandoStore.events;
  2939. var handle = expandoStore && expandoStore.handle;
  2940. if (!handle) return; //no listeners registered
  2941. if (!type) {
  2942. for (type in events) {
  2943. if (type !== '$destroy') {
  2944. element.removeEventListener(type, handle);
  2945. }
  2946. delete events[type];
  2947. }
  2948. } else {
  2949. var removeHandler = function(type) {
  2950. var listenerFns = events[type];
  2951. if (isDefined(fn)) {
  2952. arrayRemove(listenerFns || [], fn);
  2953. }
  2954. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2955. element.removeEventListener(type, handle);
  2956. delete events[type];
  2957. }
  2958. };
  2959. forEach(type.split(' '), function(type) {
  2960. removeHandler(type);
  2961. if (MOUSE_EVENT_MAP[type]) {
  2962. removeHandler(MOUSE_EVENT_MAP[type]);
  2963. }
  2964. });
  2965. }
  2966. removeIfEmptyData(element);
  2967. }
  2968. function jqLiteRemoveData(element, name) {
  2969. var expandoId = element.ng339;
  2970. var expandoStore = expandoId && jqCache[expandoId];
  2971. if (expandoStore) {
  2972. if (name) {
  2973. delete expandoStore.data[name];
  2974. } else {
  2975. expandoStore.data = {};
  2976. }
  2977. removeIfEmptyData(element);
  2978. }
  2979. }
  2980. function jqLiteExpandoStore(element, createIfNecessary) {
  2981. var expandoId = element.ng339,
  2982. expandoStore = expandoId && jqCache[expandoId];
  2983. if (createIfNecessary && !expandoStore) {
  2984. element.ng339 = expandoId = jqNextId();
  2985. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2986. }
  2987. return expandoStore;
  2988. }
  2989. function jqLiteData(element, key, value) {
  2990. if (jqLiteAcceptsData(element)) {
  2991. var prop;
  2992. var isSimpleSetter = isDefined(value);
  2993. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2994. var massGetter = !key;
  2995. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2996. var data = expandoStore && expandoStore.data;
  2997. if (isSimpleSetter) { // data('key', value)
  2998. data[kebabToCamel(key)] = value;
  2999. } else {
  3000. if (massGetter) { // data()
  3001. return data;
  3002. } else {
  3003. if (isSimpleGetter) { // data('key')
  3004. // don't force creation of expandoStore if it doesn't exist yet
  3005. return data && data[kebabToCamel(key)];
  3006. } else { // mass-setter: data({key1: val1, key2: val2})
  3007. for (prop in key) {
  3008. data[kebabToCamel(prop)] = key[prop];
  3009. }
  3010. }
  3011. }
  3012. }
  3013. }
  3014. }
  3015. function jqLiteHasClass(element, selector) {
  3016. if (!element.getAttribute) return false;
  3017. return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
  3018. indexOf(' ' + selector + ' ') > -1);
  3019. }
  3020. function jqLiteRemoveClass(element, cssClasses) {
  3021. if (cssClasses && element.setAttribute) {
  3022. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  3023. .replace(/[\n\t]/g, ' ');
  3024. var newClasses = existingClasses;
  3025. forEach(cssClasses.split(' '), function(cssClass) {
  3026. cssClass = trim(cssClass);
  3027. newClasses = newClasses.replace(' ' + cssClass + ' ', ' ');
  3028. });
  3029. if (newClasses !== existingClasses) {
  3030. element.setAttribute('class', trim(newClasses));
  3031. }
  3032. }
  3033. }
  3034. function jqLiteAddClass(element, cssClasses) {
  3035. if (cssClasses && element.setAttribute) {
  3036. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  3037. .replace(/[\n\t]/g, ' ');
  3038. var newClasses = existingClasses;
  3039. forEach(cssClasses.split(' '), function(cssClass) {
  3040. cssClass = trim(cssClass);
  3041. if (newClasses.indexOf(' ' + cssClass + ' ') === -1) {
  3042. newClasses += cssClass + ' ';
  3043. }
  3044. });
  3045. if (newClasses !== existingClasses) {
  3046. element.setAttribute('class', trim(newClasses));
  3047. }
  3048. }
  3049. }
  3050. function jqLiteAddNodes(root, elements) {
  3051. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  3052. if (elements) {
  3053. // if a Node (the most common case)
  3054. if (elements.nodeType) {
  3055. root[root.length++] = elements;
  3056. } else {
  3057. var length = elements.length;
  3058. // if an Array or NodeList and not a Window
  3059. if (typeof length === 'number' && elements.window !== elements) {
  3060. if (length) {
  3061. for (var i = 0; i < length; i++) {
  3062. root[root.length++] = elements[i];
  3063. }
  3064. }
  3065. } else {
  3066. root[root.length++] = elements;
  3067. }
  3068. }
  3069. }
  3070. }
  3071. function jqLiteController(element, name) {
  3072. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  3073. }
  3074. function jqLiteInheritedData(element, name, value) {
  3075. // if element is the document object work with the html element instead
  3076. // this makes $(document).scope() possible
  3077. if (element.nodeType === NODE_TYPE_DOCUMENT) {
  3078. element = element.documentElement;
  3079. }
  3080. var names = isArray(name) ? name : [name];
  3081. while (element) {
  3082. for (var i = 0, ii = names.length; i < ii; i++) {
  3083. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  3084. }
  3085. // If dealing with a document fragment node with a host element, and no parent, use the host
  3086. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  3087. // to lookup parent controllers.
  3088. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  3089. }
  3090. }
  3091. function jqLiteEmpty(element) {
  3092. jqLiteDealoc(element, true);
  3093. while (element.firstChild) {
  3094. element.removeChild(element.firstChild);
  3095. }
  3096. }
  3097. function jqLiteRemove(element, keepData) {
  3098. if (!keepData) jqLiteDealoc(element);
  3099. var parent = element.parentNode;
  3100. if (parent) parent.removeChild(element);
  3101. }
  3102. function jqLiteDocumentLoaded(action, win) {
  3103. win = win || window;
  3104. if (win.document.readyState === 'complete') {
  3105. // Force the action to be run async for consistent behavior
  3106. // from the action's point of view
  3107. // i.e. it will definitely not be in a $apply
  3108. win.setTimeout(action);
  3109. } else {
  3110. // No need to unbind this handler as load is only ever called once
  3111. jqLite(win).on('load', action);
  3112. }
  3113. }
  3114. function jqLiteReady(fn) {
  3115. function trigger() {
  3116. window.document.removeEventListener('DOMContentLoaded', trigger);
  3117. window.removeEventListener('load', trigger);
  3118. fn();
  3119. }
  3120. // check if document is already loaded
  3121. if (window.document.readyState === 'complete') {
  3122. window.setTimeout(fn);
  3123. } else {
  3124. // We can not use jqLite since we are not done loading and jQuery could be loaded later.
  3125. // Works for modern browsers and IE9
  3126. window.document.addEventListener('DOMContentLoaded', trigger);
  3127. // Fallback to window.onload for others
  3128. window.addEventListener('load', trigger);
  3129. }
  3130. }
  3131. //////////////////////////////////////////
  3132. // Functions which are declared directly.
  3133. //////////////////////////////////////////
  3134. var JQLitePrototype = JQLite.prototype = {
  3135. ready: jqLiteReady,
  3136. toString: function() {
  3137. var value = [];
  3138. forEach(this, function(e) { value.push('' + e);});
  3139. return '[' + value.join(', ') + ']';
  3140. },
  3141. eq: function(index) {
  3142. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  3143. },
  3144. length: 0,
  3145. push: push,
  3146. sort: [].sort,
  3147. splice: [].splice
  3148. };
  3149. //////////////////////////////////////////
  3150. // Functions iterating getter/setters.
  3151. // these functions return self on setter and
  3152. // value on get.
  3153. //////////////////////////////////////////
  3154. var BOOLEAN_ATTR = {};
  3155. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  3156. BOOLEAN_ATTR[lowercase(value)] = value;
  3157. });
  3158. var BOOLEAN_ELEMENTS = {};
  3159. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  3160. BOOLEAN_ELEMENTS[value] = true;
  3161. });
  3162. var ALIASED_ATTR = {
  3163. 'ngMinlength': 'minlength',
  3164. 'ngMaxlength': 'maxlength',
  3165. 'ngMin': 'min',
  3166. 'ngMax': 'max',
  3167. 'ngPattern': 'pattern',
  3168. 'ngStep': 'step'
  3169. };
  3170. function getBooleanAttrName(element, name) {
  3171. // check dom last since we will most likely fail on name
  3172. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  3173. // booleanAttr is here twice to minimize DOM access
  3174. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  3175. }
  3176. function getAliasedAttrName(name) {
  3177. return ALIASED_ATTR[name];
  3178. }
  3179. forEach({
  3180. data: jqLiteData,
  3181. removeData: jqLiteRemoveData,
  3182. hasData: jqLiteHasData,
  3183. cleanData: function jqLiteCleanData(nodes) {
  3184. for (var i = 0, ii = nodes.length; i < ii; i++) {
  3185. jqLiteRemoveData(nodes[i]);
  3186. jqLiteOff(nodes[i]);
  3187. }
  3188. }
  3189. }, function(fn, name) {
  3190. JQLite[name] = fn;
  3191. });
  3192. forEach({
  3193. data: jqLiteData,
  3194. inheritedData: jqLiteInheritedData,
  3195. scope: function(element) {
  3196. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3197. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  3198. },
  3199. isolateScope: function(element) {
  3200. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3201. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  3202. },
  3203. controller: jqLiteController,
  3204. injector: function(element) {
  3205. return jqLiteInheritedData(element, '$injector');
  3206. },
  3207. removeAttr: function(element, name) {
  3208. element.removeAttribute(name);
  3209. },
  3210. hasClass: jqLiteHasClass,
  3211. css: function(element, name, value) {
  3212. name = cssKebabToCamel(name);
  3213. if (isDefined(value)) {
  3214. element.style[name] = value;
  3215. } else {
  3216. return element.style[name];
  3217. }
  3218. },
  3219. attr: function(element, name, value) {
  3220. var ret;
  3221. var nodeType = element.nodeType;
  3222. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
  3223. !element.getAttribute) {
  3224. return;
  3225. }
  3226. var lowercasedName = lowercase(name);
  3227. var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
  3228. if (isDefined(value)) {
  3229. // setter
  3230. if (value === null || (value === false && isBooleanAttr)) {
  3231. element.removeAttribute(name);
  3232. } else {
  3233. element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
  3234. }
  3235. } else {
  3236. // getter
  3237. ret = element.getAttribute(name);
  3238. if (isBooleanAttr && ret !== null) {
  3239. ret = lowercasedName;
  3240. }
  3241. // Normalize non-existing attributes to undefined (as jQuery).
  3242. return ret === null ? undefined : ret;
  3243. }
  3244. },
  3245. prop: function(element, name, value) {
  3246. if (isDefined(value)) {
  3247. element[name] = value;
  3248. } else {
  3249. return element[name];
  3250. }
  3251. },
  3252. text: (function() {
  3253. getText.$dv = '';
  3254. return getText;
  3255. function getText(element, value) {
  3256. if (isUndefined(value)) {
  3257. var nodeType = element.nodeType;
  3258. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  3259. }
  3260. element.textContent = value;
  3261. }
  3262. })(),
  3263. val: function(element, value) {
  3264. if (isUndefined(value)) {
  3265. if (element.multiple && nodeName_(element) === 'select') {
  3266. var result = [];
  3267. forEach(element.options, function(option) {
  3268. if (option.selected) {
  3269. result.push(option.value || option.text);
  3270. }
  3271. });
  3272. return result;
  3273. }
  3274. return element.value;
  3275. }
  3276. element.value = value;
  3277. },
  3278. html: function(element, value) {
  3279. if (isUndefined(value)) {
  3280. return element.innerHTML;
  3281. }
  3282. jqLiteDealoc(element, true);
  3283. element.innerHTML = value;
  3284. },
  3285. empty: jqLiteEmpty
  3286. }, function(fn, name) {
  3287. /**
  3288. * Properties: writes return selection, reads return first value
  3289. */
  3290. JQLite.prototype[name] = function(arg1, arg2) {
  3291. var i, key;
  3292. var nodeCount = this.length;
  3293. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3294. // in a way that survives minification.
  3295. // jqLiteEmpty takes no arguments but is a setter.
  3296. if (fn !== jqLiteEmpty &&
  3297. (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3298. if (isObject(arg1)) {
  3299. // we are a write, but the object properties are the key/values
  3300. for (i = 0; i < nodeCount; i++) {
  3301. if (fn === jqLiteData) {
  3302. // data() takes the whole object in jQuery
  3303. fn(this[i], arg1);
  3304. } else {
  3305. for (key in arg1) {
  3306. fn(this[i], key, arg1[key]);
  3307. }
  3308. }
  3309. }
  3310. // return self for chaining
  3311. return this;
  3312. } else {
  3313. // we are a read, so read the first child.
  3314. // TODO: do we still need this?
  3315. var value = fn.$dv;
  3316. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3317. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3318. for (var j = 0; j < jj; j++) {
  3319. var nodeValue = fn(this[j], arg1, arg2);
  3320. value = value ? value + nodeValue : nodeValue;
  3321. }
  3322. return value;
  3323. }
  3324. } else {
  3325. // we are a write, so apply to all children
  3326. for (i = 0; i < nodeCount; i++) {
  3327. fn(this[i], arg1, arg2);
  3328. }
  3329. // return self for chaining
  3330. return this;
  3331. }
  3332. };
  3333. });
  3334. function createEventHandler(element, events) {
  3335. var eventHandler = function(event, type) {
  3336. // jQuery specific api
  3337. event.isDefaultPrevented = function() {
  3338. return event.defaultPrevented;
  3339. };
  3340. var eventFns = events[type || event.type];
  3341. var eventFnsLength = eventFns ? eventFns.length : 0;
  3342. if (!eventFnsLength) return;
  3343. if (isUndefined(event.immediatePropagationStopped)) {
  3344. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3345. event.stopImmediatePropagation = function() {
  3346. event.immediatePropagationStopped = true;
  3347. if (event.stopPropagation) {
  3348. event.stopPropagation();
  3349. }
  3350. if (originalStopImmediatePropagation) {
  3351. originalStopImmediatePropagation.call(event);
  3352. }
  3353. };
  3354. }
  3355. event.isImmediatePropagationStopped = function() {
  3356. return event.immediatePropagationStopped === true;
  3357. };
  3358. // Some events have special handlers that wrap the real handler
  3359. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3360. // Copy event handlers in case event handlers array is modified during execution.
  3361. if ((eventFnsLength > 1)) {
  3362. eventFns = shallowCopy(eventFns);
  3363. }
  3364. for (var i = 0; i < eventFnsLength; i++) {
  3365. if (!event.isImmediatePropagationStopped()) {
  3366. handlerWrapper(element, event, eventFns[i]);
  3367. }
  3368. }
  3369. };
  3370. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3371. // events on `element`
  3372. eventHandler.elem = element;
  3373. return eventHandler;
  3374. }
  3375. function defaultHandlerWrapper(element, event, handler) {
  3376. handler.call(element, event);
  3377. }
  3378. function specialMouseHandlerWrapper(target, event, handler) {
  3379. // Refer to jQuery's implementation of mouseenter & mouseleave
  3380. // Read about mouseenter and mouseleave:
  3381. // http://www.quirksmode.org/js/events_mouse.html#link8
  3382. var related = event.relatedTarget;
  3383. // For mousenter/leave call the handler if related is outside the target.
  3384. // NB: No relatedTarget if the mouse left/entered the browser window
  3385. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3386. handler.call(target, event);
  3387. }
  3388. }
  3389. //////////////////////////////////////////
  3390. // Functions iterating traversal.
  3391. // These functions chain results into a single
  3392. // selector.
  3393. //////////////////////////////////////////
  3394. forEach({
  3395. removeData: jqLiteRemoveData,
  3396. on: function jqLiteOn(element, type, fn, unsupported) {
  3397. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3398. // Do not add event handlers to non-elements because they will not be cleaned up.
  3399. if (!jqLiteAcceptsData(element)) {
  3400. return;
  3401. }
  3402. var expandoStore = jqLiteExpandoStore(element, true);
  3403. var events = expandoStore.events;
  3404. var handle = expandoStore.handle;
  3405. if (!handle) {
  3406. handle = expandoStore.handle = createEventHandler(element, events);
  3407. }
  3408. // http://jsperf.com/string-indexof-vs-split
  3409. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3410. var i = types.length;
  3411. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3412. var eventFns = events[type];
  3413. if (!eventFns) {
  3414. eventFns = events[type] = [];
  3415. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3416. if (type !== '$destroy' && !noEventListener) {
  3417. element.addEventListener(type, handle);
  3418. }
  3419. }
  3420. eventFns.push(fn);
  3421. };
  3422. while (i--) {
  3423. type = types[i];
  3424. if (MOUSE_EVENT_MAP[type]) {
  3425. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3426. addHandler(type, undefined, true);
  3427. } else {
  3428. addHandler(type);
  3429. }
  3430. }
  3431. },
  3432. off: jqLiteOff,
  3433. one: function(element, type, fn) {
  3434. element = jqLite(element);
  3435. //add the listener twice so that when it is called
  3436. //you can remove the original function and still be
  3437. //able to call element.off(ev, fn) normally
  3438. element.on(type, function onFn() {
  3439. element.off(type, fn);
  3440. element.off(type, onFn);
  3441. });
  3442. element.on(type, fn);
  3443. },
  3444. replaceWith: function(element, replaceNode) {
  3445. var index, parent = element.parentNode;
  3446. jqLiteDealoc(element);
  3447. forEach(new JQLite(replaceNode), function(node) {
  3448. if (index) {
  3449. parent.insertBefore(node, index.nextSibling);
  3450. } else {
  3451. parent.replaceChild(node, element);
  3452. }
  3453. index = node;
  3454. });
  3455. },
  3456. children: function(element) {
  3457. var children = [];
  3458. forEach(element.childNodes, function(element) {
  3459. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3460. children.push(element);
  3461. }
  3462. });
  3463. return children;
  3464. },
  3465. contents: function(element) {
  3466. return element.contentDocument || element.childNodes || [];
  3467. },
  3468. append: function(element, node) {
  3469. var nodeType = element.nodeType;
  3470. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3471. node = new JQLite(node);
  3472. for (var i = 0, ii = node.length; i < ii; i++) {
  3473. var child = node[i];
  3474. element.appendChild(child);
  3475. }
  3476. },
  3477. prepend: function(element, node) {
  3478. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3479. var index = element.firstChild;
  3480. forEach(new JQLite(node), function(child) {
  3481. element.insertBefore(child, index);
  3482. });
  3483. }
  3484. },
  3485. wrap: function(element, wrapNode) {
  3486. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3487. },
  3488. remove: jqLiteRemove,
  3489. detach: function(element) {
  3490. jqLiteRemove(element, true);
  3491. },
  3492. after: function(element, newElement) {
  3493. var index = element, parent = element.parentNode;
  3494. if (parent) {
  3495. newElement = new JQLite(newElement);
  3496. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3497. var node = newElement[i];
  3498. parent.insertBefore(node, index.nextSibling);
  3499. index = node;
  3500. }
  3501. }
  3502. },
  3503. addClass: jqLiteAddClass,
  3504. removeClass: jqLiteRemoveClass,
  3505. toggleClass: function(element, selector, condition) {
  3506. if (selector) {
  3507. forEach(selector.split(' '), function(className) {
  3508. var classCondition = condition;
  3509. if (isUndefined(classCondition)) {
  3510. classCondition = !jqLiteHasClass(element, className);
  3511. }
  3512. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3513. });
  3514. }
  3515. },
  3516. parent: function(element) {
  3517. var parent = element.parentNode;
  3518. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3519. },
  3520. next: function(element) {
  3521. return element.nextElementSibling;
  3522. },
  3523. find: function(element, selector) {
  3524. if (element.getElementsByTagName) {
  3525. return element.getElementsByTagName(selector);
  3526. } else {
  3527. return [];
  3528. }
  3529. },
  3530. clone: jqLiteClone,
  3531. triggerHandler: function(element, event, extraParameters) {
  3532. var dummyEvent, eventFnsCopy, handlerArgs;
  3533. var eventName = event.type || event;
  3534. var expandoStore = jqLiteExpandoStore(element);
  3535. var events = expandoStore && expandoStore.events;
  3536. var eventFns = events && events[eventName];
  3537. if (eventFns) {
  3538. // Create a dummy event to pass to the handlers
  3539. dummyEvent = {
  3540. preventDefault: function() { this.defaultPrevented = true; },
  3541. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3542. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3543. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3544. stopPropagation: noop,
  3545. type: eventName,
  3546. target: element
  3547. };
  3548. // If a custom event was provided then extend our dummy event with it
  3549. if (event.type) {
  3550. dummyEvent = extend(dummyEvent, event);
  3551. }
  3552. // Copy event handlers in case event handlers array is modified during execution.
  3553. eventFnsCopy = shallowCopy(eventFns);
  3554. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3555. forEach(eventFnsCopy, function(fn) {
  3556. if (!dummyEvent.isImmediatePropagationStopped()) {
  3557. fn.apply(element, handlerArgs);
  3558. }
  3559. });
  3560. }
  3561. }
  3562. }, function(fn, name) {
  3563. /**
  3564. * chaining functions
  3565. */
  3566. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3567. var value;
  3568. for (var i = 0, ii = this.length; i < ii; i++) {
  3569. if (isUndefined(value)) {
  3570. value = fn(this[i], arg1, arg2, arg3);
  3571. if (isDefined(value)) {
  3572. // any function which returns a value needs to be wrapped
  3573. value = jqLite(value);
  3574. }
  3575. } else {
  3576. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3577. }
  3578. }
  3579. return isDefined(value) ? value : this;
  3580. };
  3581. });
  3582. // bind legacy bind/unbind to on/off
  3583. JQLite.prototype.bind = JQLite.prototype.on;
  3584. JQLite.prototype.unbind = JQLite.prototype.off;
  3585. // Provider for private $$jqLite service
  3586. /** @this */
  3587. function $$jqLiteProvider() {
  3588. this.$get = function $$jqLite() {
  3589. return extend(JQLite, {
  3590. hasClass: function(node, classes) {
  3591. if (node.attr) node = node[0];
  3592. return jqLiteHasClass(node, classes);
  3593. },
  3594. addClass: function(node, classes) {
  3595. if (node.attr) node = node[0];
  3596. return jqLiteAddClass(node, classes);
  3597. },
  3598. removeClass: function(node, classes) {
  3599. if (node.attr) node = node[0];
  3600. return jqLiteRemoveClass(node, classes);
  3601. }
  3602. });
  3603. };
  3604. }
  3605. /**
  3606. * Computes a hash of an 'obj'.
  3607. * Hash of a:
  3608. * string is string
  3609. * number is number as string
  3610. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3611. * that is also assigned to the $$hashKey property of the object.
  3612. *
  3613. * @param obj
  3614. * @returns {string} hash string such that the same input will have the same hash string.
  3615. * The resulting string key is in 'type:hashKey' format.
  3616. */
  3617. function hashKey(obj, nextUidFn) {
  3618. var key = obj && obj.$$hashKey;
  3619. if (key) {
  3620. if (typeof key === 'function') {
  3621. key = obj.$$hashKey();
  3622. }
  3623. return key;
  3624. }
  3625. var objType = typeof obj;
  3626. if (objType === 'function' || (objType === 'object' && obj !== null)) {
  3627. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3628. } else {
  3629. key = objType + ':' + obj;
  3630. }
  3631. return key;
  3632. }
  3633. // A minimal ES2015 Map implementation.
  3634. // Should be bug/feature equivalent to the native implementations of supported browsers
  3635. // (for the features required in Angular).
  3636. // See https://kangax.github.io/compat-table/es6/#test-Map
  3637. var nanKey = Object.create(null);
  3638. function NgMapShim() {
  3639. this._keys = [];
  3640. this._values = [];
  3641. this._lastKey = NaN;
  3642. this._lastIndex = -1;
  3643. }
  3644. NgMapShim.prototype = {
  3645. _idx: function(key) {
  3646. if (key !== this._lastKey) {
  3647. this._lastKey = key;
  3648. this._lastIndex = this._keys.indexOf(key);
  3649. }
  3650. return this._lastIndex;
  3651. },
  3652. _transformKey: function(key) {
  3653. return isNumberNaN(key) ? nanKey : key;
  3654. },
  3655. get: function(key) {
  3656. key = this._transformKey(key);
  3657. var idx = this._idx(key);
  3658. if (idx !== -1) {
  3659. return this._values[idx];
  3660. }
  3661. },
  3662. has: function(key) {
  3663. key = this._transformKey(key);
  3664. var idx = this._idx(key);
  3665. return idx !== -1;
  3666. },
  3667. set: function(key, value) {
  3668. key = this._transformKey(key);
  3669. var idx = this._idx(key);
  3670. if (idx === -1) {
  3671. idx = this._lastIndex = this._keys.length;
  3672. }
  3673. this._keys[idx] = key;
  3674. this._values[idx] = value;
  3675. // Support: IE11
  3676. // Do not `return this` to simulate the partial IE11 implementation
  3677. },
  3678. delete: function(key) {
  3679. key = this._transformKey(key);
  3680. var idx = this._idx(key);
  3681. if (idx === -1) {
  3682. return false;
  3683. }
  3684. this._keys.splice(idx, 1);
  3685. this._values.splice(idx, 1);
  3686. this._lastKey = NaN;
  3687. this._lastIndex = -1;
  3688. return true;
  3689. }
  3690. };
  3691. // For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations
  3692. // are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map`
  3693. // implementations get more stable, we can reconsider switching to `window.Map` (when available).
  3694. var NgMap = NgMapShim;
  3695. var $$MapProvider = [/** @this */function() {
  3696. this.$get = [function() {
  3697. return NgMap;
  3698. }];
  3699. }];
  3700. /**
  3701. * @ngdoc function
  3702. * @module ng
  3703. * @name angular.injector
  3704. * @kind function
  3705. *
  3706. * @description
  3707. * Creates an injector object that can be used for retrieving services as well as for
  3708. * dependency injection (see {@link guide/di dependency injection}).
  3709. *
  3710. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3711. * {@link angular.module}. The `ng` module must be explicitly added.
  3712. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3713. * disallows argument name annotation inference.
  3714. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3715. *
  3716. * @example
  3717. * Typical usage
  3718. * ```js
  3719. * // create an injector
  3720. * var $injector = angular.injector(['ng']);
  3721. *
  3722. * // use the injector to kick off your application
  3723. * // use the type inference to auto inject arguments, or use implicit injection
  3724. * $injector.invoke(function($rootScope, $compile, $document) {
  3725. * $compile($document)($rootScope);
  3726. * $rootScope.$digest();
  3727. * });
  3728. * ```
  3729. *
  3730. * Sometimes you want to get access to the injector of a currently running AngularJS app
  3731. * from outside AngularJS. Perhaps, you want to inject and compile some markup after the
  3732. * application has been bootstrapped. You can do this using the extra `injector()` added
  3733. * to JQuery/jqLite elements. See {@link angular.element}.
  3734. *
  3735. * *This is fairly rare but could be the case if a third party library is injecting the
  3736. * markup.*
  3737. *
  3738. * In the following example a new block of HTML containing a `ng-controller`
  3739. * directive is added to the end of the document body by JQuery. We then compile and link
  3740. * it into the current AngularJS scope.
  3741. *
  3742. * ```js
  3743. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3744. * $(document.body).append($div);
  3745. *
  3746. * angular.element(document).injector().invoke(function($compile) {
  3747. * var scope = angular.element($div).scope();
  3748. * $compile($div)(scope);
  3749. * });
  3750. * ```
  3751. */
  3752. /**
  3753. * @ngdoc module
  3754. * @name auto
  3755. * @installation
  3756. * @description
  3757. *
  3758. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3759. */
  3760. var ARROW_ARG = /^([^(]+?)=>/;
  3761. var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
  3762. var FN_ARG_SPLIT = /,/;
  3763. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3764. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3765. var $injectorMinErr = minErr('$injector');
  3766. function stringifyFn(fn) {
  3767. return Function.prototype.toString.call(fn);
  3768. }
  3769. function extractArgs(fn) {
  3770. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3771. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3772. return args;
  3773. }
  3774. function anonFn(fn) {
  3775. // For anonymous functions, showing at the very least the function signature can help in
  3776. // debugging.
  3777. var args = extractArgs(fn);
  3778. if (args) {
  3779. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3780. }
  3781. return 'fn';
  3782. }
  3783. function annotate(fn, strictDi, name) {
  3784. var $inject,
  3785. argDecl,
  3786. last;
  3787. if (typeof fn === 'function') {
  3788. if (!($inject = fn.$inject)) {
  3789. $inject = [];
  3790. if (fn.length) {
  3791. if (strictDi) {
  3792. if (!isString(name) || !name) {
  3793. name = fn.name || anonFn(fn);
  3794. }
  3795. throw $injectorMinErr('strictdi',
  3796. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3797. }
  3798. argDecl = extractArgs(fn);
  3799. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3800. arg.replace(FN_ARG, function(all, underscore, name) {
  3801. $inject.push(name);
  3802. });
  3803. });
  3804. }
  3805. fn.$inject = $inject;
  3806. }
  3807. } else if (isArray(fn)) {
  3808. last = fn.length - 1;
  3809. assertArgFn(fn[last], 'fn');
  3810. $inject = fn.slice(0, last);
  3811. } else {
  3812. assertArgFn(fn, 'fn', true);
  3813. }
  3814. return $inject;
  3815. }
  3816. ///////////////////////////////////////
  3817. /**
  3818. * @ngdoc service
  3819. * @name $injector
  3820. *
  3821. * @description
  3822. *
  3823. * `$injector` is used to retrieve object instances as defined by
  3824. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3825. * and load modules.
  3826. *
  3827. * The following always holds true:
  3828. *
  3829. * ```js
  3830. * var $injector = angular.injector();
  3831. * expect($injector.get('$injector')).toBe($injector);
  3832. * expect($injector.invoke(function($injector) {
  3833. * return $injector;
  3834. * })).toBe($injector);
  3835. * ```
  3836. *
  3837. * ## Injection Function Annotation
  3838. *
  3839. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3840. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3841. *
  3842. * ```js
  3843. * // inferred (only works if code not minified/obfuscated)
  3844. * $injector.invoke(function(serviceA){});
  3845. *
  3846. * // annotated
  3847. * function explicit(serviceA) {};
  3848. * explicit.$inject = ['serviceA'];
  3849. * $injector.invoke(explicit);
  3850. *
  3851. * // inline
  3852. * $injector.invoke(['serviceA', function(serviceA){}]);
  3853. * ```
  3854. *
  3855. * ### Inference
  3856. *
  3857. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3858. * can then be parsed and the function arguments can be extracted. This method of discovering
  3859. * annotations is disallowed when the injector is in strict mode.
  3860. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3861. * argument names.
  3862. *
  3863. * ### `$inject` Annotation
  3864. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3865. *
  3866. * ### Inline
  3867. * As an array of injection names, where the last item in the array is the function to call.
  3868. */
  3869. /**
  3870. * @ngdoc property
  3871. * @name $injector#modules
  3872. * @type {Object}
  3873. * @description
  3874. * A hash containing all the modules that have been loaded into the
  3875. * $injector.
  3876. *
  3877. * You can use this property to find out information about a module via the
  3878. * {@link angular.Module#info `myModule.info(...)`} method.
  3879. *
  3880. * For example:
  3881. *
  3882. * ```
  3883. * var info = $injector.modules['ngAnimate'].info();
  3884. * ```
  3885. *
  3886. * **Do not use this property to attempt to modify the modules after the application
  3887. * has been bootstrapped.**
  3888. */
  3889. /**
  3890. * @ngdoc method
  3891. * @name $injector#get
  3892. *
  3893. * @description
  3894. * Return an instance of the service.
  3895. *
  3896. * @param {string} name The name of the instance to retrieve.
  3897. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3898. * @return {*} The instance.
  3899. */
  3900. /**
  3901. * @ngdoc method
  3902. * @name $injector#invoke
  3903. *
  3904. * @description
  3905. * Invoke the method and supply the method arguments from the `$injector`.
  3906. *
  3907. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3908. * injected according to the {@link guide/di $inject Annotation} rules.
  3909. * @param {Object=} self The `this` for the invoked method.
  3910. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3911. * object first, before the `$injector` is consulted.
  3912. * @returns {*} the value returned by the invoked `fn` function.
  3913. */
  3914. /**
  3915. * @ngdoc method
  3916. * @name $injector#has
  3917. *
  3918. * @description
  3919. * Allows the user to query if the particular service exists.
  3920. *
  3921. * @param {string} name Name of the service to query.
  3922. * @returns {boolean} `true` if injector has given service.
  3923. */
  3924. /**
  3925. * @ngdoc method
  3926. * @name $injector#instantiate
  3927. * @description
  3928. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3929. * operator, and supplies all of the arguments to the constructor function as specified by the
  3930. * constructor annotation.
  3931. *
  3932. * @param {Function} Type Annotated constructor function.
  3933. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3934. * object first, before the `$injector` is consulted.
  3935. * @returns {Object} new instance of `Type`.
  3936. */
  3937. /**
  3938. * @ngdoc method
  3939. * @name $injector#annotate
  3940. *
  3941. * @description
  3942. * Returns an array of service names which the function is requesting for injection. This API is
  3943. * used by the injector to determine which services need to be injected into the function when the
  3944. * function is invoked. There are three ways in which the function can be annotated with the needed
  3945. * dependencies.
  3946. *
  3947. * #### Argument names
  3948. *
  3949. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3950. * by converting the function into a string using `toString()` method and extracting the argument
  3951. * names.
  3952. * ```js
  3953. * // Given
  3954. * function MyController($scope, $route) {
  3955. * // ...
  3956. * }
  3957. *
  3958. * // Then
  3959. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3960. * ```
  3961. *
  3962. * You can disallow this method by using strict injection mode.
  3963. *
  3964. * This method does not work with code minification / obfuscation. For this reason the following
  3965. * annotation strategies are supported.
  3966. *
  3967. * #### The `$inject` property
  3968. *
  3969. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3970. * represent names of services to be injected into the function.
  3971. * ```js
  3972. * // Given
  3973. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3974. * // ...
  3975. * }
  3976. * // Define function dependencies
  3977. * MyController['$inject'] = ['$scope', '$route'];
  3978. *
  3979. * // Then
  3980. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3981. * ```
  3982. *
  3983. * #### The array notation
  3984. *
  3985. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3986. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3987. * a way that survives minification is a better choice:
  3988. *
  3989. * ```js
  3990. * // We wish to write this (not minification / obfuscation safe)
  3991. * injector.invoke(function($compile, $rootScope) {
  3992. * // ...
  3993. * });
  3994. *
  3995. * // We are forced to write break inlining
  3996. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3997. * // ...
  3998. * };
  3999. * tmpFn.$inject = ['$compile', '$rootScope'];
  4000. * injector.invoke(tmpFn);
  4001. *
  4002. * // To better support inline function the inline annotation is supported
  4003. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  4004. * // ...
  4005. * }]);
  4006. *
  4007. * // Therefore
  4008. * expect(injector.annotate(
  4009. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  4010. * ).toEqual(['$compile', '$rootScope']);
  4011. * ```
  4012. *
  4013. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  4014. * be retrieved as described above.
  4015. *
  4016. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  4017. *
  4018. * @returns {Array.<string>} The names of the services which the function requires.
  4019. */
  4020. /**
  4021. * @ngdoc method
  4022. * @name $injector#loadNewModules
  4023. *
  4024. * @description
  4025. *
  4026. * **This is a dangerous API, which you use at your own risk!**
  4027. *
  4028. * Add the specified modules to the current injector.
  4029. *
  4030. * This method will add each of the injectables to the injector and execute all of the config and run
  4031. * blocks for each module passed to the method.
  4032. *
  4033. * If a module has already been loaded into the injector then it will not be loaded again.
  4034. *
  4035. * * The application developer is responsible for loading the code containing the modules; and for
  4036. * ensuring that lazy scripts are not downloaded and executed more often that desired.
  4037. * * Previously compiled HTML will not be affected by newly loaded directives, filters and components.
  4038. * * Modules cannot be unloaded.
  4039. *
  4040. * You can use {@link $injector#modules `$injector.modules`} to check whether a module has been loaded
  4041. * into the injector, which may indicate whether the script has been executed already.
  4042. *
  4043. * @example
  4044. * Here is an example of loading a bundle of modules, with a utility method called `getScript`:
  4045. *
  4046. * ```javascript
  4047. * app.factory('loadModule', function($injector) {
  4048. * return function loadModule(moduleName, bundleUrl) {
  4049. * return getScript(bundleUrl).then(function() { $injector.loadNewModules([moduleName]); });
  4050. * };
  4051. * })
  4052. * ```
  4053. *
  4054. * @param {Array<String|Function|Array>=} mods an array of modules to load into the application.
  4055. * Each item in the array should be the name of a predefined module or a (DI annotated)
  4056. * function that will be invoked by the injector as a `config` block.
  4057. * See: {@link angular.module modules}
  4058. */
  4059. /**
  4060. * @ngdoc service
  4061. * @name $provide
  4062. *
  4063. * @description
  4064. *
  4065. * The {@link auto.$provide $provide} service has a number of methods for registering components
  4066. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  4067. * {@link angular.Module}.
  4068. *
  4069. * An AngularJS **service** is a singleton object created by a **service factory**. These **service
  4070. * factories** are functions which, in turn, are created by a **service provider**.
  4071. * The **service providers** are constructor functions. When instantiated they must contain a
  4072. * property called `$get`, which holds the **service factory** function.
  4073. *
  4074. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  4075. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  4076. * function to get the instance of the **service**.
  4077. *
  4078. * Often services have no configuration options and there is no need to add methods to the service
  4079. * provider. The provider will be no more than a constructor function with a `$get` property. For
  4080. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  4081. * services without specifying a provider.
  4082. *
  4083. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  4084. * {@link auto.$injector $injector}
  4085. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  4086. * providers and services.
  4087. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  4088. * services, not providers.
  4089. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  4090. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  4091. * given factory function.
  4092. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  4093. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  4094. * a new object using the given constructor function.
  4095. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  4096. * will be able to modify or replace the implementation of another service.
  4097. *
  4098. * See the individual methods for more information and examples.
  4099. */
  4100. /**
  4101. * @ngdoc method
  4102. * @name $provide#provider
  4103. * @description
  4104. *
  4105. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  4106. * are constructor functions, whose instances are responsible for "providing" a factory for a
  4107. * service.
  4108. *
  4109. * Service provider names start with the name of the service they provide followed by `Provider`.
  4110. * For example, the {@link ng.$log $log} service has a provider called
  4111. * {@link ng.$logProvider $logProvider}.
  4112. *
  4113. * Service provider objects can have additional methods which allow configuration of the provider
  4114. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  4115. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  4116. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  4117. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  4118. * console or not.
  4119. *
  4120. * It is possible to inject other providers into the provider function,
  4121. * but the injected provider must have been defined before the one that requires it.
  4122. *
  4123. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  4124. 'Provider'` key.
  4125. * @param {(Object|function())} provider If the provider is:
  4126. *
  4127. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  4128. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  4129. * - `Constructor`: a new instance of the provider will be created using
  4130. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  4131. *
  4132. * @returns {Object} registered provider instance
  4133. * @example
  4134. *
  4135. * The following example shows how to create a simple event tracking service and register it using
  4136. * {@link auto.$provide#provider $provide.provider()}.
  4137. *
  4138. * ```js
  4139. * // Define the eventTracker provider
  4140. * function EventTrackerProvider() {
  4141. * var trackingUrl = '/track';
  4142. *
  4143. * // A provider method for configuring where the tracked events should been saved
  4144. * this.setTrackingUrl = function(url) {
  4145. * trackingUrl = url;
  4146. * };
  4147. *
  4148. * // The service factory function
  4149. * this.$get = ['$http', function($http) {
  4150. * var trackedEvents = {};
  4151. * return {
  4152. * // Call this to track an event
  4153. * event: function(event) {
  4154. * var count = trackedEvents[event] || 0;
  4155. * count += 1;
  4156. * trackedEvents[event] = count;
  4157. * return count;
  4158. * },
  4159. * // Call this to save the tracked events to the trackingUrl
  4160. * save: function() {
  4161. * $http.post(trackingUrl, trackedEvents);
  4162. * }
  4163. * };
  4164. * }];
  4165. * }
  4166. *
  4167. * describe('eventTracker', function() {
  4168. * var postSpy;
  4169. *
  4170. * beforeEach(module(function($provide) {
  4171. * // Register the eventTracker provider
  4172. * $provide.provider('eventTracker', EventTrackerProvider);
  4173. * }));
  4174. *
  4175. * beforeEach(module(function(eventTrackerProvider) {
  4176. * // Configure eventTracker provider
  4177. * eventTrackerProvider.setTrackingUrl('/custom-track');
  4178. * }));
  4179. *
  4180. * it('tracks events', inject(function(eventTracker) {
  4181. * expect(eventTracker.event('login')).toEqual(1);
  4182. * expect(eventTracker.event('login')).toEqual(2);
  4183. * }));
  4184. *
  4185. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  4186. * postSpy = spyOn($http, 'post');
  4187. * eventTracker.event('login');
  4188. * eventTracker.save();
  4189. * expect(postSpy).toHaveBeenCalled();
  4190. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  4191. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  4192. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  4193. * }));
  4194. * });
  4195. * ```
  4196. */
  4197. /**
  4198. * @ngdoc method
  4199. * @name $provide#factory
  4200. * @description
  4201. *
  4202. * Register a **service factory**, which will be called to return the service instance.
  4203. * This is short for registering a service where its provider consists of only a `$get` property,
  4204. * which is the given service factory function.
  4205. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  4206. * configure your service in a provider.
  4207. *
  4208. * @param {string} name The name of the instance.
  4209. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  4210. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  4211. * @returns {Object} registered provider instance
  4212. *
  4213. * @example
  4214. * Here is an example of registering a service
  4215. * ```js
  4216. * $provide.factory('ping', ['$http', function($http) {
  4217. * return function ping() {
  4218. * return $http.send('/ping');
  4219. * };
  4220. * }]);
  4221. * ```
  4222. * You would then inject and use this service like this:
  4223. * ```js
  4224. * someModule.controller('Ctrl', ['ping', function(ping) {
  4225. * ping();
  4226. * }]);
  4227. * ```
  4228. */
  4229. /**
  4230. * @ngdoc method
  4231. * @name $provide#service
  4232. * @description
  4233. *
  4234. * Register a **service constructor**, which will be invoked with `new` to create the service
  4235. * instance.
  4236. * This is short for registering a service where its provider's `$get` property is a factory
  4237. * function that returns an instance instantiated by the injector from the service constructor
  4238. * function.
  4239. *
  4240. * Internally it looks a bit like this:
  4241. *
  4242. * ```
  4243. * {
  4244. * $get: function() {
  4245. * return $injector.instantiate(constructor);
  4246. * }
  4247. * }
  4248. * ```
  4249. *
  4250. *
  4251. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  4252. * as a type/class.
  4253. *
  4254. * @param {string} name The name of the instance.
  4255. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  4256. * that will be instantiated.
  4257. * @returns {Object} registered provider instance
  4258. *
  4259. * @example
  4260. * Here is an example of registering a service using
  4261. * {@link auto.$provide#service $provide.service(class)}.
  4262. * ```js
  4263. * var Ping = function($http) {
  4264. * this.$http = $http;
  4265. * };
  4266. *
  4267. * Ping.$inject = ['$http'];
  4268. *
  4269. * Ping.prototype.send = function() {
  4270. * return this.$http.get('/ping');
  4271. * };
  4272. * $provide.service('ping', Ping);
  4273. * ```
  4274. * You would then inject and use this service like this:
  4275. * ```js
  4276. * someModule.controller('Ctrl', ['ping', function(ping) {
  4277. * ping.send();
  4278. * }]);
  4279. * ```
  4280. */
  4281. /**
  4282. * @ngdoc method
  4283. * @name $provide#value
  4284. * @description
  4285. *
  4286. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  4287. * number, an array, an object or a function. This is short for registering a service where its
  4288. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  4289. * service**. That also means it is not possible to inject other services into a value service.
  4290. *
  4291. * Value services are similar to constant services, except that they cannot be injected into a
  4292. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  4293. * an AngularJS {@link auto.$provide#decorator decorator}.
  4294. *
  4295. * @param {string} name The name of the instance.
  4296. * @param {*} value The value.
  4297. * @returns {Object} registered provider instance
  4298. *
  4299. * @example
  4300. * Here are some examples of creating value services.
  4301. * ```js
  4302. * $provide.value('ADMIN_USER', 'admin');
  4303. *
  4304. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  4305. *
  4306. * $provide.value('halfOf', function(value) {
  4307. * return value / 2;
  4308. * });
  4309. * ```
  4310. */
  4311. /**
  4312. * @ngdoc method
  4313. * @name $provide#constant
  4314. * @description
  4315. *
  4316. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  4317. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  4318. * possible to inject other services into a constant.
  4319. *
  4320. * But unlike {@link auto.$provide#value value}, a constant can be
  4321. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  4322. * be overridden by an AngularJS {@link auto.$provide#decorator decorator}.
  4323. *
  4324. * @param {string} name The name of the constant.
  4325. * @param {*} value The constant value.
  4326. * @returns {Object} registered instance
  4327. *
  4328. * @example
  4329. * Here a some examples of creating constants:
  4330. * ```js
  4331. * $provide.constant('SHARD_HEIGHT', 306);
  4332. *
  4333. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  4334. *
  4335. * $provide.constant('double', function(value) {
  4336. * return value * 2;
  4337. * });
  4338. * ```
  4339. */
  4340. /**
  4341. * @ngdoc method
  4342. * @name $provide#decorator
  4343. * @description
  4344. *
  4345. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  4346. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  4347. * service. The return value of the decorator function may be the original service, or a new service
  4348. * that replaces (or wraps and delegates to) the original service.
  4349. *
  4350. * You can find out more about using decorators in the {@link guide/decorators} guide.
  4351. *
  4352. * @param {string} name The name of the service to decorate.
  4353. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  4354. * provided and should return the decorated service instance. The function is called using
  4355. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  4356. * Local injection arguments:
  4357. *
  4358. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  4359. * decorated or delegated to.
  4360. *
  4361. * @example
  4362. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  4363. * calls to {@link ng.$log#error $log.warn()}.
  4364. * ```js
  4365. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4366. * $delegate.warn = $delegate.error;
  4367. * return $delegate;
  4368. * }]);
  4369. * ```
  4370. */
  4371. function createInjector(modulesToLoad, strictDi) {
  4372. strictDi = (strictDi === true);
  4373. var INSTANTIATING = {},
  4374. providerSuffix = 'Provider',
  4375. path = [],
  4376. loadedModules = new NgMap(),
  4377. providerCache = {
  4378. $provide: {
  4379. provider: supportObject(provider),
  4380. factory: supportObject(factory),
  4381. service: supportObject(service),
  4382. value: supportObject(value),
  4383. constant: supportObject(constant),
  4384. decorator: decorator
  4385. }
  4386. },
  4387. providerInjector = (providerCache.$injector =
  4388. createInternalInjector(providerCache, function(serviceName, caller) {
  4389. if (angular.isString(caller)) {
  4390. path.push(caller);
  4391. }
  4392. throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
  4393. })),
  4394. instanceCache = {},
  4395. protoInstanceInjector =
  4396. createInternalInjector(instanceCache, function(serviceName, caller) {
  4397. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4398. return instanceInjector.invoke(
  4399. provider.$get, provider, undefined, serviceName);
  4400. }),
  4401. instanceInjector = protoInstanceInjector;
  4402. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4403. instanceInjector.modules = providerInjector.modules = createMap();
  4404. var runBlocks = loadModules(modulesToLoad);
  4405. instanceInjector = protoInstanceInjector.get('$injector');
  4406. instanceInjector.strictDi = strictDi;
  4407. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4408. instanceInjector.loadNewModules = function(mods) {
  4409. forEach(loadModules(mods), function(fn) { if (fn) instanceInjector.invoke(fn); });
  4410. };
  4411. return instanceInjector;
  4412. ////////////////////////////////////
  4413. // $provider
  4414. ////////////////////////////////////
  4415. function supportObject(delegate) {
  4416. return function(key, value) {
  4417. if (isObject(key)) {
  4418. forEach(key, reverseParams(delegate));
  4419. } else {
  4420. return delegate(key, value);
  4421. }
  4422. };
  4423. }
  4424. function provider(name, provider_) {
  4425. assertNotHasOwnProperty(name, 'service');
  4426. if (isFunction(provider_) || isArray(provider_)) {
  4427. provider_ = providerInjector.instantiate(provider_);
  4428. }
  4429. if (!provider_.$get) {
  4430. throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
  4431. }
  4432. return (providerCache[name + providerSuffix] = provider_);
  4433. }
  4434. function enforceReturnValue(name, factory) {
  4435. return /** @this */ function enforcedReturnValue() {
  4436. var result = instanceInjector.invoke(factory, this);
  4437. if (isUndefined(result)) {
  4438. throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
  4439. }
  4440. return result;
  4441. };
  4442. }
  4443. function factory(name, factoryFn, enforce) {
  4444. return provider(name, {
  4445. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4446. });
  4447. }
  4448. function service(name, constructor) {
  4449. return factory(name, ['$injector', function($injector) {
  4450. return $injector.instantiate(constructor);
  4451. }]);
  4452. }
  4453. function value(name, val) { return factory(name, valueFn(val), false); }
  4454. function constant(name, value) {
  4455. assertNotHasOwnProperty(name, 'constant');
  4456. providerCache[name] = value;
  4457. instanceCache[name] = value;
  4458. }
  4459. function decorator(serviceName, decorFn) {
  4460. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4461. orig$get = origProvider.$get;
  4462. origProvider.$get = function() {
  4463. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4464. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4465. };
  4466. }
  4467. ////////////////////////////////////
  4468. // Module Loading
  4469. ////////////////////////////////////
  4470. function loadModules(modulesToLoad) {
  4471. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4472. var runBlocks = [], moduleFn;
  4473. forEach(modulesToLoad, function(module) {
  4474. if (loadedModules.get(module)) return;
  4475. loadedModules.set(module, true);
  4476. function runInvokeQueue(queue) {
  4477. var i, ii;
  4478. for (i = 0, ii = queue.length; i < ii; i++) {
  4479. var invokeArgs = queue[i],
  4480. provider = providerInjector.get(invokeArgs[0]);
  4481. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4482. }
  4483. }
  4484. try {
  4485. if (isString(module)) {
  4486. moduleFn = angularModule(module);
  4487. instanceInjector.modules[module] = moduleFn;
  4488. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4489. runInvokeQueue(moduleFn._invokeQueue);
  4490. runInvokeQueue(moduleFn._configBlocks);
  4491. } else if (isFunction(module)) {
  4492. runBlocks.push(providerInjector.invoke(module));
  4493. } else if (isArray(module)) {
  4494. runBlocks.push(providerInjector.invoke(module));
  4495. } else {
  4496. assertArgFn(module, 'module');
  4497. }
  4498. } catch (e) {
  4499. if (isArray(module)) {
  4500. module = module[module.length - 1];
  4501. }
  4502. if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
  4503. // Safari & FF's stack traces don't contain error.message content
  4504. // unlike those of Chrome and IE
  4505. // So if stack doesn't contain message, we create a new string that contains both.
  4506. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4507. // eslint-disable-next-line no-ex-assign
  4508. e = e.message + '\n' + e.stack;
  4509. }
  4510. throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
  4511. module, e.stack || e.message || e);
  4512. }
  4513. });
  4514. return runBlocks;
  4515. }
  4516. ////////////////////////////////////
  4517. // internal Injector
  4518. ////////////////////////////////////
  4519. function createInternalInjector(cache, factory) {
  4520. function getService(serviceName, caller) {
  4521. if (cache.hasOwnProperty(serviceName)) {
  4522. if (cache[serviceName] === INSTANTIATING) {
  4523. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4524. serviceName + ' <- ' + path.join(' <- '));
  4525. }
  4526. return cache[serviceName];
  4527. } else {
  4528. try {
  4529. path.unshift(serviceName);
  4530. cache[serviceName] = INSTANTIATING;
  4531. cache[serviceName] = factory(serviceName, caller);
  4532. return cache[serviceName];
  4533. } catch (err) {
  4534. if (cache[serviceName] === INSTANTIATING) {
  4535. delete cache[serviceName];
  4536. }
  4537. throw err;
  4538. } finally {
  4539. path.shift();
  4540. }
  4541. }
  4542. }
  4543. function injectionArgs(fn, locals, serviceName) {
  4544. var args = [],
  4545. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4546. for (var i = 0, length = $inject.length; i < length; i++) {
  4547. var key = $inject[i];
  4548. if (typeof key !== 'string') {
  4549. throw $injectorMinErr('itkn',
  4550. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4551. }
  4552. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4553. getService(key, serviceName));
  4554. }
  4555. return args;
  4556. }
  4557. function isClass(func) {
  4558. // Support: IE 9-11 only
  4559. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4560. if (msie || typeof func !== 'function') {
  4561. return false;
  4562. }
  4563. var result = func.$$ngIsClass;
  4564. if (!isBoolean(result)) {
  4565. result = func.$$ngIsClass = /^class\b/.test(stringifyFn(func));
  4566. }
  4567. return result;
  4568. }
  4569. function invoke(fn, self, locals, serviceName) {
  4570. if (typeof locals === 'string') {
  4571. serviceName = locals;
  4572. locals = null;
  4573. }
  4574. var args = injectionArgs(fn, locals, serviceName);
  4575. if (isArray(fn)) {
  4576. fn = fn[fn.length - 1];
  4577. }
  4578. if (!isClass(fn)) {
  4579. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4580. // #5388
  4581. return fn.apply(self, args);
  4582. } else {
  4583. args.unshift(null);
  4584. return new (Function.prototype.bind.apply(fn, args))();
  4585. }
  4586. }
  4587. function instantiate(Type, locals, serviceName) {
  4588. // Check if Type is annotated and use just the given function at n-1 as parameter
  4589. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4590. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4591. var args = injectionArgs(Type, locals, serviceName);
  4592. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4593. args.unshift(null);
  4594. return new (Function.prototype.bind.apply(ctor, args))();
  4595. }
  4596. return {
  4597. invoke: invoke,
  4598. instantiate: instantiate,
  4599. get: getService,
  4600. annotate: createInjector.$$annotate,
  4601. has: function(name) {
  4602. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4603. }
  4604. };
  4605. }
  4606. }
  4607. createInjector.$$annotate = annotate;
  4608. /**
  4609. * @ngdoc provider
  4610. * @name $anchorScrollProvider
  4611. * @this
  4612. *
  4613. * @description
  4614. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4615. * {@link ng.$location#hash $location.hash()} changes.
  4616. */
  4617. function $AnchorScrollProvider() {
  4618. var autoScrollingEnabled = true;
  4619. /**
  4620. * @ngdoc method
  4621. * @name $anchorScrollProvider#disableAutoScrolling
  4622. *
  4623. * @description
  4624. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4625. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4626. * Use this method to disable automatic scrolling.
  4627. *
  4628. * If automatic scrolling is disabled, one must explicitly call
  4629. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4630. * current hash.
  4631. */
  4632. this.disableAutoScrolling = function() {
  4633. autoScrollingEnabled = false;
  4634. };
  4635. /**
  4636. * @ngdoc service
  4637. * @name $anchorScroll
  4638. * @kind function
  4639. * @requires $window
  4640. * @requires $location
  4641. * @requires $rootScope
  4642. *
  4643. * @description
  4644. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4645. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4646. * in the
  4647. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4648. *
  4649. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4650. * match any anchor whenever it changes. This can be disabled by calling
  4651. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4652. *
  4653. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4654. * vertical scroll-offset (either fixed or dynamic).
  4655. *
  4656. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4657. * {@link ng.$location#hash $location.hash()} will be used.
  4658. *
  4659. * @property {(number|function|jqLite)} yOffset
  4660. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4661. * positioned elements at the top of the page, such as navbars, headers etc.
  4662. *
  4663. * `yOffset` can be specified in various ways:
  4664. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4665. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4666. * a number representing the offset (in pixels).<br /><br />
  4667. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4668. * the top of the page to the element's bottom will be used as offset.<br />
  4669. * **Note**: The element will be taken into account only as long as its `position` is set to
  4670. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4671. * their height and/or positioning according to the viewport's size.
  4672. *
  4673. * <br />
  4674. * <div class="alert alert-warning">
  4675. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4676. * not some child element.
  4677. * </div>
  4678. *
  4679. * @example
  4680. <example module="anchorScrollExample" name="anchor-scroll">
  4681. <file name="index.html">
  4682. <div id="scrollArea" ng-controller="ScrollController">
  4683. <a ng-click="gotoBottom()">Go to bottom</a>
  4684. <a id="bottom"></a> You're at the bottom!
  4685. </div>
  4686. </file>
  4687. <file name="script.js">
  4688. angular.module('anchorScrollExample', [])
  4689. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4690. function($scope, $location, $anchorScroll) {
  4691. $scope.gotoBottom = function() {
  4692. // set the location.hash to the id of
  4693. // the element you wish to scroll to.
  4694. $location.hash('bottom');
  4695. // call $anchorScroll()
  4696. $anchorScroll();
  4697. };
  4698. }]);
  4699. </file>
  4700. <file name="style.css">
  4701. #scrollArea {
  4702. height: 280px;
  4703. overflow: auto;
  4704. }
  4705. #bottom {
  4706. display: block;
  4707. margin-top: 2000px;
  4708. }
  4709. </file>
  4710. </example>
  4711. *
  4712. * <hr />
  4713. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4714. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4715. *
  4716. * @example
  4717. <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
  4718. <file name="index.html">
  4719. <div class="fixed-header" ng-controller="headerCtrl">
  4720. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4721. Go to anchor {{x}}
  4722. </a>
  4723. </div>
  4724. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4725. Anchor {{x}} of 5
  4726. </div>
  4727. </file>
  4728. <file name="script.js">
  4729. angular.module('anchorScrollOffsetExample', [])
  4730. .run(['$anchorScroll', function($anchorScroll) {
  4731. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4732. }])
  4733. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4734. function($anchorScroll, $location, $scope) {
  4735. $scope.gotoAnchor = function(x) {
  4736. var newHash = 'anchor' + x;
  4737. if ($location.hash() !== newHash) {
  4738. // set the $location.hash to `newHash` and
  4739. // $anchorScroll will automatically scroll to it
  4740. $location.hash('anchor' + x);
  4741. } else {
  4742. // call $anchorScroll() explicitly,
  4743. // since $location.hash hasn't changed
  4744. $anchorScroll();
  4745. }
  4746. };
  4747. }
  4748. ]);
  4749. </file>
  4750. <file name="style.css">
  4751. body {
  4752. padding-top: 50px;
  4753. }
  4754. .anchor {
  4755. border: 2px dashed DarkOrchid;
  4756. padding: 10px 10px 200px 10px;
  4757. }
  4758. .fixed-header {
  4759. background-color: rgba(0, 0, 0, 0.2);
  4760. height: 50px;
  4761. position: fixed;
  4762. top: 0; left: 0; right: 0;
  4763. }
  4764. .fixed-header > a {
  4765. display: inline-block;
  4766. margin: 5px 15px;
  4767. }
  4768. </file>
  4769. </example>
  4770. */
  4771. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4772. var document = $window.document;
  4773. // Helper function to get first anchor from a NodeList
  4774. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4775. // and working in all supported browsers.)
  4776. function getFirstAnchor(list) {
  4777. var result = null;
  4778. Array.prototype.some.call(list, function(element) {
  4779. if (nodeName_(element) === 'a') {
  4780. result = element;
  4781. return true;
  4782. }
  4783. });
  4784. return result;
  4785. }
  4786. function getYOffset() {
  4787. var offset = scroll.yOffset;
  4788. if (isFunction(offset)) {
  4789. offset = offset();
  4790. } else if (isElement(offset)) {
  4791. var elem = offset[0];
  4792. var style = $window.getComputedStyle(elem);
  4793. if (style.position !== 'fixed') {
  4794. offset = 0;
  4795. } else {
  4796. offset = elem.getBoundingClientRect().bottom;
  4797. }
  4798. } else if (!isNumber(offset)) {
  4799. offset = 0;
  4800. }
  4801. return offset;
  4802. }
  4803. function scrollTo(elem) {
  4804. if (elem) {
  4805. elem.scrollIntoView();
  4806. var offset = getYOffset();
  4807. if (offset) {
  4808. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4809. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4810. // top of the viewport.
  4811. //
  4812. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4813. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4814. // way down the page.
  4815. //
  4816. // This is often the case for elements near the bottom of the page.
  4817. //
  4818. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4819. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4820. // desired position.
  4821. var elemTop = elem.getBoundingClientRect().top;
  4822. $window.scrollBy(0, elemTop - offset);
  4823. }
  4824. } else {
  4825. $window.scrollTo(0, 0);
  4826. }
  4827. }
  4828. function scroll(hash) {
  4829. // Allow numeric hashes
  4830. hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
  4831. var elm;
  4832. // empty hash, scroll to the top of the page
  4833. if (!hash) scrollTo(null);
  4834. // element with given id
  4835. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4836. // first anchor with given name :-D
  4837. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4838. // no element and hash === 'top', scroll to the top of the page
  4839. else if (hash === 'top') scrollTo(null);
  4840. }
  4841. // does not scroll when user clicks on anchor link that is currently on
  4842. // (no url change, no $location.hash() change), browser native does scroll
  4843. if (autoScrollingEnabled) {
  4844. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4845. function autoScrollWatchAction(newVal, oldVal) {
  4846. // skip the initial scroll if $location.hash is empty
  4847. if (newVal === oldVal && newVal === '') return;
  4848. jqLiteDocumentLoaded(function() {
  4849. $rootScope.$evalAsync(scroll);
  4850. });
  4851. });
  4852. }
  4853. return scroll;
  4854. }];
  4855. }
  4856. var $animateMinErr = minErr('$animate');
  4857. var ELEMENT_NODE = 1;
  4858. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4859. function mergeClasses(a,b) {
  4860. if (!a && !b) return '';
  4861. if (!a) return b;
  4862. if (!b) return a;
  4863. if (isArray(a)) a = a.join(' ');
  4864. if (isArray(b)) b = b.join(' ');
  4865. return a + ' ' + b;
  4866. }
  4867. function extractElementNode(element) {
  4868. for (var i = 0; i < element.length; i++) {
  4869. var elm = element[i];
  4870. if (elm.nodeType === ELEMENT_NODE) {
  4871. return elm;
  4872. }
  4873. }
  4874. }
  4875. function splitClasses(classes) {
  4876. if (isString(classes)) {
  4877. classes = classes.split(' ');
  4878. }
  4879. // Use createMap() to prevent class assumptions involving property names in
  4880. // Object.prototype
  4881. var obj = createMap();
  4882. forEach(classes, function(klass) {
  4883. // sometimes the split leaves empty string values
  4884. // incase extra spaces were applied to the options
  4885. if (klass.length) {
  4886. obj[klass] = true;
  4887. }
  4888. });
  4889. return obj;
  4890. }
  4891. // if any other type of options value besides an Object value is
  4892. // passed into the $animate.method() animation then this helper code
  4893. // will be run which will ignore it. While this patch is not the
  4894. // greatest solution to this, a lot of existing plugins depend on
  4895. // $animate to either call the callback (< 1.2) or return a promise
  4896. // that can be changed. This helper function ensures that the options
  4897. // are wiped clean incase a callback function is provided.
  4898. function prepareAnimateOptions(options) {
  4899. return isObject(options)
  4900. ? options
  4901. : {};
  4902. }
  4903. var $$CoreAnimateJsProvider = /** @this */ function() {
  4904. this.$get = noop;
  4905. };
  4906. // this is prefixed with Core since it conflicts with
  4907. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4908. var $$CoreAnimateQueueProvider = /** @this */ function() {
  4909. var postDigestQueue = new NgMap();
  4910. var postDigestElements = [];
  4911. this.$get = ['$$AnimateRunner', '$rootScope',
  4912. function($$AnimateRunner, $rootScope) {
  4913. return {
  4914. enabled: noop,
  4915. on: noop,
  4916. off: noop,
  4917. pin: noop,
  4918. push: function(element, event, options, domOperation) {
  4919. if (domOperation) {
  4920. domOperation();
  4921. }
  4922. options = options || {};
  4923. if (options.from) {
  4924. element.css(options.from);
  4925. }
  4926. if (options.to) {
  4927. element.css(options.to);
  4928. }
  4929. if (options.addClass || options.removeClass) {
  4930. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4931. }
  4932. var runner = new $$AnimateRunner();
  4933. // since there are no animations to run the runner needs to be
  4934. // notified that the animation call is complete.
  4935. runner.complete();
  4936. return runner;
  4937. }
  4938. };
  4939. function updateData(data, classes, value) {
  4940. var changed = false;
  4941. if (classes) {
  4942. classes = isString(classes) ? classes.split(' ') :
  4943. isArray(classes) ? classes : [];
  4944. forEach(classes, function(className) {
  4945. if (className) {
  4946. changed = true;
  4947. data[className] = value;
  4948. }
  4949. });
  4950. }
  4951. return changed;
  4952. }
  4953. function handleCSSClassChanges() {
  4954. forEach(postDigestElements, function(element) {
  4955. var data = postDigestQueue.get(element);
  4956. if (data) {
  4957. var existing = splitClasses(element.attr('class'));
  4958. var toAdd = '';
  4959. var toRemove = '';
  4960. forEach(data, function(status, className) {
  4961. var hasClass = !!existing[className];
  4962. if (status !== hasClass) {
  4963. if (status) {
  4964. toAdd += (toAdd.length ? ' ' : '') + className;
  4965. } else {
  4966. toRemove += (toRemove.length ? ' ' : '') + className;
  4967. }
  4968. }
  4969. });
  4970. forEach(element, function(elm) {
  4971. if (toAdd) {
  4972. jqLiteAddClass(elm, toAdd);
  4973. }
  4974. if (toRemove) {
  4975. jqLiteRemoveClass(elm, toRemove);
  4976. }
  4977. });
  4978. postDigestQueue.delete(element);
  4979. }
  4980. });
  4981. postDigestElements.length = 0;
  4982. }
  4983. function addRemoveClassesPostDigest(element, add, remove) {
  4984. var data = postDigestQueue.get(element) || {};
  4985. var classesAdded = updateData(data, add, true);
  4986. var classesRemoved = updateData(data, remove, false);
  4987. if (classesAdded || classesRemoved) {
  4988. postDigestQueue.set(element, data);
  4989. postDigestElements.push(element);
  4990. if (postDigestElements.length === 1) {
  4991. $rootScope.$$postDigest(handleCSSClassChanges);
  4992. }
  4993. }
  4994. }
  4995. }];
  4996. };
  4997. /**
  4998. * @ngdoc provider
  4999. * @name $animateProvider
  5000. *
  5001. * @description
  5002. * Default implementation of $animate that doesn't perform any animations, instead just
  5003. * synchronously performs DOM updates and resolves the returned runner promise.
  5004. *
  5005. * In order to enable animations the `ngAnimate` module has to be loaded.
  5006. *
  5007. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  5008. */
  5009. var $AnimateProvider = ['$provide', /** @this */ function($provide) {
  5010. var provider = this;
  5011. var classNameFilter = null;
  5012. var customFilter = null;
  5013. this.$$registeredAnimations = Object.create(null);
  5014. /**
  5015. * @ngdoc method
  5016. * @name $animateProvider#register
  5017. *
  5018. * @description
  5019. * Registers a new injectable animation factory function. The factory function produces the
  5020. * animation object which contains callback functions for each event that is expected to be
  5021. * animated.
  5022. *
  5023. * * `eventFn`: `function(element, ... , doneFunction, options)`
  5024. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  5025. * on the type of animation additional arguments will be injected into the animation function. The
  5026. * list below explains the function signatures for the different animation methods:
  5027. *
  5028. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  5029. * - addClass: function(element, addedClasses, doneFunction, options)
  5030. * - removeClass: function(element, removedClasses, doneFunction, options)
  5031. * - enter, leave, move: function(element, doneFunction, options)
  5032. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  5033. *
  5034. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  5035. *
  5036. * ```js
  5037. * return {
  5038. * //enter, leave, move signature
  5039. * eventFn : function(element, done, options) {
  5040. * //code to run the animation
  5041. * //once complete, then run done()
  5042. * return function endFunction(wasCancelled) {
  5043. * //code to cancel the animation
  5044. * }
  5045. * }
  5046. * }
  5047. * ```
  5048. *
  5049. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  5050. * @param {Function} factory The factory function that will be executed to return the animation
  5051. * object.
  5052. */
  5053. this.register = function(name, factory) {
  5054. if (name && name.charAt(0) !== '.') {
  5055. throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
  5056. }
  5057. var key = name + '-animation';
  5058. provider.$$registeredAnimations[name.substr(1)] = key;
  5059. $provide.factory(key, factory);
  5060. };
  5061. /**
  5062. * @ngdoc method
  5063. * @name $animateProvider#customFilter
  5064. *
  5065. * @description
  5066. * Sets and/or returns the custom filter function that is used to "filter" animations, i.e.
  5067. * determine if an animation is allowed or not. When no filter is specified (the default), no
  5068. * animation will be blocked. Setting the `customFilter` value will only allow animations for
  5069. * which the filter function's return value is truthy.
  5070. *
  5071. * This allows to easily create arbitrarily complex rules for filtering animations, such as
  5072. * allowing specific events only, or enabling animations on specific subtrees of the DOM, etc.
  5073. * Filtering animations can also boost performance for low-powered devices, as well as
  5074. * applications containing a lot of structural operations.
  5075. *
  5076. * <div class="alert alert-success">
  5077. * **Best Practice:**
  5078. * Keep the filtering function as lean as possible, because it will be called for each DOM
  5079. * action (e.g. insertion, removal, class change) performed by "animation-aware" directives.
  5080. * See {@link guide/animations#which-directives-support-animations- here} for a list of built-in
  5081. * directives that support animations.
  5082. * Performing computationally expensive or time-consuming operations on each call of the
  5083. * filtering function can make your animations sluggish.
  5084. * </div>
  5085. *
  5086. * **Note:** If present, `customFilter` will be checked before
  5087. * {@link $animateProvider#classNameFilter classNameFilter}.
  5088. *
  5089. * @param {Function=} filterFn - The filter function which will be used to filter all animations.
  5090. * If a falsy value is returned, no animation will be performed. The function will be called
  5091. * with the following arguments:
  5092. * - **node** `{DOMElement}` - The DOM element to be animated.
  5093. * - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass`
  5094. * etc).
  5095. * - **options** `{Object}` - A collection of options/styles used for the animation.
  5096. * @return {Function} The current filter function or `null` if there is none set.
  5097. */
  5098. this.customFilter = function(filterFn) {
  5099. if (arguments.length === 1) {
  5100. customFilter = isFunction(filterFn) ? filterFn : null;
  5101. }
  5102. return customFilter;
  5103. };
  5104. /**
  5105. * @ngdoc method
  5106. * @name $animateProvider#classNameFilter
  5107. *
  5108. * @description
  5109. * Sets and/or returns the CSS class regular expression that is checked when performing
  5110. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  5111. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  5112. * When setting the `classNameFilter` value, animations will only be performed on elements
  5113. * that successfully match the filter expression. This in turn can boost performance
  5114. * for low-powered devices as well as applications containing a lot of structural operations.
  5115. *
  5116. * **Note:** If present, `classNameFilter` will be checked after
  5117. * {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns
  5118. * false, `classNameFilter` will not be checked.
  5119. *
  5120. * @param {RegExp=} expression The className expression which will be checked against all animations
  5121. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  5122. */
  5123. this.classNameFilter = function(expression) {
  5124. if (arguments.length === 1) {
  5125. classNameFilter = (expression instanceof RegExp) ? expression : null;
  5126. if (classNameFilter) {
  5127. var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]');
  5128. if (reservedRegex.test(classNameFilter.toString())) {
  5129. classNameFilter = null;
  5130. throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  5131. }
  5132. }
  5133. }
  5134. return classNameFilter;
  5135. };
  5136. this.$get = ['$$animateQueue', function($$animateQueue) {
  5137. function domInsert(element, parentElement, afterElement) {
  5138. // if for some reason the previous element was removed
  5139. // from the dom sometime before this code runs then let's
  5140. // just stick to using the parent element as the anchor
  5141. if (afterElement) {
  5142. var afterNode = extractElementNode(afterElement);
  5143. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  5144. afterElement = null;
  5145. }
  5146. }
  5147. if (afterElement) {
  5148. afterElement.after(element);
  5149. } else {
  5150. parentElement.prepend(element);
  5151. }
  5152. }
  5153. /**
  5154. * @ngdoc service
  5155. * @name $animate
  5156. * @description The $animate service exposes a series of DOM utility methods that provide support
  5157. * for animation hooks. The default behavior is the application of DOM operations, however,
  5158. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  5159. * to ensure that animation runs with the triggered DOM operation.
  5160. *
  5161. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  5162. * included and only when it is active then the animation hooks that `$animate` triggers will be
  5163. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  5164. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  5165. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  5166. *
  5167. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  5168. *
  5169. * To learn more about enabling animation support, click here to visit the
  5170. * {@link ngAnimate ngAnimate module page}.
  5171. */
  5172. return {
  5173. // we don't call it directly since non-existant arguments may
  5174. // be interpreted as null within the sub enabled function
  5175. /**
  5176. *
  5177. * @ngdoc method
  5178. * @name $animate#on
  5179. * @kind function
  5180. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  5181. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  5182. * is fired with the following params:
  5183. *
  5184. * ```js
  5185. * $animate.on('enter', container,
  5186. * function callback(element, phase) {
  5187. * // cool we detected an enter animation within the container
  5188. * }
  5189. * );
  5190. * ```
  5191. *
  5192. * <div class="alert alert-warning">
  5193. * **Note**: Generally, the events that are fired correspond 1:1 to `$animate` method names,
  5194. * e.g. {@link ng.$animate#addClass addClass()} will fire `addClass`, and {@link ng.ngClass}
  5195. * will fire `addClass` if classes are added, and `removeClass` if classes are removed.
  5196. * However, there are two exceptions:
  5197. *
  5198. * <ul>
  5199. * <li>if both an {@link ng.$animate#addClass addClass()} and a
  5200. * {@link ng.$animate#removeClass removeClass()} action are performed during the same
  5201. * animation, the event fired will be `setClass`. This is true even for `ngClass`.</li>
  5202. * <li>an {@link ng.$animate#animate animate()} call that adds and removes classes will fire
  5203. * the `setClass` event, but if it either removes or adds classes,
  5204. * it will fire `animate` instead.</li>
  5205. * </ul>
  5206. *
  5207. * </div>
  5208. *
  5209. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  5210. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  5211. * as well as among its children
  5212. * @param {Function} callback the callback function that will be fired when the listener is triggered.
  5213. *
  5214. * The arguments present in the callback function are:
  5215. * * `element` - The captured DOM element that the animation was fired on.
  5216. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  5217. * * `data` - an object with these properties:
  5218. * * addClass - `{string|null}` - space-separated CSS classes to add to the element
  5219. * * removeClass - `{string|null}` - space-separated CSS classes to remove from the element
  5220. * * from - `{Object|null}` - CSS properties & values at the beginning of the animation
  5221. * * to - `{Object|null}` - CSS properties & values at the end of the animation
  5222. *
  5223. * Note that the callback does not trigger a scope digest. Wrap your call into a
  5224. * {@link $rootScope.Scope#$apply scope.$apply} to propagate changes to the scope.
  5225. */
  5226. on: $$animateQueue.on,
  5227. /**
  5228. *
  5229. * @ngdoc method
  5230. * @name $animate#off
  5231. * @kind function
  5232. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  5233. * can be used in three different ways depending on the arguments:
  5234. *
  5235. * ```js
  5236. * // remove all the animation event listeners listening for `enter`
  5237. * $animate.off('enter');
  5238. *
  5239. * // remove listeners for all animation events from the container element
  5240. * $animate.off(container);
  5241. *
  5242. * // remove all the animation event listeners listening for `enter` on the given element and its children
  5243. * $animate.off('enter', container);
  5244. *
  5245. * // remove the event listener function provided by `callback` that is set
  5246. * // to listen for `enter` on the given `container` as well as its children
  5247. * $animate.off('enter', container, callback);
  5248. * ```
  5249. *
  5250. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  5251. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  5252. * arguments are ignored.
  5253. * @param {DOMElement=} container the container element the event listener was placed on
  5254. * @param {Function=} callback the callback function that was registered as the listener
  5255. */
  5256. off: $$animateQueue.off,
  5257. /**
  5258. * @ngdoc method
  5259. * @name $animate#pin
  5260. * @kind function
  5261. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  5262. * outside of the DOM structure of the AngularJS application. By doing so, any animation triggered via `$animate` can be issued on the
  5263. * element despite being outside the realm of the application or within another application. Say for example if the application
  5264. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  5265. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  5266. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  5267. *
  5268. * Note that this feature is only active when the `ngAnimate` module is used.
  5269. *
  5270. * @param {DOMElement} element the external element that will be pinned
  5271. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  5272. */
  5273. pin: $$animateQueue.pin,
  5274. /**
  5275. *
  5276. * @ngdoc method
  5277. * @name $animate#enabled
  5278. * @kind function
  5279. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  5280. * function can be called in four ways:
  5281. *
  5282. * ```js
  5283. * // returns true or false
  5284. * $animate.enabled();
  5285. *
  5286. * // changes the enabled state for all animations
  5287. * $animate.enabled(false);
  5288. * $animate.enabled(true);
  5289. *
  5290. * // returns true or false if animations are enabled for an element
  5291. * $animate.enabled(element);
  5292. *
  5293. * // changes the enabled state for an element and its children
  5294. * $animate.enabled(element, true);
  5295. * $animate.enabled(element, false);
  5296. * ```
  5297. *
  5298. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  5299. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  5300. *
  5301. * @return {boolean} whether or not animations are enabled
  5302. */
  5303. enabled: $$animateQueue.enabled,
  5304. /**
  5305. * @ngdoc method
  5306. * @name $animate#cancel
  5307. * @kind function
  5308. * @description Cancels the provided animation and applies the end state of the animation.
  5309. * Note that this does not cancel the underlying operation, e.g. the setting of classes or
  5310. * adding the element to the DOM.
  5311. *
  5312. * @param {animationRunner} animationRunner An animation runner returned by an $animate function.
  5313. *
  5314. * @example
  5315. <example module="animationExample" deps="angular-animate.js" animations="true" name="animate-cancel">
  5316. <file name="app.js">
  5317. angular.module('animationExample', ['ngAnimate']).component('cancelExample', {
  5318. templateUrl: 'template.html',
  5319. controller: function($element, $animate) {
  5320. this.runner = null;
  5321. this.addClass = function() {
  5322. this.runner = $animate.addClass($element.find('div'), 'red');
  5323. var ctrl = this;
  5324. this.runner.finally(function() {
  5325. ctrl.runner = null;
  5326. });
  5327. };
  5328. this.removeClass = function() {
  5329. this.runner = $animate.removeClass($element.find('div'), 'red');
  5330. var ctrl = this;
  5331. this.runner.finally(function() {
  5332. ctrl.runner = null;
  5333. });
  5334. };
  5335. this.cancel = function() {
  5336. $animate.cancel(this.runner);
  5337. };
  5338. }
  5339. });
  5340. </file>
  5341. <file name="template.html">
  5342. <p>
  5343. <button id="add" ng-click="$ctrl.addClass()">Add</button>
  5344. <button ng-click="$ctrl.removeClass()">Remove</button>
  5345. <br>
  5346. <button id="cancel" ng-click="$ctrl.cancel()" ng-disabled="!$ctrl.runner">Cancel</button>
  5347. <br>
  5348. <div id="target">CSS-Animated Text</div>
  5349. </p>
  5350. </file>
  5351. <file name="index.html">
  5352. <cancel-example></cancel-example>
  5353. </file>
  5354. <file name="style.css">
  5355. .red-add, .red-remove {
  5356. transition: all 4s cubic-bezier(0.250, 0.460, 0.450, 0.940);
  5357. }
  5358. .red,
  5359. .red-add.red-add-active {
  5360. color: #FF0000;
  5361. font-size: 40px;
  5362. }
  5363. .red-remove.red-remove-active {
  5364. font-size: 10px;
  5365. color: black;
  5366. }
  5367. </file>
  5368. </example>
  5369. */
  5370. cancel: function(runner) {
  5371. if (runner.cancel) {
  5372. runner.cancel();
  5373. }
  5374. },
  5375. /**
  5376. *
  5377. * @ngdoc method
  5378. * @name $animate#enter
  5379. * @kind function
  5380. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  5381. * as the first child within the `parent` element and then triggers an animation.
  5382. * A promise is returned that will be resolved during the next digest once the animation
  5383. * has completed.
  5384. *
  5385. * @param {DOMElement} element the element which will be inserted into the DOM
  5386. * @param {DOMElement} parent the parent element which will append the element as
  5387. * a child (so long as the after element is not present)
  5388. * @param {DOMElement=} after the sibling element after which the element will be appended
  5389. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5390. * The object can have the following properties:
  5391. *
  5392. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5393. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5394. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5395. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5396. *
  5397. * @return {Runner} the animation runner
  5398. */
  5399. enter: function(element, parent, after, options) {
  5400. parent = parent && jqLite(parent);
  5401. after = after && jqLite(after);
  5402. parent = parent || after.parent();
  5403. domInsert(element, parent, after);
  5404. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  5405. },
  5406. /**
  5407. *
  5408. * @ngdoc method
  5409. * @name $animate#move
  5410. * @kind function
  5411. * @description Inserts (moves) the element into its new position in the DOM either after
  5412. * the `after` element (if provided) or as the first child within the `parent` element
  5413. * and then triggers an animation. A promise is returned that will be resolved
  5414. * during the next digest once the animation has completed.
  5415. *
  5416. * @param {DOMElement} element the element which will be moved into the new DOM position
  5417. * @param {DOMElement} parent the parent element which will append the element as
  5418. * a child (so long as the after element is not present)
  5419. * @param {DOMElement=} after the sibling element after which the element will be appended
  5420. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5421. * The object can have the following properties:
  5422. *
  5423. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5424. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5425. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5426. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5427. *
  5428. * @return {Runner} the animation runner
  5429. */
  5430. move: function(element, parent, after, options) {
  5431. parent = parent && jqLite(parent);
  5432. after = after && jqLite(after);
  5433. parent = parent || after.parent();
  5434. domInsert(element, parent, after);
  5435. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  5436. },
  5437. /**
  5438. * @ngdoc method
  5439. * @name $animate#leave
  5440. * @kind function
  5441. * @description Triggers an animation and then removes the element from the DOM.
  5442. * When the function is called a promise is returned that will be resolved during the next
  5443. * digest once the animation has completed.
  5444. *
  5445. * @param {DOMElement} element the element which will be removed from the DOM
  5446. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5447. * The object can have the following properties:
  5448. *
  5449. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5450. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5451. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5452. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5453. *
  5454. * @return {Runner} the animation runner
  5455. */
  5456. leave: function(element, options) {
  5457. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  5458. element.remove();
  5459. });
  5460. },
  5461. /**
  5462. * @ngdoc method
  5463. * @name $animate#addClass
  5464. * @kind function
  5465. *
  5466. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  5467. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  5468. * animation if element already contains the CSS class or if the class is removed at a later step.
  5469. * Note that class-based animations are treated differently compared to structural animations
  5470. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5471. * depending if CSS or JavaScript animations are used.
  5472. *
  5473. * @param {DOMElement} element the element which the CSS classes will be applied to
  5474. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  5475. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5476. * The object can have the following properties:
  5477. *
  5478. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5479. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5480. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5481. *
  5482. * @return {Runner} animationRunner the animation runner
  5483. */
  5484. addClass: function(element, className, options) {
  5485. options = prepareAnimateOptions(options);
  5486. options.addClass = mergeClasses(options.addclass, className);
  5487. return $$animateQueue.push(element, 'addClass', options);
  5488. },
  5489. /**
  5490. * @ngdoc method
  5491. * @name $animate#removeClass
  5492. * @kind function
  5493. *
  5494. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  5495. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  5496. * animation if element does not contain the CSS class or if the class is added at a later step.
  5497. * Note that class-based animations are treated differently compared to structural animations
  5498. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5499. * depending if CSS or JavaScript animations are used.
  5500. *
  5501. * @param {DOMElement} element the element which the CSS classes will be applied to
  5502. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5503. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5504. * The object can have the following properties:
  5505. *
  5506. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5507. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5508. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5509. *
  5510. * @return {Runner} the animation runner
  5511. */
  5512. removeClass: function(element, className, options) {
  5513. options = prepareAnimateOptions(options);
  5514. options.removeClass = mergeClasses(options.removeClass, className);
  5515. return $$animateQueue.push(element, 'removeClass', options);
  5516. },
  5517. /**
  5518. * @ngdoc method
  5519. * @name $animate#setClass
  5520. * @kind function
  5521. *
  5522. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5523. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5524. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5525. * passed. Note that class-based animations are treated differently compared to structural animations
  5526. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5527. * depending if CSS or JavaScript animations are used.
  5528. *
  5529. * @param {DOMElement} element the element which the CSS classes will be applied to
  5530. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5531. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5532. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5533. * The object can have the following properties:
  5534. *
  5535. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5536. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5537. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5538. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5539. *
  5540. * @return {Runner} the animation runner
  5541. */
  5542. setClass: function(element, add, remove, options) {
  5543. options = prepareAnimateOptions(options);
  5544. options.addClass = mergeClasses(options.addClass, add);
  5545. options.removeClass = mergeClasses(options.removeClass, remove);
  5546. return $$animateQueue.push(element, 'setClass', options);
  5547. },
  5548. /**
  5549. * @ngdoc method
  5550. * @name $animate#animate
  5551. * @kind function
  5552. *
  5553. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5554. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5555. * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
  5556. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5557. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5558. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5559. * method (or as part of the `options` parameter):
  5560. *
  5561. * ```js
  5562. * ngModule.animation('.my-inline-animation', function() {
  5563. * return {
  5564. * animate : function(element, from, to, done, options) {
  5565. * //animation
  5566. * done();
  5567. * }
  5568. * }
  5569. * });
  5570. * ```
  5571. *
  5572. * @param {DOMElement} element the element which the CSS styles will be applied to
  5573. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5574. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5575. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5576. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5577. * (Note that if no animation is detected then this value will not be applied to the element.)
  5578. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5579. * The object can have the following properties:
  5580. *
  5581. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5582. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5583. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5584. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5585. *
  5586. * @return {Runner} the animation runner
  5587. */
  5588. animate: function(element, from, to, className, options) {
  5589. options = prepareAnimateOptions(options);
  5590. options.from = options.from ? extend(options.from, from) : from;
  5591. options.to = options.to ? extend(options.to, to) : to;
  5592. className = className || 'ng-inline-animate';
  5593. options.tempClasses = mergeClasses(options.tempClasses, className);
  5594. return $$animateQueue.push(element, 'animate', options);
  5595. }
  5596. };
  5597. }];
  5598. }];
  5599. var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
  5600. this.$get = ['$$rAF', function($$rAF) {
  5601. var waitQueue = [];
  5602. function waitForTick(fn) {
  5603. waitQueue.push(fn);
  5604. if (waitQueue.length > 1) return;
  5605. $$rAF(function() {
  5606. for (var i = 0; i < waitQueue.length; i++) {
  5607. waitQueue[i]();
  5608. }
  5609. waitQueue = [];
  5610. });
  5611. }
  5612. return function() {
  5613. var passed = false;
  5614. waitForTick(function() {
  5615. passed = true;
  5616. });
  5617. return function(callback) {
  5618. if (passed) {
  5619. callback();
  5620. } else {
  5621. waitForTick(callback);
  5622. }
  5623. };
  5624. };
  5625. }];
  5626. };
  5627. var $$AnimateRunnerFactoryProvider = /** @this */ function() {
  5628. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
  5629. function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
  5630. var INITIAL_STATE = 0;
  5631. var DONE_PENDING_STATE = 1;
  5632. var DONE_COMPLETE_STATE = 2;
  5633. AnimateRunner.chain = function(chain, callback) {
  5634. var index = 0;
  5635. next();
  5636. function next() {
  5637. if (index === chain.length) {
  5638. callback(true);
  5639. return;
  5640. }
  5641. chain[index](function(response) {
  5642. if (response === false) {
  5643. callback(false);
  5644. return;
  5645. }
  5646. index++;
  5647. next();
  5648. });
  5649. }
  5650. };
  5651. AnimateRunner.all = function(runners, callback) {
  5652. var count = 0;
  5653. var status = true;
  5654. forEach(runners, function(runner) {
  5655. runner.done(onProgress);
  5656. });
  5657. function onProgress(response) {
  5658. status = status && response;
  5659. if (++count === runners.length) {
  5660. callback(status);
  5661. }
  5662. }
  5663. };
  5664. function AnimateRunner(host) {
  5665. this.setHost(host);
  5666. var rafTick = $$animateAsyncRun();
  5667. var timeoutTick = function(fn) {
  5668. $timeout(fn, 0, false);
  5669. };
  5670. this._doneCallbacks = [];
  5671. this._tick = function(fn) {
  5672. if ($$isDocumentHidden()) {
  5673. timeoutTick(fn);
  5674. } else {
  5675. rafTick(fn);
  5676. }
  5677. };
  5678. this._state = 0;
  5679. }
  5680. AnimateRunner.prototype = {
  5681. setHost: function(host) {
  5682. this.host = host || {};
  5683. },
  5684. done: function(fn) {
  5685. if (this._state === DONE_COMPLETE_STATE) {
  5686. fn();
  5687. } else {
  5688. this._doneCallbacks.push(fn);
  5689. }
  5690. },
  5691. progress: noop,
  5692. getPromise: function() {
  5693. if (!this.promise) {
  5694. var self = this;
  5695. this.promise = $q(function(resolve, reject) {
  5696. self.done(function(status) {
  5697. if (status === false) {
  5698. reject();
  5699. } else {
  5700. resolve();
  5701. }
  5702. });
  5703. });
  5704. }
  5705. return this.promise;
  5706. },
  5707. then: function(resolveHandler, rejectHandler) {
  5708. return this.getPromise().then(resolveHandler, rejectHandler);
  5709. },
  5710. 'catch': function(handler) {
  5711. return this.getPromise()['catch'](handler);
  5712. },
  5713. 'finally': function(handler) {
  5714. return this.getPromise()['finally'](handler);
  5715. },
  5716. pause: function() {
  5717. if (this.host.pause) {
  5718. this.host.pause();
  5719. }
  5720. },
  5721. resume: function() {
  5722. if (this.host.resume) {
  5723. this.host.resume();
  5724. }
  5725. },
  5726. end: function() {
  5727. if (this.host.end) {
  5728. this.host.end();
  5729. }
  5730. this._resolve(true);
  5731. },
  5732. cancel: function() {
  5733. if (this.host.cancel) {
  5734. this.host.cancel();
  5735. }
  5736. this._resolve(false);
  5737. },
  5738. complete: function(response) {
  5739. var self = this;
  5740. if (self._state === INITIAL_STATE) {
  5741. self._state = DONE_PENDING_STATE;
  5742. self._tick(function() {
  5743. self._resolve(response);
  5744. });
  5745. }
  5746. },
  5747. _resolve: function(response) {
  5748. if (this._state !== DONE_COMPLETE_STATE) {
  5749. forEach(this._doneCallbacks, function(fn) {
  5750. fn(response);
  5751. });
  5752. this._doneCallbacks.length = 0;
  5753. this._state = DONE_COMPLETE_STATE;
  5754. }
  5755. }
  5756. };
  5757. return AnimateRunner;
  5758. }];
  5759. };
  5760. /* exported $CoreAnimateCssProvider */
  5761. /**
  5762. * @ngdoc service
  5763. * @name $animateCss
  5764. * @kind object
  5765. * @this
  5766. *
  5767. * @description
  5768. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5769. * then the `$animateCss` service will actually perform animations.
  5770. *
  5771. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5772. */
  5773. var $CoreAnimateCssProvider = function() {
  5774. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5775. return function(element, initialOptions) {
  5776. // all of the animation functions should create
  5777. // a copy of the options data, however, if a
  5778. // parent service has already created a copy then
  5779. // we should stick to using that
  5780. var options = initialOptions || {};
  5781. if (!options.$$prepared) {
  5782. options = copy(options);
  5783. }
  5784. // there is no point in applying the styles since
  5785. // there is no animation that goes on at all in
  5786. // this version of $animateCss.
  5787. if (options.cleanupStyles) {
  5788. options.from = options.to = null;
  5789. }
  5790. if (options.from) {
  5791. element.css(options.from);
  5792. options.from = null;
  5793. }
  5794. var closed, runner = new $$AnimateRunner();
  5795. return {
  5796. start: run,
  5797. end: run
  5798. };
  5799. function run() {
  5800. $$rAF(function() {
  5801. applyAnimationContents();
  5802. if (!closed) {
  5803. runner.complete();
  5804. }
  5805. closed = true;
  5806. });
  5807. return runner;
  5808. }
  5809. function applyAnimationContents() {
  5810. if (options.addClass) {
  5811. element.addClass(options.addClass);
  5812. options.addClass = null;
  5813. }
  5814. if (options.removeClass) {
  5815. element.removeClass(options.removeClass);
  5816. options.removeClass = null;
  5817. }
  5818. if (options.to) {
  5819. element.css(options.to);
  5820. options.to = null;
  5821. }
  5822. }
  5823. };
  5824. }];
  5825. };
  5826. /* global getHash: true, stripHash: false */
  5827. function getHash(url) {
  5828. var index = url.indexOf('#');
  5829. return index === -1 ? '' : url.substr(index);
  5830. }
  5831. function trimEmptyHash(url) {
  5832. return url.replace(/#$/, '');
  5833. }
  5834. /**
  5835. * ! This is a private undocumented service !
  5836. *
  5837. * @name $browser
  5838. * @requires $log
  5839. * @description
  5840. * This object has two goals:
  5841. *
  5842. * - hide all the global state in the browser caused by the window object
  5843. * - abstract away all the browser specific features and inconsistencies
  5844. *
  5845. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5846. * service, which can be used for convenient testing of the application without the interaction with
  5847. * the real browser apis.
  5848. */
  5849. /**
  5850. * @param {object} window The global window object.
  5851. * @param {object} document jQuery wrapped document.
  5852. * @param {object} $log window.console or an object with the same interface.
  5853. * @param {object} $sniffer $sniffer service
  5854. */
  5855. function Browser(window, document, $log, $sniffer, $$taskTrackerFactory) {
  5856. var self = this,
  5857. location = window.location,
  5858. history = window.history,
  5859. setTimeout = window.setTimeout,
  5860. clearTimeout = window.clearTimeout,
  5861. pendingDeferIds = {},
  5862. taskTracker = $$taskTrackerFactory($log);
  5863. self.isMock = false;
  5864. //////////////////////////////////////////////////////////////
  5865. // Task-tracking API
  5866. //////////////////////////////////////////////////////////////
  5867. // TODO(vojta): remove this temporary api
  5868. self.$$completeOutstandingRequest = taskTracker.completeTask;
  5869. self.$$incOutstandingRequestCount = taskTracker.incTaskCount;
  5870. // TODO(vojta): prefix this method with $$ ?
  5871. self.notifyWhenNoOutstandingRequests = taskTracker.notifyWhenNoPendingTasks;
  5872. //////////////////////////////////////////////////////////////
  5873. // URL API
  5874. //////////////////////////////////////////////////////////////
  5875. var cachedState, lastHistoryState,
  5876. lastBrowserUrl = location.href,
  5877. baseElement = document.find('base'),
  5878. pendingLocation = null,
  5879. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5880. try {
  5881. return history.state;
  5882. } catch (e) {
  5883. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5884. }
  5885. };
  5886. cacheState();
  5887. /**
  5888. * @name $browser#url
  5889. *
  5890. * @description
  5891. * GETTER:
  5892. * Without any argument, this method just returns current value of `location.href` (with a
  5893. * trailing `#` stripped of if the hash is empty).
  5894. *
  5895. * SETTER:
  5896. * With at least one argument, this method sets url to new value.
  5897. * If html5 history api supported, `pushState`/`replaceState` is used, otherwise
  5898. * `location.href`/`location.replace` is used.
  5899. * Returns its own instance to allow chaining.
  5900. *
  5901. * NOTE: this api is intended for use only by the `$location` service. Please use the
  5902. * {@link ng.$location $location service} to change url.
  5903. *
  5904. * @param {string} url New url (when used as setter)
  5905. * @param {boolean=} replace Should new url replace current history record?
  5906. * @param {object=} state State object to use with `pushState`/`replaceState`
  5907. */
  5908. self.url = function(url, replace, state) {
  5909. // In modern browsers `history.state` is `null` by default; treating it separately
  5910. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5911. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5912. if (isUndefined(state)) {
  5913. state = null;
  5914. }
  5915. // Android Browser BFCache causes location, history reference to become stale.
  5916. if (location !== window.location) location = window.location;
  5917. if (history !== window.history) history = window.history;
  5918. // setter
  5919. if (url) {
  5920. var sameState = lastHistoryState === state;
  5921. // Don't change anything if previous and current URLs and states match. This also prevents
  5922. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5923. // See https://github.com/angular/angular.js/commit/ffb2701
  5924. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5925. return self;
  5926. }
  5927. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5928. lastBrowserUrl = url;
  5929. lastHistoryState = state;
  5930. // Don't use history API if only the hash changed
  5931. // due to a bug in IE10/IE11 which leads
  5932. // to not firing a `hashchange` nor `popstate` event
  5933. // in some cases (see #9143).
  5934. if ($sniffer.history && (!sameBase || !sameState)) {
  5935. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5936. cacheState();
  5937. } else {
  5938. if (!sameBase) {
  5939. pendingLocation = url;
  5940. }
  5941. if (replace) {
  5942. location.replace(url);
  5943. } else if (!sameBase) {
  5944. location.href = url;
  5945. } else {
  5946. location.hash = getHash(url);
  5947. }
  5948. if (location.href !== url) {
  5949. pendingLocation = url;
  5950. }
  5951. }
  5952. if (pendingLocation) {
  5953. pendingLocation = url;
  5954. }
  5955. return self;
  5956. // getter
  5957. } else {
  5958. // - pendingLocation is needed as browsers don't allow to read out
  5959. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5960. // https://openradar.appspot.com/22186109).
  5961. return trimEmptyHash(pendingLocation || location.href);
  5962. }
  5963. };
  5964. /**
  5965. * @name $browser#state
  5966. *
  5967. * @description
  5968. * This method is a getter.
  5969. *
  5970. * Return history.state or null if history.state is undefined.
  5971. *
  5972. * @returns {object} state
  5973. */
  5974. self.state = function() {
  5975. return cachedState;
  5976. };
  5977. var urlChangeListeners = [],
  5978. urlChangeInit = false;
  5979. function cacheStateAndFireUrlChange() {
  5980. pendingLocation = null;
  5981. fireStateOrUrlChange();
  5982. }
  5983. // This variable should be used *only* inside the cacheState function.
  5984. var lastCachedState = null;
  5985. function cacheState() {
  5986. // This should be the only place in $browser where `history.state` is read.
  5987. cachedState = getCurrentState();
  5988. cachedState = isUndefined(cachedState) ? null : cachedState;
  5989. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5990. if (equals(cachedState, lastCachedState)) {
  5991. cachedState = lastCachedState;
  5992. }
  5993. lastCachedState = cachedState;
  5994. lastHistoryState = cachedState;
  5995. }
  5996. function fireStateOrUrlChange() {
  5997. var prevLastHistoryState = lastHistoryState;
  5998. cacheState();
  5999. if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {
  6000. return;
  6001. }
  6002. lastBrowserUrl = self.url();
  6003. lastHistoryState = cachedState;
  6004. forEach(urlChangeListeners, function(listener) {
  6005. listener(self.url(), cachedState);
  6006. });
  6007. }
  6008. /**
  6009. * @name $browser#onUrlChange
  6010. *
  6011. * @description
  6012. * Register callback function that will be called, when url changes.
  6013. *
  6014. * It's only called when the url is changed from outside of AngularJS:
  6015. * - user types different url into address bar
  6016. * - user clicks on history (forward/back) button
  6017. * - user clicks on a link
  6018. *
  6019. * It's not called when url is changed by $browser.url() method
  6020. *
  6021. * The listener gets called with new url as parameter.
  6022. *
  6023. * NOTE: this api is intended for use only by the $location service. Please use the
  6024. * {@link ng.$location $location service} to monitor url changes in AngularJS apps.
  6025. *
  6026. * @param {function(string)} listener Listener function to be called when url changes.
  6027. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  6028. */
  6029. self.onUrlChange = function(callback) {
  6030. // TODO(vojta): refactor to use node's syntax for events
  6031. if (!urlChangeInit) {
  6032. // We listen on both (hashchange/popstate) when available, as some browsers don't
  6033. // fire popstate when user changes the address bar and don't fire hashchange when url
  6034. // changed by push/replaceState
  6035. // html5 history api - popstate event
  6036. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  6037. // hashchange event
  6038. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  6039. urlChangeInit = true;
  6040. }
  6041. urlChangeListeners.push(callback);
  6042. return callback;
  6043. };
  6044. /**
  6045. * @private
  6046. * Remove popstate and hashchange handler from window.
  6047. *
  6048. * NOTE: this api is intended for use only by $rootScope.
  6049. */
  6050. self.$$applicationDestroyed = function() {
  6051. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  6052. };
  6053. /**
  6054. * Checks whether the url has changed outside of AngularJS.
  6055. * Needs to be exported to be able to check for changes that have been done in sync,
  6056. * as hashchange/popstate events fire in async.
  6057. */
  6058. self.$$checkUrlChange = fireStateOrUrlChange;
  6059. //////////////////////////////////////////////////////////////
  6060. // Misc API
  6061. //////////////////////////////////////////////////////////////
  6062. /**
  6063. * @name $browser#baseHref
  6064. *
  6065. * @description
  6066. * Returns current <base href>
  6067. * (always relative - without domain)
  6068. *
  6069. * @returns {string} The current base href
  6070. */
  6071. self.baseHref = function() {
  6072. var href = baseElement.attr('href');
  6073. return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
  6074. };
  6075. /**
  6076. * @name $browser#defer
  6077. * @param {function()} fn A function, who's execution should be deferred.
  6078. * @param {number=} [delay=0] Number of milliseconds to defer the function execution.
  6079. * @param {string=} [taskType=DEFAULT_TASK_TYPE] The type of task that is deferred.
  6080. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  6081. *
  6082. * @description
  6083. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  6084. *
  6085. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  6086. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  6087. * via `$browser.defer.flush()`.
  6088. *
  6089. */
  6090. self.defer = function(fn, delay, taskType) {
  6091. var timeoutId;
  6092. delay = delay || 0;
  6093. taskType = taskType || taskTracker.DEFAULT_TASK_TYPE;
  6094. taskTracker.incTaskCount(taskType);
  6095. timeoutId = setTimeout(function() {
  6096. delete pendingDeferIds[timeoutId];
  6097. taskTracker.completeTask(fn, taskType);
  6098. }, delay);
  6099. pendingDeferIds[timeoutId] = taskType;
  6100. return timeoutId;
  6101. };
  6102. /**
  6103. * @name $browser#defer.cancel
  6104. *
  6105. * @description
  6106. * Cancels a deferred task identified with `deferId`.
  6107. *
  6108. * @param {*} deferId Token returned by the `$browser.defer` function.
  6109. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  6110. * canceled.
  6111. */
  6112. self.defer.cancel = function(deferId) {
  6113. if (pendingDeferIds.hasOwnProperty(deferId)) {
  6114. var taskType = pendingDeferIds[deferId];
  6115. delete pendingDeferIds[deferId];
  6116. clearTimeout(deferId);
  6117. taskTracker.completeTask(noop, taskType);
  6118. return true;
  6119. }
  6120. return false;
  6121. };
  6122. }
  6123. /** @this */
  6124. function $BrowserProvider() {
  6125. this.$get = ['$window', '$log', '$sniffer', '$document', '$$taskTrackerFactory',
  6126. function($window, $log, $sniffer, $document, $$taskTrackerFactory) {
  6127. return new Browser($window, $document, $log, $sniffer, $$taskTrackerFactory);
  6128. }];
  6129. }
  6130. /**
  6131. * @ngdoc service
  6132. * @name $cacheFactory
  6133. * @this
  6134. *
  6135. * @description
  6136. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  6137. * them.
  6138. *
  6139. * ```js
  6140. *
  6141. * var cache = $cacheFactory('cacheId');
  6142. * expect($cacheFactory.get('cacheId')).toBe(cache);
  6143. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  6144. *
  6145. * cache.put("key", "value");
  6146. * cache.put("another key", "another value");
  6147. *
  6148. * // We've specified no options on creation
  6149. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  6150. *
  6151. * ```
  6152. *
  6153. *
  6154. * @param {string} cacheId Name or id of the newly created cache.
  6155. * @param {object=} options Options object that specifies the cache behavior. Properties:
  6156. *
  6157. * - `{number=}` `capacity` — turns the cache into LRU cache.
  6158. *
  6159. * @returns {object} Newly created cache object with the following set of methods:
  6160. *
  6161. * - `{object}` `info()` — Returns id, size, and options of cache.
  6162. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  6163. * it.
  6164. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  6165. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  6166. * - `{void}` `removeAll()` — Removes all cached values.
  6167. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  6168. *
  6169. * @example
  6170. <example module="cacheExampleApp" name="cache-factory">
  6171. <file name="index.html">
  6172. <div ng-controller="CacheController">
  6173. <input ng-model="newCacheKey" placeholder="Key">
  6174. <input ng-model="newCacheValue" placeholder="Value">
  6175. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  6176. <p ng-if="keys.length">Cached Values</p>
  6177. <div ng-repeat="key in keys">
  6178. <span ng-bind="key"></span>
  6179. <span>: </span>
  6180. <b ng-bind="cache.get(key)"></b>
  6181. </div>
  6182. <p>Cache Info</p>
  6183. <div ng-repeat="(key, value) in cache.info()">
  6184. <span ng-bind="key"></span>
  6185. <span>: </span>
  6186. <b ng-bind="value"></b>
  6187. </div>
  6188. </div>
  6189. </file>
  6190. <file name="script.js">
  6191. angular.module('cacheExampleApp', []).
  6192. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  6193. $scope.keys = [];
  6194. $scope.cache = $cacheFactory('cacheId');
  6195. $scope.put = function(key, value) {
  6196. if (angular.isUndefined($scope.cache.get(key))) {
  6197. $scope.keys.push(key);
  6198. }
  6199. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  6200. };
  6201. }]);
  6202. </file>
  6203. <file name="style.css">
  6204. p {
  6205. margin: 10px 0 3px;
  6206. }
  6207. </file>
  6208. </example>
  6209. */
  6210. function $CacheFactoryProvider() {
  6211. this.$get = function() {
  6212. var caches = {};
  6213. function cacheFactory(cacheId, options) {
  6214. if (cacheId in caches) {
  6215. throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
  6216. }
  6217. var size = 0,
  6218. stats = extend({}, options, {id: cacheId}),
  6219. data = createMap(),
  6220. capacity = (options && options.capacity) || Number.MAX_VALUE,
  6221. lruHash = createMap(),
  6222. freshEnd = null,
  6223. staleEnd = null;
  6224. /**
  6225. * @ngdoc type
  6226. * @name $cacheFactory.Cache
  6227. *
  6228. * @description
  6229. * A cache object used to store and retrieve data, primarily used by
  6230. * {@link $templateRequest $templateRequest} and the {@link ng.directive:script script}
  6231. * directive to cache templates and other data.
  6232. *
  6233. * ```js
  6234. * angular.module('superCache')
  6235. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  6236. * return $cacheFactory('super-cache');
  6237. * }]);
  6238. * ```
  6239. *
  6240. * Example test:
  6241. *
  6242. * ```js
  6243. * it('should behave like a cache', inject(function(superCache) {
  6244. * superCache.put('key', 'value');
  6245. * superCache.put('another key', 'another value');
  6246. *
  6247. * expect(superCache.info()).toEqual({
  6248. * id: 'super-cache',
  6249. * size: 2
  6250. * });
  6251. *
  6252. * superCache.remove('another key');
  6253. * expect(superCache.get('another key')).toBeUndefined();
  6254. *
  6255. * superCache.removeAll();
  6256. * expect(superCache.info()).toEqual({
  6257. * id: 'super-cache',
  6258. * size: 0
  6259. * });
  6260. * }));
  6261. * ```
  6262. */
  6263. return (caches[cacheId] = {
  6264. /**
  6265. * @ngdoc method
  6266. * @name $cacheFactory.Cache#put
  6267. * @kind function
  6268. *
  6269. * @description
  6270. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  6271. * retrieved later, and incrementing the size of the cache if the key was not already
  6272. * present in the cache. If behaving like an LRU cache, it will also remove stale
  6273. * entries from the set.
  6274. *
  6275. * It will not insert undefined values into the cache.
  6276. *
  6277. * @param {string} key the key under which the cached data is stored.
  6278. * @param {*} value the value to store alongside the key. If it is undefined, the key
  6279. * will not be stored.
  6280. * @returns {*} the value stored.
  6281. */
  6282. put: function(key, value) {
  6283. if (isUndefined(value)) return;
  6284. if (capacity < Number.MAX_VALUE) {
  6285. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  6286. refresh(lruEntry);
  6287. }
  6288. if (!(key in data)) size++;
  6289. data[key] = value;
  6290. if (size > capacity) {
  6291. this.remove(staleEnd.key);
  6292. }
  6293. return value;
  6294. },
  6295. /**
  6296. * @ngdoc method
  6297. * @name $cacheFactory.Cache#get
  6298. * @kind function
  6299. *
  6300. * @description
  6301. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  6302. *
  6303. * @param {string} key the key of the data to be retrieved
  6304. * @returns {*} the value stored.
  6305. */
  6306. get: function(key) {
  6307. if (capacity < Number.MAX_VALUE) {
  6308. var lruEntry = lruHash[key];
  6309. if (!lruEntry) return;
  6310. refresh(lruEntry);
  6311. }
  6312. return data[key];
  6313. },
  6314. /**
  6315. * @ngdoc method
  6316. * @name $cacheFactory.Cache#remove
  6317. * @kind function
  6318. *
  6319. * @description
  6320. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  6321. *
  6322. * @param {string} key the key of the entry to be removed
  6323. */
  6324. remove: function(key) {
  6325. if (capacity < Number.MAX_VALUE) {
  6326. var lruEntry = lruHash[key];
  6327. if (!lruEntry) return;
  6328. if (lruEntry === freshEnd) freshEnd = lruEntry.p;
  6329. if (lruEntry === staleEnd) staleEnd = lruEntry.n;
  6330. link(lruEntry.n,lruEntry.p);
  6331. delete lruHash[key];
  6332. }
  6333. if (!(key in data)) return;
  6334. delete data[key];
  6335. size--;
  6336. },
  6337. /**
  6338. * @ngdoc method
  6339. * @name $cacheFactory.Cache#removeAll
  6340. * @kind function
  6341. *
  6342. * @description
  6343. * Clears the cache object of any entries.
  6344. */
  6345. removeAll: function() {
  6346. data = createMap();
  6347. size = 0;
  6348. lruHash = createMap();
  6349. freshEnd = staleEnd = null;
  6350. },
  6351. /**
  6352. * @ngdoc method
  6353. * @name $cacheFactory.Cache#destroy
  6354. * @kind function
  6355. *
  6356. * @description
  6357. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  6358. * removing it from the {@link $cacheFactory $cacheFactory} set.
  6359. */
  6360. destroy: function() {
  6361. data = null;
  6362. stats = null;
  6363. lruHash = null;
  6364. delete caches[cacheId];
  6365. },
  6366. /**
  6367. * @ngdoc method
  6368. * @name $cacheFactory.Cache#info
  6369. * @kind function
  6370. *
  6371. * @description
  6372. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  6373. *
  6374. * @returns {object} an object with the following properties:
  6375. * <ul>
  6376. * <li>**id**: the id of the cache instance</li>
  6377. * <li>**size**: the number of entries kept in the cache instance</li>
  6378. * <li>**...**: any additional properties from the options object when creating the
  6379. * cache.</li>
  6380. * </ul>
  6381. */
  6382. info: function() {
  6383. return extend({}, stats, {size: size});
  6384. }
  6385. });
  6386. /**
  6387. * makes the `entry` the freshEnd of the LRU linked list
  6388. */
  6389. function refresh(entry) {
  6390. if (entry !== freshEnd) {
  6391. if (!staleEnd) {
  6392. staleEnd = entry;
  6393. } else if (staleEnd === entry) {
  6394. staleEnd = entry.n;
  6395. }
  6396. link(entry.n, entry.p);
  6397. link(entry, freshEnd);
  6398. freshEnd = entry;
  6399. freshEnd.n = null;
  6400. }
  6401. }
  6402. /**
  6403. * bidirectionally links two entries of the LRU linked list
  6404. */
  6405. function link(nextEntry, prevEntry) {
  6406. if (nextEntry !== prevEntry) {
  6407. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  6408. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  6409. }
  6410. }
  6411. }
  6412. /**
  6413. * @ngdoc method
  6414. * @name $cacheFactory#info
  6415. *
  6416. * @description
  6417. * Get information about all the caches that have been created
  6418. *
  6419. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  6420. */
  6421. cacheFactory.info = function() {
  6422. var info = {};
  6423. forEach(caches, function(cache, cacheId) {
  6424. info[cacheId] = cache.info();
  6425. });
  6426. return info;
  6427. };
  6428. /**
  6429. * @ngdoc method
  6430. * @name $cacheFactory#get
  6431. *
  6432. * @description
  6433. * Get access to a cache object by the `cacheId` used when it was created.
  6434. *
  6435. * @param {string} cacheId Name or id of a cache to access.
  6436. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  6437. */
  6438. cacheFactory.get = function(cacheId) {
  6439. return caches[cacheId];
  6440. };
  6441. return cacheFactory;
  6442. };
  6443. }
  6444. /**
  6445. * @ngdoc service
  6446. * @name $templateCache
  6447. * @this
  6448. *
  6449. * @description
  6450. * `$templateCache` is a {@link $cacheFactory.Cache Cache object} created by the
  6451. * {@link ng.$cacheFactory $cacheFactory}.
  6452. *
  6453. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  6454. * can load templates directly into the cache in a `script` tag, by using {@link $templateRequest},
  6455. * or by consuming the `$templateCache` service directly.
  6456. *
  6457. * Adding via the `script` tag:
  6458. *
  6459. * ```html
  6460. * <script type="text/ng-template" id="templateId.html">
  6461. * <p>This is the content of the template</p>
  6462. * </script>
  6463. * ```
  6464. *
  6465. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  6466. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (e.g.
  6467. * element with {@link ngApp} attribute), otherwise the template will be ignored.
  6468. *
  6469. * Adding via the `$templateCache` service:
  6470. *
  6471. * ```js
  6472. * var myApp = angular.module('myApp', []);
  6473. * myApp.run(function($templateCache) {
  6474. * $templateCache.put('templateId.html', 'This is the content of the template');
  6475. * });
  6476. * ```
  6477. *
  6478. * To retrieve the template later, simply use it in your component:
  6479. * ```js
  6480. * myApp.component('myComponent', {
  6481. * templateUrl: 'templateId.html'
  6482. * });
  6483. * ```
  6484. *
  6485. * or get it via the `$templateCache` service:
  6486. * ```js
  6487. * $templateCache.get('templateId.html')
  6488. * ```
  6489. *
  6490. */
  6491. function $TemplateCacheProvider() {
  6492. this.$get = ['$cacheFactory', function($cacheFactory) {
  6493. return $cacheFactory('templates');
  6494. }];
  6495. }
  6496. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  6497. * Any commits to this file should be reviewed with security in mind. *
  6498. * Changes to this file can potentially create security vulnerabilities. *
  6499. * An approval from 2 Core members with history of modifying *
  6500. * this file is required. *
  6501. * *
  6502. * Does the change somehow allow for arbitrary javascript to be executed? *
  6503. * Or allows for someone to change the prototype of built-in objects? *
  6504. * Or gives undesired access to variables like document or window? *
  6505. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  6506. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  6507. *
  6508. * DOM-related variables:
  6509. *
  6510. * - "node" - DOM Node
  6511. * - "element" - DOM Element or Node
  6512. * - "$node" or "$element" - jqLite-wrapped node or element
  6513. *
  6514. *
  6515. * Compiler related stuff:
  6516. *
  6517. * - "linkFn" - linking fn of a single directive
  6518. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6519. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6520. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6521. */
  6522. /**
  6523. * @ngdoc service
  6524. * @name $compile
  6525. * @kind function
  6526. *
  6527. * @description
  6528. * Compiles an HTML string or DOM into a template and produces a template function, which
  6529. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6530. *
  6531. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6532. * {@link ng.$compileProvider#directive directives}.
  6533. *
  6534. * <div class="alert alert-warning">
  6535. * **Note:** This document is an in-depth reference of all directive options.
  6536. * For a gentle introduction to directives with examples of common use cases,
  6537. * see the {@link guide/directive directive guide}.
  6538. * </div>
  6539. *
  6540. * ## Comprehensive Directive API
  6541. *
  6542. * There are many different options for a directive.
  6543. *
  6544. * The difference resides in the return value of the factory function.
  6545. * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
  6546. * that defines the directive properties, or just the `postLink` function (all other properties will have
  6547. * the default values).
  6548. *
  6549. * <div class="alert alert-success">
  6550. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6551. * </div>
  6552. *
  6553. * Here's an example directive declared with a Directive Definition Object:
  6554. *
  6555. * ```js
  6556. * var myModule = angular.module(...);
  6557. *
  6558. * myModule.directive('directiveName', function factory(injectables) {
  6559. * var directiveDefinitionObject = {
  6560. * {@link $compile#-priority- priority}: 0,
  6561. * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6562. * // or
  6563. * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6564. * {@link $compile#-transclude- transclude}: false,
  6565. * {@link $compile#-restrict- restrict}: 'A',
  6566. * {@link $compile#-templatenamespace- templateNamespace}: 'html',
  6567. * {@link $compile#-scope- scope}: false,
  6568. * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6569. * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
  6570. * {@link $compile#-bindtocontroller- bindToController}: false,
  6571. * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6572. * {@link $compile#-multielement- multiElement}: false,
  6573. * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
  6574. * return {
  6575. * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6576. * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6577. * }
  6578. * // or
  6579. * // return function postLink( ... ) { ... }
  6580. * },
  6581. * // or
  6582. * // {@link $compile#-link- link}: {
  6583. * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6584. * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6585. * // }
  6586. * // or
  6587. * // {@link $compile#-link- link}: function postLink( ... ) { ... }
  6588. * };
  6589. * return directiveDefinitionObject;
  6590. * });
  6591. * ```
  6592. *
  6593. * <div class="alert alert-warning">
  6594. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6595. * </div>
  6596. *
  6597. * Therefore the above can be simplified as:
  6598. *
  6599. * ```js
  6600. * var myModule = angular.module(...);
  6601. *
  6602. * myModule.directive('directiveName', function factory(injectables) {
  6603. * var directiveDefinitionObject = {
  6604. * link: function postLink(scope, iElement, iAttrs) { ... }
  6605. * };
  6606. * return directiveDefinitionObject;
  6607. * // or
  6608. * // return function postLink(scope, iElement, iAttrs) { ... }
  6609. * });
  6610. * ```
  6611. *
  6612. * ### Life-cycle hooks
  6613. * Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the
  6614. * directive:
  6615. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6616. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6617. * this element). This is a good place to put initialization code for your controller.
  6618. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6619. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6620. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6621. * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will
  6622. * also be called when your bindings are initialized.
  6623. * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
  6624. * changes. Any actions that you wish to take in response to the changes that you detect must be
  6625. * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
  6626. * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
  6627. * be detected by AngularJS's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
  6628. * if detecting changes, you must store the previous value(s) for comparison to the current values.
  6629. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6630. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6631. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6632. * components will have their `$onDestroy()` hook called before child components.
  6633. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6634. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6635. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6636. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6637. * suspended until that occurs.
  6638. *
  6639. * #### Comparison with life-cycle hooks in the new Angular
  6640. * The new Angular also uses life-cycle hooks for its components. While the AngularJS life-cycle hooks are similar there are
  6641. * some differences that you should be aware of, especially when it comes to moving your code from AngularJS to Angular:
  6642. *
  6643. * * AngularJS hooks are prefixed with `$`, such as `$onInit`. Angular hooks are prefixed with `ng`, such as `ngOnInit`.
  6644. * * AngularJS hooks can be defined on the controller prototype or added to the controller inside its constructor.
  6645. * In Angular you can only define hooks on the prototype of the Component class.
  6646. * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in AngularJS than you would to
  6647. * `ngDoCheck` in Angular.
  6648. * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
  6649. * propagated throughout the application.
  6650. * Angular does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
  6651. * error or do nothing depending upon the state of `enableProdMode()`.
  6652. *
  6653. * #### Life-cycle hook examples
  6654. *
  6655. * This example shows how you can check for mutations to a Date object even though the identity of the object
  6656. * has not changed.
  6657. *
  6658. * <example name="doCheckDateExample" module="do-check-module">
  6659. * <file name="app.js">
  6660. * angular.module('do-check-module', [])
  6661. * .component('app', {
  6662. * template:
  6663. * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
  6664. * 'Date: {{ $ctrl.date }}' +
  6665. * '<test date="$ctrl.date"></test>',
  6666. * controller: function() {
  6667. * this.date = new Date();
  6668. * this.month = this.date.getMonth();
  6669. * this.updateDate = function() {
  6670. * this.date.setMonth(this.month);
  6671. * };
  6672. * }
  6673. * })
  6674. * .component('test', {
  6675. * bindings: { date: '<' },
  6676. * template:
  6677. * '<pre>{{ $ctrl.log | json }}</pre>',
  6678. * controller: function() {
  6679. * var previousValue;
  6680. * this.log = [];
  6681. * this.$doCheck = function() {
  6682. * var currentValue = this.date && this.date.valueOf();
  6683. * if (previousValue !== currentValue) {
  6684. * this.log.push('doCheck: date mutated: ' + this.date);
  6685. * previousValue = currentValue;
  6686. * }
  6687. * };
  6688. * }
  6689. * });
  6690. * </file>
  6691. * <file name="index.html">
  6692. * <app></app>
  6693. * </file>
  6694. * </example>
  6695. *
  6696. * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
  6697. * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
  6698. * arrays or objects can have a negative impact on your application performance)
  6699. *
  6700. * <example name="doCheckArrayExample" module="do-check-module">
  6701. * <file name="index.html">
  6702. * <div ng-init="items = []">
  6703. * <button ng-click="items.push(items.length)">Add Item</button>
  6704. * <button ng-click="items = []">Reset Items</button>
  6705. * <pre>{{ items }}</pre>
  6706. * <test items="items"></test>
  6707. * </div>
  6708. * </file>
  6709. * <file name="app.js">
  6710. * angular.module('do-check-module', [])
  6711. * .component('test', {
  6712. * bindings: { items: '<' },
  6713. * template:
  6714. * '<pre>{{ $ctrl.log | json }}</pre>',
  6715. * controller: function() {
  6716. * this.log = [];
  6717. *
  6718. * this.$doCheck = function() {
  6719. * if (this.items_ref !== this.items) {
  6720. * this.log.push('doCheck: items changed');
  6721. * this.items_ref = this.items;
  6722. * }
  6723. * if (!angular.equals(this.items_clone, this.items)) {
  6724. * this.log.push('doCheck: items mutated');
  6725. * this.items_clone = angular.copy(this.items);
  6726. * }
  6727. * };
  6728. * }
  6729. * });
  6730. * </file>
  6731. * </example>
  6732. *
  6733. *
  6734. * ### Directive Definition Object
  6735. *
  6736. * The directive definition object provides instructions to the {@link ng.$compile
  6737. * compiler}. The attributes are:
  6738. *
  6739. * #### `multiElement`
  6740. * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
  6741. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6742. * together as the directive elements. It is recommended that this feature be used on directives
  6743. * which are not strictly behavioral (such as {@link ngClick}), and which
  6744. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6745. *
  6746. * #### `priority`
  6747. * When there are multiple directives defined on a single DOM element, sometimes it
  6748. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6749. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6750. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6751. * are also run in priority order, but post-link functions are run in reverse order. The order
  6752. * of directives with the same priority is undefined. The default priority is `0`.
  6753. *
  6754. * #### `terminal`
  6755. * If set to true then the current `priority` will be the last set of directives
  6756. * which will execute (any directives at the current priority will still execute
  6757. * as the order of execution on same `priority` is undefined). Note that expressions
  6758. * and other directives used in the directive's template will also be excluded from execution.
  6759. *
  6760. * #### `scope`
  6761. * The scope property can be `false`, `true`, or an object:
  6762. *
  6763. * * **`false` (default):** No scope will be created for the directive. The directive will use its
  6764. * parent's scope.
  6765. *
  6766. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6767. * the directive's element. If multiple directives on the same element request a new scope,
  6768. * only one new scope is created.
  6769. *
  6770. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template.
  6771. * The 'isolate' scope differs from normal scope in that it does not prototypically
  6772. * inherit from its parent scope. This is useful when creating reusable components, which should not
  6773. * accidentally read or modify data in the parent scope. Note that an isolate scope
  6774. * directive without a `template` or `templateUrl` will not apply the isolate scope
  6775. * to its children elements.
  6776. *
  6777. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6778. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6779. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6780. * is bound to the parent scope, via matching attributes on the directive's element:
  6781. *
  6782. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6783. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6784. * attribute name is assumed to be the same as the local name. Given `<my-component
  6785. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6786. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6787. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6788. * scope. The `name` is read from the parent scope (not the directive's scope).
  6789. *
  6790. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6791. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6792. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6793. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6794. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6795. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6796. * `localModel` and vice versa. If the binding expression is non-assignable, or if the attribute
  6797. * isn't optional and doesn't exist, an exception
  6798. * ({@link error/$compile/nonassign `$compile:nonassign`}) will be thrown upon discovering changes
  6799. * to the local value, since it will be impossible to sync them back to the parent scope.
  6800. *
  6801. * By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6802. * method is used for tracking changes, and the equality check is based on object identity.
  6803. * However, if an object literal or an array literal is passed as the binding expression, the
  6804. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6805. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6806. * `$watchCollection`}: use `=*` or `=*attr`
  6807. *
  6808. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6809. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6810. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6811. * local name.
  6812. *
  6813. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6814. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6815. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6816. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6817. * two caveats:
  6818. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6819. * sets the same value. That means if your bound value is an object, changes to its properties
  6820. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6821. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6822. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6823. * to the value has changed. In most cases, this should not be of concern, but can be important
  6824. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6825. * If you now change a property of the object in your parent scope, the change will not be
  6826. * propagated to the isolated scope, because the identity of the object on the parent scope
  6827. * has not changed. Instead you must assign a new object.
  6828. *
  6829. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6830. * back to the parent. However, it does not make this completely impossible.
  6831. *
  6832. * By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6833. * method is used for tracking changes, and the equality check is based on object identity.
  6834. * It's also possible to watch the evaluated value shallowly with
  6835. * {@link ng.$rootScope.Scope#$watchCollection `$watchCollection`}: use `<*` or `<*attr`
  6836. *
  6837. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6838. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6839. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6840. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6841. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6842. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6843. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6844. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6845. *
  6846. * All 4 kinds of bindings (`@`, `=`, `<`, and `&`) can be made optional by adding `?` to the expression.
  6847. * The marker must come after the mode and before the attribute name.
  6848. * See the {@link error/$compile/iscp Invalid Isolate Scope Definition error} for definition examples.
  6849. * This is useful to refine the interface directives provide.
  6850. * One subtle difference between optional and non-optional happens **when the binding attribute is not
  6851. * set**:
  6852. * - the binding is optional: the property will not be defined
  6853. * - the binding is not optional: the property is defined
  6854. *
  6855. * ```js
  6856. *app.directive('testDir', function() {
  6857. return {
  6858. scope: {
  6859. notoptional: '=',
  6860. optional: '=?',
  6861. },
  6862. bindToController: true,
  6863. controller: function() {
  6864. this.$onInit = function() {
  6865. console.log(this.hasOwnProperty('notoptional')) // true
  6866. console.log(this.hasOwnProperty('optional')) // false
  6867. }
  6868. }
  6869. }
  6870. })
  6871. *```
  6872. *
  6873. *
  6874. * ##### Combining directives with different scope defintions
  6875. *
  6876. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6877. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6878. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6879. *
  6880. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6881. * * **child scope** + **no scope** => Both directives will share one single child scope
  6882. * * **child scope** + **child scope** => Both directives will share one single child scope
  6883. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6884. * its parent's scope
  6885. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6886. * be applied to the same element.
  6887. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6888. * cannot be applied to the same element.
  6889. *
  6890. *
  6891. * #### `bindToController`
  6892. * This property is used to bind scope properties directly to the controller. It can be either
  6893. * `true` or an object hash with the same format as the `scope` property.
  6894. *
  6895. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6896. * allow a component to have its properties bound to the controller, rather than to scope.
  6897. *
  6898. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6899. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6900. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6901. * initialized.
  6902. *
  6903. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6904. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6905. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6906. * scope (useful for component directives).
  6907. *
  6908. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6909. *
  6910. *
  6911. * #### `controller`
  6912. * Controller constructor function. The controller is instantiated before the
  6913. * pre-linking phase and can be accessed by other directives (see
  6914. * `require` attribute). This allows the directives to communicate with each other and augment
  6915. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6916. *
  6917. * * `$scope` - Current scope associated with the element
  6918. * * `$element` - Current element
  6919. * * `$attrs` - Current attributes object for the element
  6920. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6921. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6922. * * `scope`: (optional) override the scope.
  6923. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6924. * * `futureParentElement` (optional):
  6925. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6926. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6927. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6928. * and when the `cloneLinkingFn` is passed,
  6929. * as those elements need to created and cloned in a special way when they are defined outside their
  6930. * usual containers (e.g. like `<svg>`).
  6931. * * See also the `directive.templateNamespace` property.
  6932. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6933. * then the default transclusion is provided.
  6934. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6935. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6936. *
  6937. * #### `require`
  6938. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6939. * `require` property can be a string, an array or an object:
  6940. * * a **string** containing the name of the directive to pass to the linking function
  6941. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6942. * linking function will be an array of controllers in the same order as the names in the `require` property
  6943. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6944. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6945. * controllers.
  6946. *
  6947. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6948. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6949. * have been constructed but before `$onInit` is called.
  6950. * If the name of the required controller is the same as the local name (the key), the name can be
  6951. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  6952. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6953. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6954. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6955. * controller, in which case error checking is skipped). The name can be prefixed with:
  6956. *
  6957. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6958. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6959. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6960. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6961. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6962. * `null` to the `link` fn if not found.
  6963. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6964. * `null` to the `link` fn if not found.
  6965. *
  6966. *
  6967. * #### `controllerAs`
  6968. * Identifier name for a reference to the controller in the directive's scope.
  6969. * This allows the controller to be referenced from the directive template. This is especially
  6970. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6971. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6972. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6973. *
  6974. *
  6975. * #### `restrict`
  6976. * String of subset of `EACM` which restricts the directive to a specific directive
  6977. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6978. *
  6979. * * `E` - Element name (default): `<my-directive></my-directive>`
  6980. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6981. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6982. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6983. *
  6984. *
  6985. * #### `templateNamespace`
  6986. * String representing the document type used by the markup in the template.
  6987. * AngularJS needs this information as those elements need to be created and cloned
  6988. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6989. *
  6990. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6991. * top-level elements such as `<svg>` or `<math>`.
  6992. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6993. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6994. *
  6995. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6996. *
  6997. * #### `template`
  6998. * HTML markup that may:
  6999. * * Replace the contents of the directive's element (default).
  7000. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  7001. * * Wrap the contents of the directive's element (if `transclude` is true).
  7002. *
  7003. * Value may be:
  7004. *
  7005. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  7006. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  7007. * function api below) and returns a string value.
  7008. *
  7009. *
  7010. * #### `templateUrl`
  7011. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  7012. *
  7013. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  7014. * for later when the template has been resolved. In the meantime it will continue to compile and link
  7015. * sibling and parent elements as though this element had not contained any directives.
  7016. *
  7017. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  7018. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  7019. * case when only one deeply nested directive has `templateUrl`.
  7020. *
  7021. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  7022. *
  7023. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  7024. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  7025. * a string value representing the url. In either case, the template URL is passed through {@link
  7026. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  7027. *
  7028. *
  7029. * #### `replace`
  7030. * <div class="alert alert-danger">
  7031. * **Note:** `replace` is deprecated in AngularJS and has been removed in the new Angular (v2+).
  7032. * </div>
  7033. *
  7034. * Specifies what the template should replace. Defaults to `false`.
  7035. *
  7036. * * `true` - the template will replace the directive's element.
  7037. * * `false` - the template will replace the contents of the directive's element.
  7038. *
  7039. * The replacement process migrates all of the attributes / classes from the old element to the new
  7040. * one. See the {@link guide/directive#template-expanding-directive
  7041. * Directives Guide} for an example.
  7042. *
  7043. * There are very few scenarios where element replacement is required for the application function,
  7044. * the main one being reusable custom components that are used within SVG contexts
  7045. * (because SVG doesn't work with custom elements in the DOM tree).
  7046. *
  7047. * #### `transclude`
  7048. * Extract the contents of the element where the directive appears and make it available to the directive.
  7049. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  7050. * {@link $compile#transclusion Transclusion} section below.
  7051. *
  7052. *
  7053. * #### `compile`
  7054. *
  7055. * ```js
  7056. * function compile(tElement, tAttrs, transclude) { ... }
  7057. * ```
  7058. *
  7059. * The compile function deals with transforming the template DOM. Since most directives do not do
  7060. * template transformation, it is not used often. The compile function takes the following arguments:
  7061. *
  7062. * * `tElement` - template element - The element where the directive has been declared. It is
  7063. * safe to do template transformation on the element and child elements only.
  7064. *
  7065. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  7066. * between all directive compile functions.
  7067. *
  7068. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  7069. *
  7070. * <div class="alert alert-warning">
  7071. * **Note:** The template instance and the link instance may be different objects if the template has
  7072. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  7073. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  7074. * should be done in a linking function rather than in a compile function.
  7075. * </div>
  7076. * <div class="alert alert-warning">
  7077. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  7078. * own templates or compile functions. Compiling these directives results in an infinite loop and
  7079. * stack overflow errors.
  7080. *
  7081. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  7082. * a directive's template instead of relying on automatic template compilation via `template` or
  7083. * `templateUrl` declaration or manual compilation inside the compile function.
  7084. * </div>
  7085. *
  7086. * <div class="alert alert-danger">
  7087. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  7088. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  7089. * to the link function instead.
  7090. * </div>
  7091. * A compile function can have a return value which can be either a function or an object.
  7092. *
  7093. * * returning a (post-link) function - is equivalent to registering the linking function via the
  7094. * `link` property of the config object when the compile function is empty.
  7095. *
  7096. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  7097. * control when a linking function should be called during the linking phase. See info about
  7098. * pre-linking and post-linking functions below.
  7099. *
  7100. *
  7101. * #### `link`
  7102. * This property is used only if the `compile` property is not defined.
  7103. *
  7104. * ```js
  7105. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  7106. * ```
  7107. *
  7108. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  7109. * executed after the template has been cloned. This is where most of the directive logic will be
  7110. * put.
  7111. *
  7112. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  7113. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  7114. *
  7115. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  7116. * manipulate the children of the element only in `postLink` function since the children have
  7117. * already been linked.
  7118. *
  7119. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  7120. * between all directive linking functions.
  7121. *
  7122. * * `controller` - the directive's required controller instance(s) - Instances are shared
  7123. * among all directives, which allows the directives to use the controllers as a communication
  7124. * channel. The exact value depends on the directive's `require` property:
  7125. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  7126. * * `string`: the controller instance
  7127. * * `array`: array of controller instances
  7128. *
  7129. * If a required controller cannot be found, and it is optional, the instance is `null`,
  7130. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  7131. *
  7132. * Note that you can also require the directive's own controller - it will be made available like
  7133. * any other controller.
  7134. *
  7135. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  7136. * This is the same as the `$transclude` parameter of directive controllers,
  7137. * see {@link ng.$compile#-controller- the controller section for details}.
  7138. * `function([scope], cloneLinkingFn, futureParentElement)`.
  7139. *
  7140. * #### Pre-linking function
  7141. *
  7142. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  7143. * compiler linking function will fail to locate the correct elements for linking.
  7144. *
  7145. * #### Post-linking function
  7146. *
  7147. * Executed after the child elements are linked.
  7148. *
  7149. * Note that child elements that contain `templateUrl` directives will not have been compiled
  7150. * and linked since they are waiting for their template to load asynchronously and their own
  7151. * compilation and linking has been suspended until that occurs.
  7152. *
  7153. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  7154. * for their async templates to be resolved.
  7155. *
  7156. *
  7157. * ### Transclusion
  7158. *
  7159. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  7160. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  7161. * scope from where they were taken.
  7162. *
  7163. * Transclusion is used (often with {@link ngTransclude}) to insert the
  7164. * original contents of a directive's element into a specified place in the template of the directive.
  7165. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  7166. * content has access to the properties on the scope from which it was taken, even if the directive
  7167. * has isolated scope.
  7168. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  7169. *
  7170. * This makes it possible for the widget to have private state for its template, while the transcluded
  7171. * content has access to its originating scope.
  7172. *
  7173. * <div class="alert alert-warning">
  7174. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  7175. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  7176. * Testing Transclusion Directives}.
  7177. * </div>
  7178. *
  7179. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  7180. * directive's element, the entire element or multiple parts of the element contents:
  7181. *
  7182. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  7183. * * `'element'` - transclude the whole of the directive's element including any directives on this
  7184. * element that defined at a lower priority than this directive. When used, the `template`
  7185. * property is ignored.
  7186. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  7187. *
  7188. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  7189. *
  7190. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  7191. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  7192. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  7193. *
  7194. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7195. *
  7196. * If the element selector is prefixed with a `?` then that slot is optional.
  7197. *
  7198. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  7199. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  7200. *
  7201. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  7202. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  7203. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  7204. * injectable into the directive's controller.
  7205. *
  7206. *
  7207. * #### Transclusion Functions
  7208. *
  7209. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  7210. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  7211. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  7212. *
  7213. * <div class="alert alert-info">
  7214. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  7215. * ngTransclude will deal with it for us.
  7216. * </div>
  7217. *
  7218. * If you want to manually control the insertion and removal of the transcluded content in your directive
  7219. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  7220. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  7221. *
  7222. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  7223. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  7224. * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
  7225. *
  7226. * <div class="alert alert-info">
  7227. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  7228. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  7229. * </div>
  7230. *
  7231. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  7232. * attach function**:
  7233. *
  7234. * ```js
  7235. * var transcludedContent, transclusionScope;
  7236. *
  7237. * $transclude(function(clone, scope) {
  7238. * element.append(clone);
  7239. * transcludedContent = clone;
  7240. * transclusionScope = scope;
  7241. * });
  7242. * ```
  7243. *
  7244. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  7245. * associated transclusion scope:
  7246. *
  7247. * ```js
  7248. * transcludedContent.remove();
  7249. * transclusionScope.$destroy();
  7250. * ```
  7251. *
  7252. * <div class="alert alert-info">
  7253. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  7254. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  7255. * then you are also responsible for calling `$destroy` on the transclusion scope.
  7256. * </div>
  7257. *
  7258. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  7259. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  7260. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  7261. *
  7262. *
  7263. * #### Transclusion Scopes
  7264. *
  7265. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  7266. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  7267. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  7268. * was taken.
  7269. *
  7270. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  7271. * like this:
  7272. *
  7273. * ```html
  7274. * <div ng-app>
  7275. * <div isolate>
  7276. * <div transclusion>
  7277. * </div>
  7278. * </div>
  7279. * </div>
  7280. * ```
  7281. *
  7282. * The `$parent` scope hierarchy will look like this:
  7283. *
  7284. ```
  7285. - $rootScope
  7286. - isolate
  7287. - transclusion
  7288. ```
  7289. *
  7290. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  7291. *
  7292. ```
  7293. - $rootScope
  7294. - transclusion
  7295. - isolate
  7296. ```
  7297. *
  7298. *
  7299. * ### Attributes
  7300. *
  7301. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  7302. * `link()` or `compile()` functions. It has a variety of uses.
  7303. *
  7304. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  7305. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  7306. * to the attributes.
  7307. *
  7308. * * *Directive inter-communication:* All directives share the same instance of the attributes
  7309. * object which allows the directives to use the attributes object as inter directive
  7310. * communication.
  7311. *
  7312. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  7313. * allowing other directives to read the interpolated value.
  7314. *
  7315. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  7316. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  7317. * the only way to easily get the actual value because during the linking phase the interpolation
  7318. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  7319. *
  7320. * ```js
  7321. * function linkingFn(scope, elm, attrs, ctrl) {
  7322. * // get the attribute value
  7323. * console.log(attrs.ngModel);
  7324. *
  7325. * // change the attribute
  7326. * attrs.$set('ngModel', 'new value');
  7327. *
  7328. * // observe changes to interpolated attribute
  7329. * attrs.$observe('ngModel', function(value) {
  7330. * console.log('ngModel has changed value to ' + value);
  7331. * });
  7332. * }
  7333. * ```
  7334. *
  7335. * ## Example
  7336. *
  7337. * <div class="alert alert-warning">
  7338. * **Note**: Typically directives are registered with `module.directive`. The example below is
  7339. * to illustrate how `$compile` works.
  7340. * </div>
  7341. *
  7342. <example module="compileExample" name="compile">
  7343. <file name="index.html">
  7344. <script>
  7345. angular.module('compileExample', [], function($compileProvider) {
  7346. // configure new 'compile' directive by passing a directive
  7347. // factory function. The factory function injects the '$compile'
  7348. $compileProvider.directive('compile', function($compile) {
  7349. // directive factory creates a link function
  7350. return function(scope, element, attrs) {
  7351. scope.$watch(
  7352. function(scope) {
  7353. // watch the 'compile' expression for changes
  7354. return scope.$eval(attrs.compile);
  7355. },
  7356. function(value) {
  7357. // when the 'compile' expression changes
  7358. // assign it into the current DOM
  7359. element.html(value);
  7360. // compile the new DOM and link it to the current
  7361. // scope.
  7362. // NOTE: we only compile .childNodes so that
  7363. // we don't get into infinite loop compiling ourselves
  7364. $compile(element.contents())(scope);
  7365. }
  7366. );
  7367. };
  7368. });
  7369. })
  7370. .controller('GreeterController', ['$scope', function($scope) {
  7371. $scope.name = 'AngularJS';
  7372. $scope.html = 'Hello {{name}}';
  7373. }]);
  7374. </script>
  7375. <div ng-controller="GreeterController">
  7376. <input ng-model="name"> <br/>
  7377. <textarea ng-model="html"></textarea> <br/>
  7378. <div compile="html"></div>
  7379. </div>
  7380. </file>
  7381. <file name="protractor.js" type="protractor">
  7382. it('should auto compile', function() {
  7383. var textarea = $('textarea');
  7384. var output = $('div[compile]');
  7385. // The initial state reads 'Hello AngularJS'.
  7386. expect(output.getText()).toBe('Hello AngularJS');
  7387. textarea.clear();
  7388. textarea.sendKeys('{{name}}!');
  7389. expect(output.getText()).toBe('AngularJS!');
  7390. });
  7391. </file>
  7392. </example>
  7393. *
  7394. *
  7395. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  7396. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  7397. *
  7398. * <div class="alert alert-danger">
  7399. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  7400. * e.g. will not use the right outer scope. Please pass the transclude function as a
  7401. * `parentBoundTranscludeFn` to the link function instead.
  7402. * </div>
  7403. *
  7404. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  7405. * root element(s), not their children)
  7406. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  7407. * (a DOM element/tree) to a scope. Where:
  7408. *
  7409. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  7410. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  7411. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  7412. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  7413. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  7414. *
  7415. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  7416. * * `scope` - is the current scope with which the linking function is working with.
  7417. *
  7418. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  7419. * keys may be used to control linking behavior:
  7420. *
  7421. * * `parentBoundTranscludeFn` - the transclude function made available to
  7422. * directives; if given, it will be passed through to the link functions of
  7423. * directives found in `element` during compilation.
  7424. * * `transcludeControllers` - an object hash with keys that map controller names
  7425. * to a hash with the key `instance`, which maps to the controller instance;
  7426. * if given, it will make the controllers available to directives on the compileNode:
  7427. * ```
  7428. * {
  7429. * parent: {
  7430. * instance: parentControllerInstance
  7431. * }
  7432. * }
  7433. * ```
  7434. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  7435. * the cloned elements; only needed for transcludes that are allowed to contain non html
  7436. * elements (e.g. SVG elements). See also the directive.controller property.
  7437. *
  7438. * Calling the linking function returns the element of the template. It is either the original
  7439. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  7440. *
  7441. * After linking the view is not updated until after a call to $digest which typically is done by
  7442. * AngularJS automatically.
  7443. *
  7444. * If you need access to the bound view, there are two ways to do it:
  7445. *
  7446. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  7447. * before you send them to the compiler and keep this reference around.
  7448. * ```js
  7449. * var element = $compile('<p>{{total}}</p>')(scope);
  7450. * ```
  7451. *
  7452. * - if on the other hand, you need the element to be cloned, the view reference from the original
  7453. * example would not point to the clone, but rather to the original template that was cloned. In
  7454. * this case, you can access the clone via the cloneAttachFn:
  7455. * ```js
  7456. * var templateElement = angular.element('<p>{{total}}</p>'),
  7457. * scope = ....;
  7458. *
  7459. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  7460. * //attach the clone to DOM document at the right place
  7461. * });
  7462. *
  7463. * //now we have reference to the cloned DOM via `clonedElement`
  7464. * ```
  7465. *
  7466. *
  7467. * For information on how the compiler works, see the
  7468. * {@link guide/compiler AngularJS HTML Compiler} section of the Developer Guide.
  7469. *
  7470. * @knownIssue
  7471. *
  7472. * ### Double Compilation
  7473. *
  7474. Double compilation occurs when an already compiled part of the DOM gets
  7475. compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,
  7476. and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it
  7477. section on double compilation} for an in-depth explanation and ways to avoid it.
  7478. * @knownIssue
  7479. ### Issues with `replace: true`
  7480. *
  7481. * <div class="alert alert-danger">
  7482. * **Note**: {@link $compile#-replace- `replace: true`} is deprecated and not recommended to use,
  7483. * mainly due to the issues listed here. It has been completely removed in the new Angular.
  7484. * </div>
  7485. *
  7486. * #### Attribute values are not merged
  7487. *
  7488. * When a `replace` directive encounters the same attribute on the original and the replace node,
  7489. * it will simply deduplicate the attribute and join the values with a space or with a `;` in case of
  7490. * the `style` attribute.
  7491. * ```html
  7492. * Original Node: <span class="original" style="color: red;"></span>
  7493. * Replace Template: <span class="replaced" style="background: blue;"></span>
  7494. * Result: <span class="original replaced" style="color: red; background: blue;"></span>
  7495. * ```
  7496. *
  7497. * That means attributes that contain AngularJS expressions will not be merged correctly, e.g.
  7498. * {@link ngShow} or {@link ngClass} will cause a {@link $parse} error:
  7499. *
  7500. * ```html
  7501. * Original Node: <span ng-class="{'something': something}" ng-show="!condition"></span>
  7502. * Replace Template: <span ng-class="{'else': else}" ng-show="otherCondition"></span>
  7503. * Result: <span ng-class="{'something': something} {'else': else}" ng-show="!condition otherCondition"></span>
  7504. * ```
  7505. *
  7506. * See issue [#5695](https://github.com/angular/angular.js/issues/5695).
  7507. *
  7508. * #### Directives are not deduplicated before compilation
  7509. *
  7510. * When the original node and the replace template declare the same directive(s), they will be
  7511. * {@link guide/compiler#double-compilation-and-how-to-avoid-it compiled twice} because the compiler
  7512. * does not deduplicate them. In many cases, this is not noticable, but e.g. {@link ngModel} will
  7513. * attach `$formatters` and `$parsers` twice.
  7514. *
  7515. * See issue [#2573](https://github.com/angular/angular.js/issues/2573).
  7516. *
  7517. * #### `transclude: element` in the replace template root can have unexpected effects
  7518. *
  7519. * When the replace template has a directive at the root node that uses
  7520. * {@link $compile#-transclude- `transclude: element`}, e.g.
  7521. * {@link ngIf} or {@link ngRepeat}, the DOM structure or scope inheritance can be incorrect.
  7522. * See the following issues:
  7523. *
  7524. * - Incorrect scope on replaced element:
  7525. * [#9837](https://github.com/angular/angular.js/issues/9837)
  7526. * - Different DOM between `template` and `templateUrl`:
  7527. * [#10612](https://github.com/angular/angular.js/issues/14326)
  7528. *
  7529. */
  7530. /**
  7531. * @ngdoc directive
  7532. * @name ngProp
  7533. * @restrict A
  7534. * @element ANY
  7535. *
  7536. * @usage
  7537. *
  7538. * ```html
  7539. * <ANY ng-prop-propname="expression">
  7540. * </ANY>
  7541. * ```
  7542. *
  7543. * or with uppercase letters in property (e.g. "propName"):
  7544. *
  7545. *
  7546. * ```html
  7547. * <ANY ng-prop-prop_name="expression">
  7548. * </ANY>
  7549. * ```
  7550. *
  7551. *
  7552. * @description
  7553. * The `ngProp` directive binds an expression to a DOM element property.
  7554. * `ngProp` allows writing to arbitrary properties by including
  7555. * the property name in the attribute, e.g. `ng-prop-value="'my value'"` binds 'my value' to
  7556. * the `value` property.
  7557. *
  7558. * Usually, it's not necessary to write to properties in AngularJS, as the built-in directives
  7559. * handle the most common use cases (instead of the above example, you would use {@link ngValue}).
  7560. *
  7561. * However, [custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements)
  7562. * often use custom properties to hold data, and `ngProp` can be used to provide input to these
  7563. * custom elements.
  7564. *
  7565. * ## Binding to camelCase properties
  7566. *
  7567. * Since HTML attributes are case-insensitive, camelCase properties like `innerHTML` must be escaped.
  7568. * AngularJS uses the underscore (_) in front of a character to indicate that it is uppercase, so
  7569. * `innerHTML` must be written as `ng-prop-inner_h_t_m_l="expression"` (Note that this is just an
  7570. * example, and for binding HTML {@link ngBindHtml} should be used.
  7571. *
  7572. * ## Security
  7573. *
  7574. * Binding expressions to arbitrary properties poses a security risk, as properties like `innerHTML`
  7575. * can insert potentially dangerous HTML into the application, e.g. script tags that execute
  7576. * malicious code.
  7577. * For this reason, `ngProp` applies Strict Contextual Escaping with the {@link ng.$sce $sce service}.
  7578. * This means vulnerable properties require their content to be "trusted", based on the
  7579. * context of the property. For example, the `innerHTML` is in the `HTML` context, and the
  7580. * `iframe.src` property is in the `RESOURCE_URL` context, which requires that values written to
  7581. * this property are trusted as a `RESOURCE_URL`.
  7582. *
  7583. * This can be set explicitly by calling $sce.trustAs(type, value) on the value that is
  7584. * trusted before passing it to the `ng-prop-*` directive. There are exist shorthand methods for
  7585. * each context type in the form of {@link ng.$sce#trustAsResourceUrl $sce.trustAsResourceUrl()} et al.
  7586. *
  7587. * In some cases you can also rely upon automatic sanitization of untrusted values - see below.
  7588. *
  7589. * Based on the context, other options may exist to mark a value as trusted / configure the behavior
  7590. * of {@link ng.$sce}. For example, to restrict the `RESOURCE_URL` context to specific origins, use
  7591. * the {@link $sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist()}
  7592. * and {@link $sceDelegateProvider#resourceUrlBlacklist resourceUrlBlacklist()}.
  7593. *
  7594. * {@link ng.$sce#what-trusted-context-types-are-supported- Find out more about the different context types}.
  7595. *
  7596. * ### HTML Sanitization
  7597. *
  7598. * By default, `$sce` will throw an error if it detects untrusted HTML content, and will not bind the
  7599. * content.
  7600. * However, if you include the {@link ngSanitize ngSanitize module}, it will try to sanitize the
  7601. * potentially dangerous HTML, e.g. strip non-whitelisted tags and attributes when binding to
  7602. * `innerHTML`.
  7603. *
  7604. * @example
  7605. * ### Binding to different contexts
  7606. *
  7607. * <example name="ngProp" module="exampleNgProp">
  7608. * <file name="app.js">
  7609. * angular.module('exampleNgProp', [])
  7610. * .component('main', {
  7611. * templateUrl: 'main.html',
  7612. * controller: function($sce) {
  7613. * this.safeContent = '<strong>Safe content</strong>';
  7614. * this.unsafeContent = '<button onclick="alert(\'Hello XSS!\')">Click for XSS</button>';
  7615. * this.trustedUnsafeContent = $sce.trustAsHtml(this.unsafeContent);
  7616. * }
  7617. * });
  7618. * </file>
  7619. * <file name="main.html">
  7620. * <div>
  7621. * <div class="prop-unit">
  7622. * Binding to a property without security context:
  7623. * <div class="prop-binding" ng-prop-inner_text="$ctrl.safeContent"></div>
  7624. * <span class="prop-note">innerText</span> (safeContent)
  7625. * </div>
  7626. *
  7627. * <div class="prop-unit">
  7628. * "Safe" content that requires a security context will throw because the contents could potentially be dangerous ...
  7629. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.safeContent"></div>
  7630. * <span class="prop-note">innerHTML</span> (safeContent)
  7631. * </div>
  7632. *
  7633. * <div class="prop-unit">
  7634. * ... so that actually dangerous content cannot be executed:
  7635. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.unsafeContent"></div>
  7636. * <span class="prop-note">innerHTML</span> (unsafeContent)
  7637. * </div>
  7638. *
  7639. * <div class="prop-unit">
  7640. * ... but unsafe Content that has been trusted explicitly works - only do this if you are 100% sure!
  7641. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.trustedUnsafeContent"></div>
  7642. * <span class="prop-note">innerHTML</span> (trustedUnsafeContent)
  7643. * </div>
  7644. * </div>
  7645. * </file>
  7646. * <file name="index.html">
  7647. * <main></main>
  7648. * </file>
  7649. * <file name="styles.css">
  7650. * .prop-unit {
  7651. * margin-bottom: 10px;
  7652. * }
  7653. *
  7654. * .prop-binding {
  7655. * min-height: 30px;
  7656. * border: 1px solid blue;
  7657. * }
  7658. *
  7659. * .prop-note {
  7660. * font-family: Monospace;
  7661. * }
  7662. * </file>
  7663. * </example>
  7664. *
  7665. *
  7666. * @example
  7667. * ### Binding to innerHTML with ngSanitize
  7668. *
  7669. * <example name="ngProp" module="exampleNgProp" deps="angular-sanitize.js">
  7670. * <file name="app.js">
  7671. * angular.module('exampleNgProp', ['ngSanitize'])
  7672. * .component('main', {
  7673. * templateUrl: 'main.html',
  7674. * controller: function($sce) {
  7675. * this.safeContent = '<strong>Safe content</strong>';
  7676. * this.unsafeContent = '<button onclick="alert(\'Hello XSS!\')">Click for XSS</button>';
  7677. * this.trustedUnsafeContent = $sce.trustAsHtml(this.unsafeContent);
  7678. * }
  7679. * });
  7680. * </file>
  7681. * <file name="main.html">
  7682. * <div>
  7683. * <div class="prop-unit">
  7684. * "Safe" content will be sanitized ...
  7685. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.safeContent"></div>
  7686. * <span class="prop-note">innerHTML</span> (safeContent)
  7687. * </div>
  7688. *
  7689. * <div class="prop-unit">
  7690. * ... as will dangerous content:
  7691. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.unsafeContent"></div>
  7692. * <span class="prop-note">innerHTML</span> (unsafeContent)
  7693. * </div>
  7694. *
  7695. * <div class="prop-unit">
  7696. * ... and content that has been trusted explicitly works the same as without ngSanitize:
  7697. * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.trustedUnsafeContent"></div>
  7698. * <span class="prop-note">innerHTML</span> (trustedUnsafeContent)
  7699. * </div>
  7700. * </div>
  7701. * </file>
  7702. * <file name="index.html">
  7703. * <main></main>
  7704. * </file>
  7705. * <file name="styles.css">
  7706. * .prop-unit {
  7707. * margin-bottom: 10px;
  7708. * }
  7709. *
  7710. * .prop-binding {
  7711. * min-height: 30px;
  7712. * border: 1px solid blue;
  7713. * }
  7714. *
  7715. * .prop-note {
  7716. * font-family: Monospace;
  7717. * }
  7718. * </file>
  7719. * </example>
  7720. *
  7721. */
  7722. /** @ngdoc directive
  7723. * @name ngOn
  7724. * @restrict A
  7725. * @element ANY
  7726. *
  7727. * @usage
  7728. *
  7729. * ```html
  7730. * <ANY ng-on-eventname="expression">
  7731. * </ANY>
  7732. * ```
  7733. *
  7734. * or with uppercase letters in property (e.g. "eventName"):
  7735. *
  7736. *
  7737. * ```html
  7738. * <ANY ng-on-event_name="expression">
  7739. * </ANY>
  7740. * ```
  7741. *
  7742. * @description
  7743. * The `ngOn` directive adds an event listener to a DOM element via
  7744. * {@link angular.element angular.element().on()}, and evaluates an expression when the event is
  7745. * fired.
  7746. * `ngOn` allows adding listeners for arbitrary events by including
  7747. * the event name in the attribute, e.g. `ng-on-drop="onDrop()"` executes the 'onDrop()' expression
  7748. * when the `drop` event is fired.
  7749. *
  7750. * AngularJS provides specific directives for many events, such as {@link ngClick}, so in most
  7751. * cases it is not necessary to use `ngOn`. However, AngularJS does not support all events
  7752. * (e.g. the `drop` event in the example above), and new events might be introduced in later DOM
  7753. * standards.
  7754. *
  7755. * Another use-case for `ngOn` is listening to
  7756. * [custom events](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events)
  7757. * fired by
  7758. * [custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements).
  7759. *
  7760. * ## Binding to camelCase properties
  7761. *
  7762. * Since HTML attributes are case-insensitive, camelCase properties like `myEvent` must be escaped.
  7763. * AngularJS uses the underscore (_) in front of a character to indicate that it is uppercase, so
  7764. * `myEvent` must be written as `ng-on-my_event="expression"`.
  7765. *
  7766. * @example
  7767. * ### Bind to built-in DOM events
  7768. *
  7769. * <example name="ngOn" module="exampleNgOn">
  7770. * <file name="app.js">
  7771. * angular.module('exampleNgOn', [])
  7772. * .component('main', {
  7773. * templateUrl: 'main.html',
  7774. * controller: function() {
  7775. * this.clickCount = 0;
  7776. * this.mouseoverCount = 0;
  7777. *
  7778. * this.loadingState = 0;
  7779. * }
  7780. * });
  7781. * </file>
  7782. * <file name="main.html">
  7783. * <div>
  7784. * This is equivalent to `ngClick` and `ngMouseover`:<br>
  7785. * <button
  7786. * ng-on-click="$ctrl.clickCount = $ctrl.clickCount + 1"
  7787. * ng-on-mouseover="$ctrl.mouseoverCount = $ctrl.mouseoverCount + 1">Click or mouseover</button><br>
  7788. * clickCount: {{$ctrl.clickCount}}<br>
  7789. * mouseover: {{$ctrl.mouseoverCount}}
  7790. *
  7791. * <hr>
  7792. *
  7793. * For the `error` and `load` event on images no built-in AngularJS directives exist:<br>
  7794. * <img src="thisimagedoesnotexist.png" ng-on-error="$ctrl.loadingState = -1" ng-on-load="$ctrl.loadingState = 1"><br>
  7795. * <div ng-switch="$ctrl.loadingState">
  7796. * <span ng-switch-when="0">Image is loading</span>
  7797. * <span ng-switch-when="-1">Image load error</span>
  7798. * <span ng-switch-when="1">Image loaded successfully</span>
  7799. * </div>
  7800. * </div>
  7801. * </file>
  7802. * <file name="index.html">
  7803. * <main></main>
  7804. * </file>
  7805. * </example>
  7806. *
  7807. *
  7808. * @example
  7809. * ### Bind to custom DOM events
  7810. *
  7811. * <example name="ngOnCustom" module="exampleNgOn">
  7812. * <file name="app.js">
  7813. * angular.module('exampleNgOn', [])
  7814. * .component('main', {
  7815. * templateUrl: 'main.html',
  7816. * controller: function() {
  7817. * this.eventLog = '';
  7818. *
  7819. * this.listener = function($event) {
  7820. * this.eventLog = 'Event with type "' + $event.type + '" fired at ' + $event.detail;
  7821. * };
  7822. * }
  7823. * })
  7824. * .component('childComponent', {
  7825. * templateUrl: 'child.html',
  7826. * controller: function($element) {
  7827. * this.fireEvent = function() {
  7828. * var event = new CustomEvent('customtype', { detail: new Date()});
  7829. *
  7830. * $element[0].dispatchEvent(event);
  7831. * };
  7832. * }
  7833. * });
  7834. * </file>
  7835. * <file name="main.html">
  7836. * <child-component ng-on-customtype="$ctrl.listener($event)"></child-component><br>
  7837. * <span>Event log: {{$ctrl.eventLog}}</span>
  7838. * </file>
  7839. * <file name="child.html">
  7840. <button ng-click="$ctrl.fireEvent()">Fire custom event</button>
  7841. * </file>
  7842. * <file name="index.html">
  7843. * <main></main>
  7844. * </file>
  7845. * </example>
  7846. */
  7847. var $compileMinErr = minErr('$compile');
  7848. function UNINITIALIZED_VALUE() {}
  7849. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  7850. /**
  7851. * @ngdoc provider
  7852. * @name $compileProvider
  7853. *
  7854. * @description
  7855. */
  7856. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  7857. /** @this */
  7858. function $CompileProvider($provide, $$sanitizeUriProvider) {
  7859. var hasDirectives = {},
  7860. Suffix = 'Directive',
  7861. COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/,
  7862. CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,
  7863. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  7864. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  7865. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  7866. // The assumption is that future DOM event attribute names will begin with
  7867. // 'on' and be composed of only English letters.
  7868. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  7869. var bindingCache = createMap();
  7870. function parseIsolateBindings(scope, directiveName, isController) {
  7871. var LOCAL_REGEXP = /^([@&]|[=<](\*?))(\??)\s*([\w$]*)$/;
  7872. var bindings = createMap();
  7873. forEach(scope, function(definition, scopeName) {
  7874. definition = definition.trim();
  7875. if (definition in bindingCache) {
  7876. bindings[scopeName] = bindingCache[definition];
  7877. return;
  7878. }
  7879. var match = definition.match(LOCAL_REGEXP);
  7880. if (!match) {
  7881. throw $compileMinErr('iscp',
  7882. 'Invalid {3} for directive \'{0}\'.' +
  7883. ' Definition: {... {1}: \'{2}\' ...}',
  7884. directiveName, scopeName, definition,
  7885. (isController ? 'controller bindings definition' :
  7886. 'isolate scope definition'));
  7887. }
  7888. bindings[scopeName] = {
  7889. mode: match[1][0],
  7890. collection: match[2] === '*',
  7891. optional: match[3] === '?',
  7892. attrName: match[4] || scopeName
  7893. };
  7894. if (match[4]) {
  7895. bindingCache[definition] = bindings[scopeName];
  7896. }
  7897. });
  7898. return bindings;
  7899. }
  7900. function parseDirectiveBindings(directive, directiveName) {
  7901. var bindings = {
  7902. isolateScope: null,
  7903. bindToController: null
  7904. };
  7905. if (isObject(directive.scope)) {
  7906. if (directive.bindToController === true) {
  7907. bindings.bindToController = parseIsolateBindings(directive.scope,
  7908. directiveName, true);
  7909. bindings.isolateScope = {};
  7910. } else {
  7911. bindings.isolateScope = parseIsolateBindings(directive.scope,
  7912. directiveName, false);
  7913. }
  7914. }
  7915. if (isObject(directive.bindToController)) {
  7916. bindings.bindToController =
  7917. parseIsolateBindings(directive.bindToController, directiveName, true);
  7918. }
  7919. if (bindings.bindToController && !directive.controller) {
  7920. // There is no controller
  7921. throw $compileMinErr('noctrl',
  7922. 'Cannot bind to controller without directive \'{0}\'s controller.',
  7923. directiveName);
  7924. }
  7925. return bindings;
  7926. }
  7927. function assertValidDirectiveName(name) {
  7928. var letter = name.charAt(0);
  7929. if (!letter || letter !== lowercase(letter)) {
  7930. throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
  7931. }
  7932. if (name !== name.trim()) {
  7933. throw $compileMinErr('baddir',
  7934. 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
  7935. name);
  7936. }
  7937. }
  7938. function getDirectiveRequire(directive) {
  7939. var require = directive.require || (directive.controller && directive.name);
  7940. if (!isArray(require) && isObject(require)) {
  7941. forEach(require, function(value, key) {
  7942. var match = value.match(REQUIRE_PREFIX_REGEXP);
  7943. var name = value.substring(match[0].length);
  7944. if (!name) require[key] = match[0] + key;
  7945. });
  7946. }
  7947. return require;
  7948. }
  7949. function getDirectiveRestrict(restrict, name) {
  7950. if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
  7951. throw $compileMinErr('badrestrict',
  7952. 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
  7953. restrict,
  7954. name);
  7955. }
  7956. return restrict || 'EA';
  7957. }
  7958. /**
  7959. * @ngdoc method
  7960. * @name $compileProvider#directive
  7961. * @kind function
  7962. *
  7963. * @description
  7964. * Register a new directive with the compiler.
  7965. *
  7966. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  7967. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  7968. * names and the values are the factories.
  7969. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  7970. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  7971. * @returns {ng.$compileProvider} Self for chaining.
  7972. */
  7973. this.directive = function registerDirective(name, directiveFactory) {
  7974. assertArg(name, 'name');
  7975. assertNotHasOwnProperty(name, 'directive');
  7976. if (isString(name)) {
  7977. assertValidDirectiveName(name);
  7978. assertArg(directiveFactory, 'directiveFactory');
  7979. if (!hasDirectives.hasOwnProperty(name)) {
  7980. hasDirectives[name] = [];
  7981. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  7982. function($injector, $exceptionHandler) {
  7983. var directives = [];
  7984. forEach(hasDirectives[name], function(directiveFactory, index) {
  7985. try {
  7986. var directive = $injector.invoke(directiveFactory);
  7987. if (isFunction(directive)) {
  7988. directive = { compile: valueFn(directive) };
  7989. } else if (!directive.compile && directive.link) {
  7990. directive.compile = valueFn(directive.link);
  7991. }
  7992. directive.priority = directive.priority || 0;
  7993. directive.index = index;
  7994. directive.name = directive.name || name;
  7995. directive.require = getDirectiveRequire(directive);
  7996. directive.restrict = getDirectiveRestrict(directive.restrict, name);
  7997. directive.$$moduleName = directiveFactory.$$moduleName;
  7998. directives.push(directive);
  7999. } catch (e) {
  8000. $exceptionHandler(e);
  8001. }
  8002. });
  8003. return directives;
  8004. }]);
  8005. }
  8006. hasDirectives[name].push(directiveFactory);
  8007. } else {
  8008. forEach(name, reverseParams(registerDirective));
  8009. }
  8010. return this;
  8011. };
  8012. /**
  8013. * @ngdoc method
  8014. * @name $compileProvider#component
  8015. * @module ng
  8016. * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`),
  8017. * or an object map of components where the keys are the names and the values are the component definition objects.
  8018. * @param {Object} options Component definition object (a simplified
  8019. * {@link ng.$compile#directive-definition-object directive definition object}),
  8020. * with the following properties (all optional):
  8021. *
  8022. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  8023. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  8024. * registered controller} if passed as a string. An empty `noop` function by default.
  8025. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  8026. * If present, the controller will be published to scope under the `controllerAs` name.
  8027. * If not present, this will default to be `$ctrl`.
  8028. * - `template` – `{string=|function()=}` – html template as a string or a function that
  8029. * returns an html template as a string which should be used as the contents of this component.
  8030. * Empty string by default.
  8031. *
  8032. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  8033. * the following locals:
  8034. *
  8035. * - `$element` - Current element
  8036. * - `$attrs` - Current attributes object for the element
  8037. *
  8038. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  8039. * template that should be used as the contents of this component.
  8040. *
  8041. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  8042. * the following locals:
  8043. *
  8044. * - `$element` - Current element
  8045. * - `$attrs` - Current attributes object for the element
  8046. *
  8047. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  8048. * Component properties are always bound to the component controller and not to the scope.
  8049. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  8050. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  8051. * Disabled by default.
  8052. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  8053. * this component's controller. The object keys specify the property names under which the required
  8054. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  8055. * - `$...` – additional properties to attach to the directive factory function and the controller
  8056. * constructor function. (This is used by the component router to annotate)
  8057. *
  8058. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  8059. * @description
  8060. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  8061. * type of directive, which represents a self-contained UI component in your application. Such components
  8062. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  8063. *
  8064. * Component definitions are very simple and do not require as much configuration as defining general
  8065. * directives. Component definitions usually consist only of a template and a controller backing it.
  8066. *
  8067. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  8068. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  8069. *
  8070. * Here are a few examples of how you would usually define components:
  8071. *
  8072. * ```js
  8073. * var myMod = angular.module(...);
  8074. * myMod.component('myComp', {
  8075. * template: '<div>My name is {{$ctrl.name}}</div>',
  8076. * controller: function() {
  8077. * this.name = 'shahar';
  8078. * }
  8079. * });
  8080. *
  8081. * myMod.component('myComp', {
  8082. * template: '<div>My name is {{$ctrl.name}}</div>',
  8083. * bindings: {name: '@'}
  8084. * });
  8085. *
  8086. * myMod.component('myComp', {
  8087. * templateUrl: 'views/my-comp.html',
  8088. * controller: 'MyCtrl',
  8089. * controllerAs: 'ctrl',
  8090. * bindings: {name: '@'}
  8091. * });
  8092. *
  8093. * ```
  8094. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  8095. *
  8096. * <br />
  8097. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  8098. */
  8099. this.component = function registerComponent(name, options) {
  8100. if (!isString(name)) {
  8101. forEach(name, reverseParams(bind(this, registerComponent)));
  8102. return this;
  8103. }
  8104. var controller = options.controller || function() {};
  8105. function factory($injector) {
  8106. function makeInjectable(fn) {
  8107. if (isFunction(fn) || isArray(fn)) {
  8108. return /** @this */ function(tElement, tAttrs) {
  8109. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  8110. };
  8111. } else {
  8112. return fn;
  8113. }
  8114. }
  8115. var template = (!options.template && !options.templateUrl ? '' : options.template);
  8116. var ddo = {
  8117. controller: controller,
  8118. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  8119. template: makeInjectable(template),
  8120. templateUrl: makeInjectable(options.templateUrl),
  8121. transclude: options.transclude,
  8122. scope: {},
  8123. bindToController: options.bindings || {},
  8124. restrict: 'E',
  8125. require: options.require
  8126. };
  8127. // Copy annotations (starting with $) over to the DDO
  8128. forEach(options, function(val, key) {
  8129. if (key.charAt(0) === '$') ddo[key] = val;
  8130. });
  8131. return ddo;
  8132. }
  8133. // TODO(pete) remove the following `forEach` before we release 1.6.0
  8134. // The component-router@0.2.0 looks for the annotations on the controller constructor
  8135. // Nothing in AngularJS looks for annotations on the factory function but we can't remove
  8136. // it from 1.5.x yet.
  8137. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  8138. // These could be used by libraries such as the new component router
  8139. forEach(options, function(val, key) {
  8140. if (key.charAt(0) === '$') {
  8141. factory[key] = val;
  8142. // Don't try to copy over annotations to named controller
  8143. if (isFunction(controller)) controller[key] = val;
  8144. }
  8145. });
  8146. factory.$inject = ['$injector'];
  8147. return this.directive(name, factory);
  8148. };
  8149. /**
  8150. * @ngdoc method
  8151. * @name $compileProvider#aHrefSanitizationWhitelist
  8152. * @kind function
  8153. *
  8154. * @description
  8155. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  8156. * urls during a[href] sanitization.
  8157. *
  8158. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  8159. *
  8160. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  8161. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  8162. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  8163. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  8164. *
  8165. * @param {RegExp=} regexp New regexp to whitelist urls with.
  8166. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  8167. * chaining otherwise.
  8168. */
  8169. this.aHrefSanitizationWhitelist = function(regexp) {
  8170. if (isDefined(regexp)) {
  8171. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  8172. return this;
  8173. } else {
  8174. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  8175. }
  8176. };
  8177. /**
  8178. * @ngdoc method
  8179. * @name $compileProvider#imgSrcSanitizationWhitelist
  8180. * @kind function
  8181. *
  8182. * @description
  8183. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  8184. * urls during img[src] sanitization.
  8185. *
  8186. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  8187. *
  8188. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  8189. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  8190. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  8191. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  8192. *
  8193. * @param {RegExp=} regexp New regexp to whitelist urls with.
  8194. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  8195. * chaining otherwise.
  8196. */
  8197. this.imgSrcSanitizationWhitelist = function(regexp) {
  8198. if (isDefined(regexp)) {
  8199. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  8200. return this;
  8201. } else {
  8202. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  8203. }
  8204. };
  8205. /**
  8206. * @ngdoc method
  8207. * @name $compileProvider#debugInfoEnabled
  8208. *
  8209. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  8210. * current debugInfoEnabled state
  8211. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8212. *
  8213. * @kind function
  8214. *
  8215. * @description
  8216. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  8217. * binding information and a reference to the current scope on to DOM elements.
  8218. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  8219. * * `ng-binding` CSS class
  8220. * * `ng-scope` and `ng-isolated-scope` CSS classes
  8221. * * `$binding` data property containing an array of the binding expressions
  8222. * * Data properties used by the {@link angular.element#methods `scope()`/`isolateScope()` methods} to return
  8223. * the element's scope.
  8224. * * Placeholder comments will contain information about what directive and binding caused the placeholder.
  8225. * E.g. `<!-- ngIf: shouldShow() -->`.
  8226. *
  8227. * You may want to disable this in production for a significant performance boost. See
  8228. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  8229. *
  8230. * The default value is true.
  8231. */
  8232. var debugInfoEnabled = true;
  8233. this.debugInfoEnabled = function(enabled) {
  8234. if (isDefined(enabled)) {
  8235. debugInfoEnabled = enabled;
  8236. return this;
  8237. }
  8238. return debugInfoEnabled;
  8239. };
  8240. /**
  8241. * @ngdoc method
  8242. * @name $compileProvider#strictComponentBindingsEnabled
  8243. *
  8244. * @param {boolean=} enabled update the strictComponentBindingsEnabled state if provided,
  8245. * otherwise return the current strictComponentBindingsEnabled state.
  8246. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8247. *
  8248. * @kind function
  8249. *
  8250. * @description
  8251. * Call this method to enable / disable the strict component bindings check. If enabled, the
  8252. * compiler will enforce that all scope / controller bindings of a
  8253. * {@link $compileProvider#directive directive} / {@link $compileProvider#component component}
  8254. * that are not set as optional with `?`, must be provided when the directive is instantiated.
  8255. * If not provided, the compiler will throw the
  8256. * {@link error/$compile/missingattr $compile:missingattr error}.
  8257. *
  8258. * The default value is false.
  8259. */
  8260. var strictComponentBindingsEnabled = false;
  8261. this.strictComponentBindingsEnabled = function(enabled) {
  8262. if (isDefined(enabled)) {
  8263. strictComponentBindingsEnabled = enabled;
  8264. return this;
  8265. }
  8266. return strictComponentBindingsEnabled;
  8267. };
  8268. var TTL = 10;
  8269. /**
  8270. * @ngdoc method
  8271. * @name $compileProvider#onChangesTtl
  8272. * @description
  8273. *
  8274. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  8275. * assuming that the model is unstable.
  8276. *
  8277. * The current default is 10 iterations.
  8278. *
  8279. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  8280. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  8281. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  8282. * the `$onChanges` hook execution.
  8283. *
  8284. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  8285. *
  8286. * @param {number} limit The number of `$onChanges` hook iterations.
  8287. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  8288. */
  8289. this.onChangesTtl = function(value) {
  8290. if (arguments.length) {
  8291. TTL = value;
  8292. return this;
  8293. }
  8294. return TTL;
  8295. };
  8296. var commentDirectivesEnabledConfig = true;
  8297. /**
  8298. * @ngdoc method
  8299. * @name $compileProvider#commentDirectivesEnabled
  8300. * @description
  8301. *
  8302. * It indicates to the compiler
  8303. * whether or not directives on comments should be compiled.
  8304. * Defaults to `true`.
  8305. *
  8306. * Calling this function with false disables the compilation of directives
  8307. * on comments for the whole application.
  8308. * This results in a compilation performance gain,
  8309. * as the compiler doesn't have to check comments when looking for directives.
  8310. * This should however only be used if you are sure that no comment directives are used in
  8311. * the application (including any 3rd party directives).
  8312. *
  8313. * @param {boolean} enabled `false` if the compiler may ignore directives on comments
  8314. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  8315. */
  8316. this.commentDirectivesEnabled = function(value) {
  8317. if (arguments.length) {
  8318. commentDirectivesEnabledConfig = value;
  8319. return this;
  8320. }
  8321. return commentDirectivesEnabledConfig;
  8322. };
  8323. var cssClassDirectivesEnabledConfig = true;
  8324. /**
  8325. * @ngdoc method
  8326. * @name $compileProvider#cssClassDirectivesEnabled
  8327. * @description
  8328. *
  8329. * It indicates to the compiler
  8330. * whether or not directives on element classes should be compiled.
  8331. * Defaults to `true`.
  8332. *
  8333. * Calling this function with false disables the compilation of directives
  8334. * on element classes for the whole application.
  8335. * This results in a compilation performance gain,
  8336. * as the compiler doesn't have to check element classes when looking for directives.
  8337. * This should however only be used if you are sure that no class directives are used in
  8338. * the application (including any 3rd party directives).
  8339. *
  8340. * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
  8341. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  8342. */
  8343. this.cssClassDirectivesEnabled = function(value) {
  8344. if (arguments.length) {
  8345. cssClassDirectivesEnabledConfig = value;
  8346. return this;
  8347. }
  8348. return cssClassDirectivesEnabledConfig;
  8349. };
  8350. /**
  8351. * The security context of DOM Properties.
  8352. * @private
  8353. */
  8354. var PROP_CONTEXTS = createMap();
  8355. /**
  8356. * @ngdoc method
  8357. * @name $compileProvider#addPropertySecurityContext
  8358. * @description
  8359. *
  8360. * Defines the security context for DOM properties bound by ng-prop-*.
  8361. *
  8362. * @param {string} elementName The element name or '*' to match any element.
  8363. * @param {string} propertyName The DOM property name.
  8364. * @param {string} ctx The {@link $sce} security context in which this value is safe for use, e.g. `$sce.URL`
  8365. * @returns {object} `this` for chaining
  8366. */
  8367. this.addPropertySecurityContext = function(elementName, propertyName, ctx) {
  8368. var key = (elementName.toLowerCase() + '|' + propertyName.toLowerCase());
  8369. if (key in PROP_CONTEXTS && PROP_CONTEXTS[key] !== ctx) {
  8370. throw $compileMinErr('ctxoverride', 'Property context \'{0}.{1}\' already set to \'{2}\', cannot override to \'{3}\'.', elementName, propertyName, PROP_CONTEXTS[key], ctx);
  8371. }
  8372. PROP_CONTEXTS[key] = ctx;
  8373. return this;
  8374. };
  8375. /* Default property contexts.
  8376. *
  8377. * Copy of https://github.com/angular/angular/blob/6.0.6/packages/compiler/src/schema/dom_security_schema.ts#L31-L58
  8378. * Changing:
  8379. * - SecurityContext.* => SCE_CONTEXTS/$sce.*
  8380. * - STYLE => CSS
  8381. * - various URL => MEDIA_URL
  8382. * - *|formAction, form|action URL => RESOURCE_URL (like the attribute)
  8383. */
  8384. (function registerNativePropertyContexts() {
  8385. function registerContext(ctx, values) {
  8386. forEach(values, function(v) { PROP_CONTEXTS[v.toLowerCase()] = ctx; });
  8387. }
  8388. registerContext(SCE_CONTEXTS.HTML, [
  8389. 'iframe|srcdoc',
  8390. '*|innerHTML',
  8391. '*|outerHTML'
  8392. ]);
  8393. registerContext(SCE_CONTEXTS.CSS, ['*|style']);
  8394. registerContext(SCE_CONTEXTS.URL, [
  8395. 'area|href', 'area|ping',
  8396. 'a|href', 'a|ping',
  8397. 'blockquote|cite',
  8398. 'body|background',
  8399. 'del|cite',
  8400. 'input|src',
  8401. 'ins|cite',
  8402. 'q|cite'
  8403. ]);
  8404. registerContext(SCE_CONTEXTS.MEDIA_URL, [
  8405. 'audio|src',
  8406. 'img|src', 'img|srcset',
  8407. 'source|src', 'source|srcset',
  8408. 'track|src',
  8409. 'video|src', 'video|poster'
  8410. ]);
  8411. registerContext(SCE_CONTEXTS.RESOURCE_URL, [
  8412. '*|formAction',
  8413. 'applet|code', 'applet|codebase',
  8414. 'base|href',
  8415. 'embed|src',
  8416. 'frame|src',
  8417. 'form|action',
  8418. 'head|profile',
  8419. 'html|manifest',
  8420. 'iframe|src',
  8421. 'link|href',
  8422. 'media|src',
  8423. 'object|codebase', 'object|data',
  8424. 'script|src'
  8425. ]);
  8426. })();
  8427. this.$get = [
  8428. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  8429. '$controller', '$rootScope', '$sce', '$animate',
  8430. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  8431. $controller, $rootScope, $sce, $animate) {
  8432. var SIMPLE_ATTR_NAME = /^\w/;
  8433. var specialAttrHolder = window.document.createElement('div');
  8434. var commentDirectivesEnabled = commentDirectivesEnabledConfig;
  8435. var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
  8436. var onChangesTtl = TTL;
  8437. // The onChanges hooks should all be run together in a single digest
  8438. // When changes occur, the call to trigger their hooks will be added to this queue
  8439. var onChangesQueue;
  8440. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  8441. function flushOnChangesQueue() {
  8442. try {
  8443. if (!(--onChangesTtl)) {
  8444. // We have hit the TTL limit so reset everything
  8445. onChangesQueue = undefined;
  8446. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  8447. }
  8448. // We must run this hook in an apply since the $$postDigest runs outside apply
  8449. $rootScope.$apply(function() {
  8450. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  8451. try {
  8452. onChangesQueue[i]();
  8453. } catch (e) {
  8454. $exceptionHandler(e);
  8455. }
  8456. }
  8457. // Reset the queue to trigger a new schedule next time there is a change
  8458. onChangesQueue = undefined;
  8459. });
  8460. } finally {
  8461. onChangesTtl++;
  8462. }
  8463. }
  8464. function sanitizeSrcset(value, invokeType) {
  8465. if (!value) {
  8466. return value;
  8467. }
  8468. if (!isString(value)) {
  8469. throw $compileMinErr('srcset', 'Can\'t pass trusted values to `{0}`: "{1}"', invokeType, value.toString());
  8470. }
  8471. // Such values are a bit too complex to handle automatically inside $sce.
  8472. // Instead, we sanitize each of the URIs individually, which works, even dynamically.
  8473. // It's not possible to work around this using `$sce.trustAsMediaUrl`.
  8474. // If you want to programmatically set explicitly trusted unsafe URLs, you should use
  8475. // `$sce.trustAsHtml` on the whole `img` tag and inject it into the DOM using the
  8476. // `ng-bind-html` directive.
  8477. var result = '';
  8478. // first check if there are spaces because it's not the same pattern
  8479. var trimmedSrcset = trim(value);
  8480. // ( 999x ,| 999w ,| ,|, )
  8481. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  8482. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  8483. // split srcset into tuple of uri and descriptor except for the last item
  8484. var rawUris = trimmedSrcset.split(pattern);
  8485. // for each tuples
  8486. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  8487. for (var i = 0; i < nbrUrisWith2parts; i++) {
  8488. var innerIdx = i * 2;
  8489. // sanitize the uri
  8490. result += $sce.getTrustedMediaUrl(trim(rawUris[innerIdx]));
  8491. // add the descriptor
  8492. result += ' ' + trim(rawUris[innerIdx + 1]);
  8493. }
  8494. // split the last item into uri and descriptor
  8495. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  8496. // sanitize the last uri
  8497. result += $sce.getTrustedMediaUrl(trim(lastTuple[0]));
  8498. // and add the last descriptor if any
  8499. if (lastTuple.length === 2) {
  8500. result += (' ' + trim(lastTuple[1]));
  8501. }
  8502. return result;
  8503. }
  8504. function Attributes(element, attributesToCopy) {
  8505. if (attributesToCopy) {
  8506. var keys = Object.keys(attributesToCopy);
  8507. var i, l, key;
  8508. for (i = 0, l = keys.length; i < l; i++) {
  8509. key = keys[i];
  8510. this[key] = attributesToCopy[key];
  8511. }
  8512. } else {
  8513. this.$attr = {};
  8514. }
  8515. this.$$element = element;
  8516. }
  8517. Attributes.prototype = {
  8518. /**
  8519. * @ngdoc method
  8520. * @name $compile.directive.Attributes#$normalize
  8521. * @kind function
  8522. *
  8523. * @description
  8524. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  8525. * `data-`) to its normalized, camelCase form.
  8526. *
  8527. * Also there is special case for Moz prefix starting with upper case letter.
  8528. *
  8529. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  8530. *
  8531. * @param {string} name Name to normalize
  8532. */
  8533. $normalize: directiveNormalize,
  8534. /**
  8535. * @ngdoc method
  8536. * @name $compile.directive.Attributes#$addClass
  8537. * @kind function
  8538. *
  8539. * @description
  8540. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  8541. * are enabled then an animation will be triggered for the class addition.
  8542. *
  8543. * @param {string} classVal The className value that will be added to the element
  8544. */
  8545. $addClass: function(classVal) {
  8546. if (classVal && classVal.length > 0) {
  8547. $animate.addClass(this.$$element, classVal);
  8548. }
  8549. },
  8550. /**
  8551. * @ngdoc method
  8552. * @name $compile.directive.Attributes#$removeClass
  8553. * @kind function
  8554. *
  8555. * @description
  8556. * Removes the CSS class value specified by the classVal parameter from the element. If
  8557. * animations are enabled then an animation will be triggered for the class removal.
  8558. *
  8559. * @param {string} classVal The className value that will be removed from the element
  8560. */
  8561. $removeClass: function(classVal) {
  8562. if (classVal && classVal.length > 0) {
  8563. $animate.removeClass(this.$$element, classVal);
  8564. }
  8565. },
  8566. /**
  8567. * @ngdoc method
  8568. * @name $compile.directive.Attributes#$updateClass
  8569. * @kind function
  8570. *
  8571. * @description
  8572. * Adds and removes the appropriate CSS class values to the element based on the difference
  8573. * between the new and old CSS class values (specified as newClasses and oldClasses).
  8574. *
  8575. * @param {string} newClasses The current CSS className value
  8576. * @param {string} oldClasses The former CSS className value
  8577. */
  8578. $updateClass: function(newClasses, oldClasses) {
  8579. var toAdd = tokenDifference(newClasses, oldClasses);
  8580. if (toAdd && toAdd.length) {
  8581. $animate.addClass(this.$$element, toAdd);
  8582. }
  8583. var toRemove = tokenDifference(oldClasses, newClasses);
  8584. if (toRemove && toRemove.length) {
  8585. $animate.removeClass(this.$$element, toRemove);
  8586. }
  8587. },
  8588. /**
  8589. * Set a normalized attribute on the element in a way such that all directives
  8590. * can share the attribute. This function properly handles boolean attributes.
  8591. * @param {string} key Normalized key. (ie ngAttribute)
  8592. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  8593. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  8594. * Defaults to true.
  8595. * @param {string=} attrName Optional none normalized name. Defaults to key.
  8596. */
  8597. $set: function(key, value, writeAttr, attrName) {
  8598. // TODO: decide whether or not to throw an error if "class"
  8599. // is set through this function since it may cause $updateClass to
  8600. // become unstable.
  8601. var node = this.$$element[0],
  8602. booleanKey = getBooleanAttrName(node, key),
  8603. aliasedKey = getAliasedAttrName(key),
  8604. observer = key,
  8605. nodeName;
  8606. if (booleanKey) {
  8607. this.$$element.prop(key, value);
  8608. attrName = booleanKey;
  8609. } else if (aliasedKey) {
  8610. this[aliasedKey] = value;
  8611. observer = aliasedKey;
  8612. }
  8613. this[key] = value;
  8614. // translate normalized key to actual key
  8615. if (attrName) {
  8616. this.$attr[key] = attrName;
  8617. } else {
  8618. attrName = this.$attr[key];
  8619. if (!attrName) {
  8620. this.$attr[key] = attrName = snake_case(key, '-');
  8621. }
  8622. }
  8623. nodeName = nodeName_(this.$$element);
  8624. // Sanitize img[srcset] values.
  8625. if (nodeName === 'img' && key === 'srcset') {
  8626. this[key] = value = sanitizeSrcset(value, '$set(\'srcset\', value)');
  8627. }
  8628. if (writeAttr !== false) {
  8629. if (value === null || isUndefined(value)) {
  8630. this.$$element.removeAttr(attrName);
  8631. } else {
  8632. if (SIMPLE_ATTR_NAME.test(attrName)) {
  8633. this.$$element.attr(attrName, value);
  8634. } else {
  8635. setSpecialAttr(this.$$element[0], attrName, value);
  8636. }
  8637. }
  8638. }
  8639. // fire observers
  8640. var $$observers = this.$$observers;
  8641. if ($$observers) {
  8642. forEach($$observers[observer], function(fn) {
  8643. try {
  8644. fn(value);
  8645. } catch (e) {
  8646. $exceptionHandler(e);
  8647. }
  8648. });
  8649. }
  8650. },
  8651. /**
  8652. * @ngdoc method
  8653. * @name $compile.directive.Attributes#$observe
  8654. * @kind function
  8655. *
  8656. * @description
  8657. * Observes an interpolated attribute.
  8658. *
  8659. * The observer function will be invoked once during the next `$digest` following
  8660. * compilation. The observer is then invoked whenever the interpolated value
  8661. * changes.
  8662. *
  8663. * @param {string} key Normalized key. (ie ngAttribute) .
  8664. * @param {function(interpolatedValue)} fn Function that will be called whenever
  8665. the interpolated value of the attribute changes.
  8666. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  8667. * guide} for more info.
  8668. * @returns {function()} Returns a deregistration function for this observer.
  8669. */
  8670. $observe: function(key, fn) {
  8671. var attrs = this,
  8672. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  8673. listeners = ($$observers[key] || ($$observers[key] = []));
  8674. listeners.push(fn);
  8675. $rootScope.$evalAsync(function() {
  8676. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  8677. // no one registered attribute interpolation function, so lets call it manually
  8678. fn(attrs[key]);
  8679. }
  8680. });
  8681. return function() {
  8682. arrayRemove(listeners, fn);
  8683. };
  8684. }
  8685. };
  8686. function setSpecialAttr(element, attrName, value) {
  8687. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  8688. // so we have to jump through some hoops to get such an attribute
  8689. // https://github.com/angular/angular.js/pull/13318
  8690. specialAttrHolder.innerHTML = '<span ' + attrName + '>';
  8691. var attributes = specialAttrHolder.firstChild.attributes;
  8692. var attribute = attributes[0];
  8693. // We have to remove the attribute from its container element before we can add it to the destination element
  8694. attributes.removeNamedItem(attribute.name);
  8695. attribute.value = value;
  8696. element.attributes.setNamedItem(attribute);
  8697. }
  8698. function safeAddClass($element, className) {
  8699. try {
  8700. $element.addClass(className);
  8701. } catch (e) {
  8702. // ignore, since it means that we are trying to set class on
  8703. // SVG element, where class name is read-only.
  8704. }
  8705. }
  8706. var startSymbol = $interpolate.startSymbol(),
  8707. endSymbol = $interpolate.endSymbol(),
  8708. denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
  8709. ? identity
  8710. : function denormalizeTemplate(template) {
  8711. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  8712. },
  8713. NG_PREFIX_BINDING = /^ng(Attr|Prop|On)([A-Z].*)$/;
  8714. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  8715. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  8716. var bindings = $element.data('$binding') || [];
  8717. if (isArray(binding)) {
  8718. bindings = bindings.concat(binding);
  8719. } else {
  8720. bindings.push(binding);
  8721. }
  8722. $element.data('$binding', bindings);
  8723. } : noop;
  8724. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  8725. safeAddClass($element, 'ng-binding');
  8726. } : noop;
  8727. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  8728. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  8729. $element.data(dataName, scope);
  8730. } : noop;
  8731. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  8732. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  8733. } : noop;
  8734. compile.$$createComment = function(directiveName, comment) {
  8735. var content = '';
  8736. if (debugInfoEnabled) {
  8737. content = ' ' + (directiveName || '') + ': ';
  8738. if (comment) content += comment + ' ';
  8739. }
  8740. return window.document.createComment(content);
  8741. };
  8742. return compile;
  8743. //================================
  8744. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  8745. previousCompileContext) {
  8746. if (!($compileNodes instanceof jqLite)) {
  8747. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  8748. // modify it.
  8749. $compileNodes = jqLite($compileNodes);
  8750. }
  8751. var compositeLinkFn =
  8752. compileNodes($compileNodes, transcludeFn, $compileNodes,
  8753. maxPriority, ignoreDirective, previousCompileContext);
  8754. compile.$$addScopeClass($compileNodes);
  8755. var namespace = null;
  8756. return function publicLinkFn(scope, cloneConnectFn, options) {
  8757. if (!$compileNodes) {
  8758. throw $compileMinErr('multilink', 'This element has already been linked.');
  8759. }
  8760. assertArg(scope, 'scope');
  8761. if (previousCompileContext && previousCompileContext.needsNewScope) {
  8762. // A parent directive did a replace and a directive on this element asked
  8763. // for transclusion, which caused us to lose a layer of element on which
  8764. // we could hold the new transclusion scope, so we will create it manually
  8765. // here.
  8766. scope = scope.$parent.$new();
  8767. }
  8768. options = options || {};
  8769. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  8770. transcludeControllers = options.transcludeControllers,
  8771. futureParentElement = options.futureParentElement;
  8772. // When `parentBoundTranscludeFn` is passed, it is a
  8773. // `controllersBoundTransclude` function (it was previously passed
  8774. // as `transclude` to directive.link) so we must unwrap it to get
  8775. // its `boundTranscludeFn`
  8776. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  8777. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  8778. }
  8779. if (!namespace) {
  8780. namespace = detectNamespaceForChildElements(futureParentElement);
  8781. }
  8782. var $linkNode;
  8783. if (namespace !== 'html') {
  8784. // When using a directive with replace:true and templateUrl the $compileNodes
  8785. // (or a child element inside of them)
  8786. // might change, so we need to recreate the namespace adapted compileNodes
  8787. // for call to the link function.
  8788. // Note: This will already clone the nodes...
  8789. $linkNode = jqLite(
  8790. wrapTemplate(namespace, jqLite('<div></div>').append($compileNodes).html())
  8791. );
  8792. } else if (cloneConnectFn) {
  8793. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  8794. // and sometimes changes the structure of the DOM.
  8795. $linkNode = JQLitePrototype.clone.call($compileNodes);
  8796. } else {
  8797. $linkNode = $compileNodes;
  8798. }
  8799. if (transcludeControllers) {
  8800. for (var controllerName in transcludeControllers) {
  8801. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  8802. }
  8803. }
  8804. compile.$$addScopeInfo($linkNode, scope);
  8805. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  8806. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  8807. if (!cloneConnectFn) {
  8808. $compileNodes = compositeLinkFn = null;
  8809. }
  8810. return $linkNode;
  8811. };
  8812. }
  8813. function detectNamespaceForChildElements(parentElement) {
  8814. // TODO: Make this detect MathML as well...
  8815. var node = parentElement && parentElement[0];
  8816. if (!node) {
  8817. return 'html';
  8818. } else {
  8819. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  8820. }
  8821. }
  8822. /**
  8823. * Compile function matches each node in nodeList against the directives. Once all directives
  8824. * for a particular node are collected their compile functions are executed. The compile
  8825. * functions return values - the linking functions - are combined into a composite linking
  8826. * function, which is the a linking function for the node.
  8827. *
  8828. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  8829. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8830. * scope argument is auto-generated to the new child of the transcluded parent scope.
  8831. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  8832. * the rootElement must be set the jqLite collection of the compile root. This is
  8833. * needed so that the jqLite collection items can be replaced with widgets.
  8834. * @param {number=} maxPriority Max directive priority.
  8835. * @returns {Function} A composite linking function of all of the matched directives or null.
  8836. */
  8837. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  8838. previousCompileContext) {
  8839. var linkFns = [],
  8840. // `nodeList` can be either an element's `.childNodes` (live NodeList)
  8841. // or a jqLite/jQuery collection or an array
  8842. notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),
  8843. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  8844. for (var i = 0; i < nodeList.length; i++) {
  8845. attrs = new Attributes();
  8846. // Support: IE 11 only
  8847. // Workaround for #11781 and #14924
  8848. if (msie === 11) {
  8849. mergeConsecutiveTextNodes(nodeList, i, notLiveList);
  8850. }
  8851. // We must always refer to `nodeList[i]` hereafter,
  8852. // since the nodes can be replaced underneath us.
  8853. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  8854. ignoreDirective);
  8855. nodeLinkFn = (directives.length)
  8856. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  8857. null, [], [], previousCompileContext)
  8858. : null;
  8859. if (nodeLinkFn && nodeLinkFn.scope) {
  8860. compile.$$addScopeClass(attrs.$$element);
  8861. }
  8862. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  8863. !(childNodes = nodeList[i].childNodes) ||
  8864. !childNodes.length)
  8865. ? null
  8866. : compileNodes(childNodes,
  8867. nodeLinkFn ? (
  8868. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  8869. && nodeLinkFn.transclude) : transcludeFn);
  8870. if (nodeLinkFn || childLinkFn) {
  8871. linkFns.push(i, nodeLinkFn, childLinkFn);
  8872. linkFnFound = true;
  8873. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  8874. }
  8875. //use the previous context only for the first element in the virtual group
  8876. previousCompileContext = null;
  8877. }
  8878. // return a linking function if we have found anything, null otherwise
  8879. return linkFnFound ? compositeLinkFn : null;
  8880. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  8881. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  8882. var stableNodeList;
  8883. if (nodeLinkFnFound) {
  8884. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  8885. // offsets don't get screwed up
  8886. var nodeListLength = nodeList.length;
  8887. stableNodeList = new Array(nodeListLength);
  8888. // create a sparse array by only copying the elements which have a linkFn
  8889. for (i = 0; i < linkFns.length; i += 3) {
  8890. idx = linkFns[i];
  8891. stableNodeList[idx] = nodeList[idx];
  8892. }
  8893. } else {
  8894. stableNodeList = nodeList;
  8895. }
  8896. for (i = 0, ii = linkFns.length; i < ii;) {
  8897. node = stableNodeList[linkFns[i++]];
  8898. nodeLinkFn = linkFns[i++];
  8899. childLinkFn = linkFns[i++];
  8900. if (nodeLinkFn) {
  8901. if (nodeLinkFn.scope) {
  8902. childScope = scope.$new();
  8903. compile.$$addScopeInfo(jqLite(node), childScope);
  8904. } else {
  8905. childScope = scope;
  8906. }
  8907. if (nodeLinkFn.transcludeOnThisElement) {
  8908. childBoundTranscludeFn = createBoundTranscludeFn(
  8909. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  8910. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  8911. childBoundTranscludeFn = parentBoundTranscludeFn;
  8912. } else if (!parentBoundTranscludeFn && transcludeFn) {
  8913. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  8914. } else {
  8915. childBoundTranscludeFn = null;
  8916. }
  8917. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  8918. } else if (childLinkFn) {
  8919. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  8920. }
  8921. }
  8922. }
  8923. }
  8924. function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {
  8925. var node = nodeList[idx];
  8926. var parent = node.parentNode;
  8927. var sibling;
  8928. if (node.nodeType !== NODE_TYPE_TEXT) {
  8929. return;
  8930. }
  8931. while (true) {
  8932. sibling = parent ? node.nextSibling : nodeList[idx + 1];
  8933. if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {
  8934. break;
  8935. }
  8936. node.nodeValue = node.nodeValue + sibling.nodeValue;
  8937. if (sibling.parentNode) {
  8938. sibling.parentNode.removeChild(sibling);
  8939. }
  8940. if (notLiveList && sibling === nodeList[idx + 1]) {
  8941. nodeList.splice(idx + 1, 1);
  8942. }
  8943. }
  8944. }
  8945. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  8946. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  8947. if (!transcludedScope) {
  8948. transcludedScope = scope.$new(false, containingScope);
  8949. transcludedScope.$$transcluded = true;
  8950. }
  8951. return transcludeFn(transcludedScope, cloneFn, {
  8952. parentBoundTranscludeFn: previousBoundTranscludeFn,
  8953. transcludeControllers: controllers,
  8954. futureParentElement: futureParentElement
  8955. });
  8956. }
  8957. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  8958. // so that they are available inside the `controllersBoundTransclude` function
  8959. var boundSlots = boundTranscludeFn.$$slots = createMap();
  8960. for (var slotName in transcludeFn.$$slots) {
  8961. if (transcludeFn.$$slots[slotName]) {
  8962. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  8963. } else {
  8964. boundSlots[slotName] = null;
  8965. }
  8966. }
  8967. return boundTranscludeFn;
  8968. }
  8969. /**
  8970. * Looks for directives on the given node and adds them to the directive collection which is
  8971. * sorted.
  8972. *
  8973. * @param node Node to search.
  8974. * @param directives An array to which the directives are added to. This array is sorted before
  8975. * the function returns.
  8976. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  8977. * @param {number=} maxPriority Max directive priority.
  8978. */
  8979. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8980. var nodeType = node.nodeType,
  8981. attrsMap = attrs.$attr,
  8982. match,
  8983. nodeName,
  8984. className;
  8985. switch (nodeType) {
  8986. case NODE_TYPE_ELEMENT: /* Element */
  8987. nodeName = nodeName_(node);
  8988. // use the node name: <directive>
  8989. addDirective(directives,
  8990. directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
  8991. // iterate over the attributes
  8992. for (var attr, name, nName, value, ngPrefixMatch, nAttrs = node.attributes,
  8993. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  8994. var attrStartName = false;
  8995. var attrEndName = false;
  8996. var isNgAttr = false, isNgProp = false, isNgEvent = false;
  8997. var multiElementMatch;
  8998. attr = nAttrs[j];
  8999. name = attr.name;
  9000. value = attr.value;
  9001. nName = directiveNormalize(name.toLowerCase());
  9002. // Support ng-attr-*, ng-prop-* and ng-on-*
  9003. if ((ngPrefixMatch = nName.match(NG_PREFIX_BINDING))) {
  9004. isNgAttr = ngPrefixMatch[1] === 'Attr';
  9005. isNgProp = ngPrefixMatch[1] === 'Prop';
  9006. isNgEvent = ngPrefixMatch[1] === 'On';
  9007. // Normalize the non-prefixed name
  9008. name = name.replace(PREFIX_REGEXP, '')
  9009. .toLowerCase()
  9010. .substr(4 + ngPrefixMatch[1].length).replace(/_(.)/g, function(match, letter) {
  9011. return letter.toUpperCase();
  9012. });
  9013. // Support *-start / *-end multi element directives
  9014. } else if ((multiElementMatch = nName.match(MULTI_ELEMENT_DIR_RE)) && directiveIsMultiElement(multiElementMatch[1])) {
  9015. attrStartName = name;
  9016. attrEndName = name.substr(0, name.length - 5) + 'end';
  9017. name = name.substr(0, name.length - 6);
  9018. }
  9019. if (isNgProp || isNgEvent) {
  9020. attrs[nName] = value;
  9021. attrsMap[nName] = attr.name;
  9022. if (isNgProp) {
  9023. addPropertyDirective(node, directives, nName, name);
  9024. } else {
  9025. addEventDirective(directives, nName, name);
  9026. }
  9027. } else {
  9028. // Update nName for cases where a prefix was removed
  9029. // NOTE: the .toLowerCase() is unnecessary and causes https://github.com/angular/angular.js/issues/16624 for ng-attr-*
  9030. nName = directiveNormalize(name.toLowerCase());
  9031. attrsMap[nName] = name;
  9032. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  9033. attrs[nName] = value;
  9034. if (getBooleanAttrName(node, nName)) {
  9035. attrs[nName] = true; // presence means true
  9036. }
  9037. }
  9038. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  9039. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  9040. attrEndName);
  9041. }
  9042. }
  9043. if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {
  9044. // Hidden input elements can have strange behaviour when navigating back to the page
  9045. // This tells the browser not to try to cache and reinstate previous values
  9046. node.setAttribute('autocomplete', 'off');
  9047. }
  9048. // use class as directive
  9049. if (!cssClassDirectivesEnabled) break;
  9050. className = node.className;
  9051. if (isObject(className)) {
  9052. // Maybe SVGAnimatedString
  9053. className = className.animVal;
  9054. }
  9055. if (isString(className) && className !== '') {
  9056. while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
  9057. nName = directiveNormalize(match[2]);
  9058. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  9059. attrs[nName] = trim(match[3]);
  9060. }
  9061. className = className.substr(match.index + match[0].length);
  9062. }
  9063. }
  9064. break;
  9065. case NODE_TYPE_TEXT: /* Text Node */
  9066. addTextInterpolateDirective(directives, node.nodeValue);
  9067. break;
  9068. case NODE_TYPE_COMMENT: /* Comment */
  9069. if (!commentDirectivesEnabled) break;
  9070. collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
  9071. break;
  9072. }
  9073. directives.sort(byPriority);
  9074. return directives;
  9075. }
  9076. function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  9077. // function created because of performance, try/catch disables
  9078. // the optimization of the whole function #14848
  9079. try {
  9080. var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  9081. if (match) {
  9082. var nName = directiveNormalize(match[1]);
  9083. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  9084. attrs[nName] = trim(match[2]);
  9085. }
  9086. }
  9087. } catch (e) {
  9088. // turns out that under some circumstances IE9 throws errors when one attempts to read
  9089. // comment's node value.
  9090. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  9091. }
  9092. }
  9093. /**
  9094. * Given a node with a directive-start it collects all of the siblings until it finds
  9095. * directive-end.
  9096. * @param node
  9097. * @param attrStart
  9098. * @param attrEnd
  9099. * @returns {*}
  9100. */
  9101. function groupScan(node, attrStart, attrEnd) {
  9102. var nodes = [];
  9103. var depth = 0;
  9104. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  9105. do {
  9106. if (!node) {
  9107. throw $compileMinErr('uterdir',
  9108. 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
  9109. attrStart, attrEnd);
  9110. }
  9111. if (node.nodeType === NODE_TYPE_ELEMENT) {
  9112. if (node.hasAttribute(attrStart)) depth++;
  9113. if (node.hasAttribute(attrEnd)) depth--;
  9114. }
  9115. nodes.push(node);
  9116. node = node.nextSibling;
  9117. } while (depth > 0);
  9118. } else {
  9119. nodes.push(node);
  9120. }
  9121. return jqLite(nodes);
  9122. }
  9123. /**
  9124. * Wrapper for linking function which converts normal linking function into a grouped
  9125. * linking function.
  9126. * @param linkFn
  9127. * @param attrStart
  9128. * @param attrEnd
  9129. * @returns {Function}
  9130. */
  9131. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  9132. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  9133. element = groupScan(element[0], attrStart, attrEnd);
  9134. return linkFn(scope, element, attrs, controllers, transcludeFn);
  9135. };
  9136. }
  9137. /**
  9138. * A function generator that is used to support both eager and lazy compilation
  9139. * linking function.
  9140. * @param eager
  9141. * @param $compileNodes
  9142. * @param transcludeFn
  9143. * @param maxPriority
  9144. * @param ignoreDirective
  9145. * @param previousCompileContext
  9146. * @returns {Function}
  9147. */
  9148. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  9149. var compiled;
  9150. if (eager) {
  9151. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  9152. }
  9153. return /** @this */ function lazyCompilation() {
  9154. if (!compiled) {
  9155. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  9156. // Null out all of these references in order to make them eligible for garbage collection
  9157. // since this is a potentially long lived closure
  9158. $compileNodes = transcludeFn = previousCompileContext = null;
  9159. }
  9160. return compiled.apply(this, arguments);
  9161. };
  9162. }
  9163. /**
  9164. * Once the directives have been collected, their compile functions are executed. This method
  9165. * is responsible for inlining directive templates as well as terminating the application
  9166. * of the directives if the terminal directive has been reached.
  9167. *
  9168. * @param {Array} directives Array of collected directives to execute their compile function.
  9169. * this needs to be pre-sorted by priority order.
  9170. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  9171. * @param {Object} templateAttrs The shared attribute function
  9172. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  9173. * scope argument is auto-generated to the new
  9174. * child of the transcluded parent scope.
  9175. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  9176. * argument has the root jqLite array so that we can replace nodes
  9177. * on it.
  9178. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  9179. * compiling the transclusion.
  9180. * @param {Array.<Function>} preLinkFns
  9181. * @param {Array.<Function>} postLinkFns
  9182. * @param {Object} previousCompileContext Context used for previous compilation of the current
  9183. * node
  9184. * @returns {Function} linkFn
  9185. */
  9186. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  9187. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  9188. previousCompileContext) {
  9189. previousCompileContext = previousCompileContext || {};
  9190. var terminalPriority = -Number.MAX_VALUE,
  9191. newScopeDirective = previousCompileContext.newScopeDirective,
  9192. controllerDirectives = previousCompileContext.controllerDirectives,
  9193. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  9194. templateDirective = previousCompileContext.templateDirective,
  9195. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  9196. hasTranscludeDirective = false,
  9197. hasTemplate = false,
  9198. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  9199. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  9200. directive,
  9201. directiveName,
  9202. $template,
  9203. replaceDirective = originalReplaceDirective,
  9204. childTranscludeFn = transcludeFn,
  9205. linkFn,
  9206. didScanForMultipleTransclusion = false,
  9207. mightHaveMultipleTransclusionError = false,
  9208. directiveValue;
  9209. // executes all directives on the current element
  9210. for (var i = 0, ii = directives.length; i < ii; i++) {
  9211. directive = directives[i];
  9212. var attrStart = directive.$$start;
  9213. var attrEnd = directive.$$end;
  9214. // collect multiblock sections
  9215. if (attrStart) {
  9216. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  9217. }
  9218. $template = undefined;
  9219. if (terminalPriority > directive.priority) {
  9220. break; // prevent further processing of directives
  9221. }
  9222. directiveValue = directive.scope;
  9223. if (directiveValue) {
  9224. // skip the check for directives with async templates, we'll check the derived sync
  9225. // directive when the template arrives
  9226. if (!directive.templateUrl) {
  9227. if (isObject(directiveValue)) {
  9228. // This directive is trying to add an isolated scope.
  9229. // Check that there is no scope of any kind already
  9230. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  9231. directive, $compileNode);
  9232. newIsolateScopeDirective = directive;
  9233. } else {
  9234. // This directive is trying to add a child scope.
  9235. // Check that there is no isolated scope already
  9236. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  9237. $compileNode);
  9238. }
  9239. }
  9240. newScopeDirective = newScopeDirective || directive;
  9241. }
  9242. directiveName = directive.name;
  9243. // If we encounter a condition that can result in transclusion on the directive,
  9244. // then scan ahead in the remaining directives for others that may cause a multiple
  9245. // transclusion error to be thrown during the compilation process. If a matching directive
  9246. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  9247. // compile the `transclude` function rather than doing it lazily in order to throw
  9248. // exceptions at the correct time
  9249. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  9250. || (directive.transclude && !directive.$$tlb))) {
  9251. var candidateDirective;
  9252. for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
  9253. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  9254. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  9255. mightHaveMultipleTransclusionError = true;
  9256. break;
  9257. }
  9258. }
  9259. didScanForMultipleTransclusion = true;
  9260. }
  9261. if (!directive.templateUrl && directive.controller) {
  9262. controllerDirectives = controllerDirectives || createMap();
  9263. assertNoDuplicate('\'' + directiveName + '\' controller',
  9264. controllerDirectives[directiveName], directive, $compileNode);
  9265. controllerDirectives[directiveName] = directive;
  9266. }
  9267. directiveValue = directive.transclude;
  9268. if (directiveValue) {
  9269. hasTranscludeDirective = true;
  9270. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  9271. // This option should only be used by directives that know how to safely handle element transclusion,
  9272. // where the transcluded nodes are added or replaced after linking.
  9273. if (!directive.$$tlb) {
  9274. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  9275. nonTlbTranscludeDirective = directive;
  9276. }
  9277. if (directiveValue === 'element') {
  9278. hasElementTranscludeDirective = true;
  9279. terminalPriority = directive.priority;
  9280. $template = $compileNode;
  9281. $compileNode = templateAttrs.$$element =
  9282. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  9283. compileNode = $compileNode[0];
  9284. replaceWith(jqCollection, sliceArgs($template), compileNode);
  9285. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  9286. replaceDirective && replaceDirective.name, {
  9287. // Don't pass in:
  9288. // - controllerDirectives - otherwise we'll create duplicates controllers
  9289. // - newIsolateScopeDirective or templateDirective - combining templates with
  9290. // element transclusion doesn't make sense.
  9291. //
  9292. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  9293. // on the same element more than once.
  9294. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  9295. });
  9296. } else {
  9297. var slots = createMap();
  9298. if (!isObject(directiveValue)) {
  9299. $template = jqLite(jqLiteClone(compileNode)).contents();
  9300. } else {
  9301. // We have transclusion slots,
  9302. // collect them up, compile them and store their transclusion functions
  9303. $template = window.document.createDocumentFragment();
  9304. var slotMap = createMap();
  9305. var filledSlots = createMap();
  9306. // Parse the element selectors
  9307. forEach(directiveValue, function(elementSelector, slotName) {
  9308. // If an element selector starts with a ? then it is optional
  9309. var optional = (elementSelector.charAt(0) === '?');
  9310. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  9311. slotMap[elementSelector] = slotName;
  9312. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  9313. // Later when calling boundTransclusion functions with a slot name we only error if the
  9314. // slot is `undefined`
  9315. slots[slotName] = null;
  9316. // filledSlots contains `true` for all slots that are either optional or have been
  9317. // filled. This is used to check that we have not missed any required slots
  9318. filledSlots[slotName] = optional;
  9319. });
  9320. // Add the matching elements into their slot
  9321. forEach($compileNode.contents(), function(node) {
  9322. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  9323. if (slotName) {
  9324. filledSlots[slotName] = true;
  9325. slots[slotName] = slots[slotName] || window.document.createDocumentFragment();
  9326. slots[slotName].appendChild(node);
  9327. } else {
  9328. $template.appendChild(node);
  9329. }
  9330. });
  9331. // Check for required slots that were not filled
  9332. forEach(filledSlots, function(filled, slotName) {
  9333. if (!filled) {
  9334. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  9335. }
  9336. });
  9337. for (var slotName in slots) {
  9338. if (slots[slotName]) {
  9339. // Only define a transclusion function if the slot was filled
  9340. var slotCompileNodes = jqLite(slots[slotName].childNodes);
  9341. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slotCompileNodes, transcludeFn);
  9342. }
  9343. }
  9344. $template = jqLite($template.childNodes);
  9345. }
  9346. $compileNode.empty(); // clear contents
  9347. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  9348. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  9349. childTranscludeFn.$$slots = slots;
  9350. }
  9351. }
  9352. if (directive.template) {
  9353. hasTemplate = true;
  9354. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  9355. templateDirective = directive;
  9356. directiveValue = (isFunction(directive.template))
  9357. ? directive.template($compileNode, templateAttrs)
  9358. : directive.template;
  9359. directiveValue = denormalizeTemplate(directiveValue);
  9360. if (directive.replace) {
  9361. replaceDirective = directive;
  9362. if (jqLiteIsTextNode(directiveValue)) {
  9363. $template = [];
  9364. } else {
  9365. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  9366. }
  9367. compileNode = $template[0];
  9368. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  9369. throw $compileMinErr('tplrt',
  9370. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  9371. directiveName, '');
  9372. }
  9373. replaceWith(jqCollection, $compileNode, compileNode);
  9374. var newTemplateAttrs = {$attr: {}};
  9375. // combine directives from the original node and from the template:
  9376. // - take the array of directives for this element
  9377. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  9378. // - collect directives from the template and sort them by priority
  9379. // - combine directives as: processed + template + unprocessed
  9380. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  9381. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  9382. if (newIsolateScopeDirective || newScopeDirective) {
  9383. // The original directive caused the current element to be replaced but this element
  9384. // also needs to have a new scope, so we need to tell the template directives
  9385. // that they would need to get their scope from further up, if they require transclusion
  9386. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  9387. }
  9388. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  9389. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  9390. ii = directives.length;
  9391. } else {
  9392. $compileNode.html(directiveValue);
  9393. }
  9394. }
  9395. if (directive.templateUrl) {
  9396. hasTemplate = true;
  9397. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  9398. templateDirective = directive;
  9399. if (directive.replace) {
  9400. replaceDirective = directive;
  9401. }
  9402. // eslint-disable-next-line no-func-assign
  9403. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  9404. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  9405. controllerDirectives: controllerDirectives,
  9406. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  9407. newIsolateScopeDirective: newIsolateScopeDirective,
  9408. templateDirective: templateDirective,
  9409. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  9410. });
  9411. ii = directives.length;
  9412. } else if (directive.compile) {
  9413. try {
  9414. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  9415. var context = directive.$$originalDirective || directive;
  9416. if (isFunction(linkFn)) {
  9417. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  9418. } else if (linkFn) {
  9419. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  9420. }
  9421. } catch (e) {
  9422. $exceptionHandler(e, startingTag($compileNode));
  9423. }
  9424. }
  9425. if (directive.terminal) {
  9426. nodeLinkFn.terminal = true;
  9427. terminalPriority = Math.max(terminalPriority, directive.priority);
  9428. }
  9429. }
  9430. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  9431. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  9432. nodeLinkFn.templateOnThisElement = hasTemplate;
  9433. nodeLinkFn.transclude = childTranscludeFn;
  9434. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  9435. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  9436. return nodeLinkFn;
  9437. ////////////////////
  9438. function addLinkFns(pre, post, attrStart, attrEnd) {
  9439. if (pre) {
  9440. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  9441. pre.require = directive.require;
  9442. pre.directiveName = directiveName;
  9443. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  9444. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  9445. }
  9446. preLinkFns.push(pre);
  9447. }
  9448. if (post) {
  9449. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  9450. post.require = directive.require;
  9451. post.directiveName = directiveName;
  9452. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  9453. post = cloneAndAnnotateFn(post, {isolateScope: true});
  9454. }
  9455. postLinkFns.push(post);
  9456. }
  9457. }
  9458. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  9459. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  9460. attrs, scopeBindingInfo;
  9461. if (compileNode === linkNode) {
  9462. attrs = templateAttrs;
  9463. $element = templateAttrs.$$element;
  9464. } else {
  9465. $element = jqLite(linkNode);
  9466. attrs = new Attributes($element, templateAttrs);
  9467. }
  9468. controllerScope = scope;
  9469. if (newIsolateScopeDirective) {
  9470. isolateScope = scope.$new(true);
  9471. } else if (newScopeDirective) {
  9472. controllerScope = scope.$parent;
  9473. }
  9474. if (boundTranscludeFn) {
  9475. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  9476. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  9477. transcludeFn = controllersBoundTransclude;
  9478. transcludeFn.$$boundTransclude = boundTranscludeFn;
  9479. // expose the slots on the `$transclude` function
  9480. transcludeFn.isSlotFilled = function(slotName) {
  9481. return !!boundTranscludeFn.$$slots[slotName];
  9482. };
  9483. }
  9484. if (controllerDirectives) {
  9485. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  9486. }
  9487. if (newIsolateScopeDirective) {
  9488. // Initialize isolate scope bindings for new isolate scope directive.
  9489. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  9490. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  9491. compile.$$addScopeClass($element, true);
  9492. isolateScope.$$isolateBindings =
  9493. newIsolateScopeDirective.$$isolateBindings;
  9494. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  9495. isolateScope.$$isolateBindings,
  9496. newIsolateScopeDirective);
  9497. if (scopeBindingInfo.removeWatches) {
  9498. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  9499. }
  9500. }
  9501. // Initialize bindToController bindings
  9502. for (var name in elementControllers) {
  9503. var controllerDirective = controllerDirectives[name];
  9504. var controller = elementControllers[name];
  9505. var bindings = controllerDirective.$$bindings.bindToController;
  9506. controller.instance = controller();
  9507. $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
  9508. controller.bindingInfo =
  9509. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  9510. }
  9511. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  9512. forEach(controllerDirectives, function(controllerDirective, name) {
  9513. var require = controllerDirective.require;
  9514. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  9515. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  9516. }
  9517. });
  9518. // Handle the init and destroy lifecycle hooks on all controllers that have them
  9519. forEach(elementControllers, function(controller) {
  9520. var controllerInstance = controller.instance;
  9521. if (isFunction(controllerInstance.$onChanges)) {
  9522. try {
  9523. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  9524. } catch (e) {
  9525. $exceptionHandler(e);
  9526. }
  9527. }
  9528. if (isFunction(controllerInstance.$onInit)) {
  9529. try {
  9530. controllerInstance.$onInit();
  9531. } catch (e) {
  9532. $exceptionHandler(e);
  9533. }
  9534. }
  9535. if (isFunction(controllerInstance.$doCheck)) {
  9536. controllerScope.$watch(function() { controllerInstance.$doCheck(); });
  9537. controllerInstance.$doCheck();
  9538. }
  9539. if (isFunction(controllerInstance.$onDestroy)) {
  9540. controllerScope.$on('$destroy', function callOnDestroyHook() {
  9541. controllerInstance.$onDestroy();
  9542. });
  9543. }
  9544. });
  9545. // PRELINKING
  9546. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  9547. linkFn = preLinkFns[i];
  9548. invokeLinkFn(linkFn,
  9549. linkFn.isolateScope ? isolateScope : scope,
  9550. $element,
  9551. attrs,
  9552. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  9553. transcludeFn
  9554. );
  9555. }
  9556. // RECURSION
  9557. // We only pass the isolate scope, if the isolate directive has a template,
  9558. // otherwise the child elements do not belong to the isolate directive.
  9559. var scopeToChild = scope;
  9560. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  9561. scopeToChild = isolateScope;
  9562. }
  9563. if (childLinkFn) {
  9564. childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  9565. }
  9566. // POSTLINKING
  9567. for (i = postLinkFns.length - 1; i >= 0; i--) {
  9568. linkFn = postLinkFns[i];
  9569. invokeLinkFn(linkFn,
  9570. linkFn.isolateScope ? isolateScope : scope,
  9571. $element,
  9572. attrs,
  9573. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  9574. transcludeFn
  9575. );
  9576. }
  9577. // Trigger $postLink lifecycle hooks
  9578. forEach(elementControllers, function(controller) {
  9579. var controllerInstance = controller.instance;
  9580. if (isFunction(controllerInstance.$postLink)) {
  9581. controllerInstance.$postLink();
  9582. }
  9583. });
  9584. // This is the function that is injected as `$transclude`.
  9585. // Note: all arguments are optional!
  9586. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  9587. var transcludeControllers;
  9588. // No scope passed in:
  9589. if (!isScope(scope)) {
  9590. slotName = futureParentElement;
  9591. futureParentElement = cloneAttachFn;
  9592. cloneAttachFn = scope;
  9593. scope = undefined;
  9594. }
  9595. if (hasElementTranscludeDirective) {
  9596. transcludeControllers = elementControllers;
  9597. }
  9598. if (!futureParentElement) {
  9599. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  9600. }
  9601. if (slotName) {
  9602. // slotTranscludeFn can be one of three things:
  9603. // * a transclude function - a filled slot
  9604. // * `null` - an optional slot that was not filled
  9605. // * `undefined` - a slot that was not declared (i.e. invalid)
  9606. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  9607. if (slotTranscludeFn) {
  9608. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  9609. } else if (isUndefined(slotTranscludeFn)) {
  9610. throw $compileMinErr('noslot',
  9611. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  9612. 'Element: {1}',
  9613. slotName, startingTag($element));
  9614. }
  9615. } else {
  9616. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  9617. }
  9618. }
  9619. }
  9620. }
  9621. function getControllers(directiveName, require, $element, elementControllers) {
  9622. var value;
  9623. if (isString(require)) {
  9624. var match = require.match(REQUIRE_PREFIX_REGEXP);
  9625. var name = require.substring(match[0].length);
  9626. var inheritType = match[1] || match[3];
  9627. var optional = match[2] === '?';
  9628. //If only parents then start at the parent element
  9629. if (inheritType === '^^') {
  9630. $element = $element.parent();
  9631. //Otherwise attempt getting the controller from elementControllers in case
  9632. //the element is transcluded (and has no data) and to avoid .data if possible
  9633. } else {
  9634. value = elementControllers && elementControllers[name];
  9635. value = value && value.instance;
  9636. }
  9637. if (!value) {
  9638. var dataName = '$' + name + 'Controller';
  9639. if (inheritType === '^^' && $element[0] && $element[0].nodeType === NODE_TYPE_DOCUMENT) {
  9640. // inheritedData() uses the documentElement when it finds the document, so we would
  9641. // require from the element itself.
  9642. value = null;
  9643. } else {
  9644. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  9645. }
  9646. }
  9647. if (!value && !optional) {
  9648. throw $compileMinErr('ctreq',
  9649. 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
  9650. name, directiveName);
  9651. }
  9652. } else if (isArray(require)) {
  9653. value = [];
  9654. for (var i = 0, ii = require.length; i < ii; i++) {
  9655. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  9656. }
  9657. } else if (isObject(require)) {
  9658. value = {};
  9659. forEach(require, function(controller, property) {
  9660. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  9661. });
  9662. }
  9663. return value || null;
  9664. }
  9665. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  9666. var elementControllers = createMap();
  9667. for (var controllerKey in controllerDirectives) {
  9668. var directive = controllerDirectives[controllerKey];
  9669. var locals = {
  9670. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  9671. $element: $element,
  9672. $attrs: attrs,
  9673. $transclude: transcludeFn
  9674. };
  9675. var controller = directive.controller;
  9676. if (controller === '@') {
  9677. controller = attrs[directive.name];
  9678. }
  9679. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  9680. // For directives with element transclusion the element is a comment.
  9681. // In this case .data will not attach any data.
  9682. // Instead, we save the controllers for the element in a local hash and attach to .data
  9683. // later, once we have the actual element.
  9684. elementControllers[directive.name] = controllerInstance;
  9685. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  9686. }
  9687. return elementControllers;
  9688. }
  9689. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  9690. // or child scope created. For instance:
  9691. // * if the directive has been pulled into a template because another directive with a higher priority
  9692. // asked for element transclusion
  9693. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  9694. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  9695. function markDirectiveScope(directives, isolateScope, newScope) {
  9696. for (var j = 0, jj = directives.length; j < jj; j++) {
  9697. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  9698. }
  9699. }
  9700. /**
  9701. * looks up the directive and decorates it with exception handling and proper parameters. We
  9702. * call this the boundDirective.
  9703. *
  9704. * @param {string} name name of the directive to look up.
  9705. * @param {string} location The directive must be found in specific format.
  9706. * String containing any of theses characters:
  9707. *
  9708. * * `E`: element name
  9709. * * `A': attribute
  9710. * * `C`: class
  9711. * * `M`: comment
  9712. * @returns {boolean} true if directive was added.
  9713. */
  9714. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  9715. endAttrName) {
  9716. if (name === ignoreDirective) return null;
  9717. var match = null;
  9718. if (hasDirectives.hasOwnProperty(name)) {
  9719. for (var directive, directives = $injector.get(name + Suffix),
  9720. i = 0, ii = directives.length; i < ii; i++) {
  9721. directive = directives[i];
  9722. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  9723. directive.restrict.indexOf(location) !== -1) {
  9724. if (startAttrName) {
  9725. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  9726. }
  9727. if (!directive.$$bindings) {
  9728. var bindings = directive.$$bindings =
  9729. parseDirectiveBindings(directive, directive.name);
  9730. if (isObject(bindings.isolateScope)) {
  9731. directive.$$isolateBindings = bindings.isolateScope;
  9732. }
  9733. }
  9734. tDirectives.push(directive);
  9735. match = directive;
  9736. }
  9737. }
  9738. }
  9739. return match;
  9740. }
  9741. /**
  9742. * looks up the directive and returns true if it is a multi-element directive,
  9743. * and therefore requires DOM nodes between -start and -end markers to be grouped
  9744. * together.
  9745. *
  9746. * @param {string} name name of the directive to look up.
  9747. * @returns true if directive was registered as multi-element.
  9748. */
  9749. function directiveIsMultiElement(name) {
  9750. if (hasDirectives.hasOwnProperty(name)) {
  9751. for (var directive, directives = $injector.get(name + Suffix),
  9752. i = 0, ii = directives.length; i < ii; i++) {
  9753. directive = directives[i];
  9754. if (directive.multiElement) {
  9755. return true;
  9756. }
  9757. }
  9758. }
  9759. return false;
  9760. }
  9761. /**
  9762. * When the element is replaced with HTML template then the new attributes
  9763. * on the template need to be merged with the existing attributes in the DOM.
  9764. * The desired effect is to have both of the attributes present.
  9765. *
  9766. * @param {object} dst destination attributes (original DOM)
  9767. * @param {object} src source attributes (from the directive template)
  9768. */
  9769. function mergeTemplateAttributes(dst, src) {
  9770. var srcAttr = src.$attr,
  9771. dstAttr = dst.$attr;
  9772. // reapply the old attributes to the new element
  9773. forEach(dst, function(value, key) {
  9774. if (key.charAt(0) !== '$') {
  9775. if (src[key] && src[key] !== value) {
  9776. if (value.length) {
  9777. value += (key === 'style' ? ';' : ' ') + src[key];
  9778. } else {
  9779. value = src[key];
  9780. }
  9781. }
  9782. dst.$set(key, value, true, srcAttr[key]);
  9783. }
  9784. });
  9785. // copy the new attributes on the old attrs object
  9786. forEach(src, function(value, key) {
  9787. // Check if we already set this attribute in the loop above.
  9788. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  9789. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  9790. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  9791. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  9792. dst[key] = value;
  9793. if (key !== 'class' && key !== 'style') {
  9794. dstAttr[key] = srcAttr[key];
  9795. }
  9796. }
  9797. });
  9798. }
  9799. function compileTemplateUrl(directives, $compileNode, tAttrs,
  9800. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  9801. var linkQueue = [],
  9802. afterTemplateNodeLinkFn,
  9803. afterTemplateChildLinkFn,
  9804. beforeTemplateCompileNode = $compileNode[0],
  9805. origAsyncDirective = directives.shift(),
  9806. derivedSyncDirective = inherit(origAsyncDirective, {
  9807. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  9808. }),
  9809. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  9810. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  9811. : origAsyncDirective.templateUrl,
  9812. templateNamespace = origAsyncDirective.templateNamespace;
  9813. $compileNode.empty();
  9814. $templateRequest(templateUrl)
  9815. .then(function(content) {
  9816. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  9817. content = denormalizeTemplate(content);
  9818. if (origAsyncDirective.replace) {
  9819. if (jqLiteIsTextNode(content)) {
  9820. $template = [];
  9821. } else {
  9822. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  9823. }
  9824. compileNode = $template[0];
  9825. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  9826. throw $compileMinErr('tplrt',
  9827. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  9828. origAsyncDirective.name, templateUrl);
  9829. }
  9830. tempTemplateAttrs = {$attr: {}};
  9831. replaceWith($rootElement, $compileNode, compileNode);
  9832. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  9833. if (isObject(origAsyncDirective.scope)) {
  9834. // the original directive that caused the template to be loaded async required
  9835. // an isolate scope
  9836. markDirectiveScope(templateDirectives, true);
  9837. }
  9838. directives = templateDirectives.concat(directives);
  9839. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  9840. } else {
  9841. compileNode = beforeTemplateCompileNode;
  9842. $compileNode.html(content);
  9843. }
  9844. directives.unshift(derivedSyncDirective);
  9845. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  9846. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  9847. previousCompileContext);
  9848. forEach($rootElement, function(node, i) {
  9849. if (node === compileNode) {
  9850. $rootElement[i] = $compileNode[0];
  9851. }
  9852. });
  9853. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  9854. while (linkQueue.length) {
  9855. var scope = linkQueue.shift(),
  9856. beforeTemplateLinkNode = linkQueue.shift(),
  9857. linkRootElement = linkQueue.shift(),
  9858. boundTranscludeFn = linkQueue.shift(),
  9859. linkNode = $compileNode[0];
  9860. if (scope.$$destroyed) continue;
  9861. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  9862. var oldClasses = beforeTemplateLinkNode.className;
  9863. if (!(previousCompileContext.hasElementTranscludeDirective &&
  9864. origAsyncDirective.replace)) {
  9865. // it was cloned therefore we have to clone as well.
  9866. linkNode = jqLiteClone(compileNode);
  9867. }
  9868. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  9869. // Copy in CSS classes from original node
  9870. safeAddClass(jqLite(linkNode), oldClasses);
  9871. }
  9872. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9873. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9874. } else {
  9875. childBoundTranscludeFn = boundTranscludeFn;
  9876. }
  9877. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  9878. childBoundTranscludeFn);
  9879. }
  9880. linkQueue = null;
  9881. }).catch(function(error) {
  9882. if (isError(error)) {
  9883. $exceptionHandler(error);
  9884. }
  9885. });
  9886. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  9887. var childBoundTranscludeFn = boundTranscludeFn;
  9888. if (scope.$$destroyed) return;
  9889. if (linkQueue) {
  9890. linkQueue.push(scope,
  9891. node,
  9892. rootElement,
  9893. childBoundTranscludeFn);
  9894. } else {
  9895. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9896. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9897. }
  9898. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  9899. }
  9900. };
  9901. }
  9902. /**
  9903. * Sorting function for bound directives.
  9904. */
  9905. function byPriority(a, b) {
  9906. var diff = b.priority - a.priority;
  9907. if (diff !== 0) return diff;
  9908. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  9909. return a.index - b.index;
  9910. }
  9911. function assertNoDuplicate(what, previousDirective, directive, element) {
  9912. function wrapModuleNameIfDefined(moduleName) {
  9913. return moduleName ?
  9914. (' (module: ' + moduleName + ')') :
  9915. '';
  9916. }
  9917. if (previousDirective) {
  9918. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  9919. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  9920. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  9921. }
  9922. }
  9923. function addTextInterpolateDirective(directives, text) {
  9924. var interpolateFn = $interpolate(text, true);
  9925. if (interpolateFn) {
  9926. directives.push({
  9927. priority: 0,
  9928. compile: function textInterpolateCompileFn(templateNode) {
  9929. var templateNodeParent = templateNode.parent(),
  9930. hasCompileParent = !!templateNodeParent.length;
  9931. // When transcluding a template that has bindings in the root
  9932. // we don't have a parent and thus need to add the class during linking fn.
  9933. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  9934. return function textInterpolateLinkFn(scope, node) {
  9935. var parent = node.parent();
  9936. if (!hasCompileParent) compile.$$addBindingClass(parent);
  9937. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  9938. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  9939. node[0].nodeValue = value;
  9940. });
  9941. };
  9942. }
  9943. });
  9944. }
  9945. }
  9946. function wrapTemplate(type, template) {
  9947. type = lowercase(type || 'html');
  9948. switch (type) {
  9949. case 'svg':
  9950. case 'math':
  9951. var wrapper = window.document.createElement('div');
  9952. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  9953. return wrapper.childNodes[0].childNodes;
  9954. default:
  9955. return template;
  9956. }
  9957. }
  9958. function getTrustedAttrContext(nodeName, attrNormalizedName) {
  9959. if (attrNormalizedName === 'srcdoc') {
  9960. return $sce.HTML;
  9961. }
  9962. // All nodes with src attributes require a RESOURCE_URL value, except for
  9963. // img and various html5 media nodes, which require the MEDIA_URL context.
  9964. if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
  9965. if (['img', 'video', 'audio', 'source', 'track'].indexOf(nodeName) === -1) {
  9966. return $sce.RESOURCE_URL;
  9967. }
  9968. return $sce.MEDIA_URL;
  9969. } else if (attrNormalizedName === 'xlinkHref') {
  9970. // Some xlink:href are okay, most aren't
  9971. if (nodeName === 'image') return $sce.MEDIA_URL;
  9972. if (nodeName === 'a') return $sce.URL;
  9973. return $sce.RESOURCE_URL;
  9974. } else if (
  9975. // Formaction
  9976. (nodeName === 'form' && attrNormalizedName === 'action') ||
  9977. // If relative URLs can go where they are not expected to, then
  9978. // all sorts of trust issues can arise.
  9979. (nodeName === 'base' && attrNormalizedName === 'href') ||
  9980. // links can be stylesheets or imports, which can run script in the current origin
  9981. (nodeName === 'link' && attrNormalizedName === 'href')
  9982. ) {
  9983. return $sce.RESOURCE_URL;
  9984. } else if (nodeName === 'a' && (attrNormalizedName === 'href' ||
  9985. attrNormalizedName === 'ngHref')) {
  9986. return $sce.URL;
  9987. }
  9988. }
  9989. function getTrustedPropContext(nodeName, propNormalizedName) {
  9990. var prop = propNormalizedName.toLowerCase();
  9991. return PROP_CONTEXTS[nodeName + '|' + prop] || PROP_CONTEXTS['*|' + prop];
  9992. }
  9993. function sanitizeSrcsetPropertyValue(value) {
  9994. return sanitizeSrcset($sce.valueOf(value), 'ng-prop-srcset');
  9995. }
  9996. function addPropertyDirective(node, directives, attrName, propName) {
  9997. if (EVENT_HANDLER_ATTR_REGEXP.test(propName)) {
  9998. throw $compileMinErr('nodomevents', 'Property bindings for HTML DOM event properties are disallowed');
  9999. }
  10000. var nodeName = nodeName_(node);
  10001. var trustedContext = getTrustedPropContext(nodeName, propName);
  10002. var sanitizer = identity;
  10003. // Sanitize img[srcset] + source[srcset] values.
  10004. if (propName === 'srcset' && (nodeName === 'img' || nodeName === 'source')) {
  10005. sanitizer = sanitizeSrcsetPropertyValue;
  10006. } else if (trustedContext) {
  10007. sanitizer = $sce.getTrusted.bind($sce, trustedContext);
  10008. }
  10009. directives.push({
  10010. priority: 100,
  10011. compile: function ngPropCompileFn(_, attr) {
  10012. var ngPropGetter = $parse(attr[attrName]);
  10013. var ngPropWatch = $parse(attr[attrName], function sceValueOf(val) {
  10014. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  10015. return $sce.valueOf(val);
  10016. });
  10017. return {
  10018. pre: function ngPropPreLinkFn(scope, $element) {
  10019. function applyPropValue() {
  10020. var propValue = ngPropGetter(scope);
  10021. $element.prop(propName, sanitizer(propValue));
  10022. }
  10023. applyPropValue();
  10024. scope.$watch(ngPropWatch, applyPropValue);
  10025. }
  10026. };
  10027. }
  10028. });
  10029. }
  10030. function addEventDirective(directives, attrName, eventName) {
  10031. directives.push(
  10032. createEventDirective($parse, $rootScope, $exceptionHandler, attrName, eventName, /*forceAsync=*/false)
  10033. );
  10034. }
  10035. function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {
  10036. var nodeName = nodeName_(node);
  10037. var trustedContext = getTrustedAttrContext(nodeName, name);
  10038. var mustHaveExpression = !isNgAttr;
  10039. var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;
  10040. var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
  10041. // no interpolation found -> ignore
  10042. if (!interpolateFn) return;
  10043. if (name === 'multiple' && nodeName === 'select') {
  10044. throw $compileMinErr('selmulti',
  10045. 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
  10046. startingTag(node));
  10047. }
  10048. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  10049. throw $compileMinErr('nodomevents', 'Interpolations for HTML DOM event attributes are disallowed');
  10050. }
  10051. directives.push({
  10052. priority: 100,
  10053. compile: function() {
  10054. return {
  10055. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  10056. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  10057. // If the attribute has changed since last $interpolate()ed
  10058. var newValue = attr[name];
  10059. if (newValue !== value) {
  10060. // we need to interpolate again since the attribute value has been updated
  10061. // (e.g. by another directive's compile function)
  10062. // ensure unset/empty values make interpolateFn falsy
  10063. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  10064. value = newValue;
  10065. }
  10066. // if attribute was updated so that there is no interpolation going on we don't want to
  10067. // register any observers
  10068. if (!interpolateFn) return;
  10069. // initialize attr object so that it's ready in case we need the value for isolate
  10070. // scope initialization, otherwise the value would not be available from isolate
  10071. // directive's linking fn during linking phase
  10072. attr[name] = interpolateFn(scope);
  10073. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  10074. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  10075. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  10076. //special case for class attribute addition + removal
  10077. //so that class changes can tap into the animation
  10078. //hooks provided by the $animate service. Be sure to
  10079. //skip animations when the first digest occurs (when
  10080. //both the new and the old values are the same) since
  10081. //the CSS classes are the non-interpolated values
  10082. if (name === 'class' && newValue !== oldValue) {
  10083. attr.$updateClass(newValue, oldValue);
  10084. } else {
  10085. attr.$set(name, newValue);
  10086. }
  10087. });
  10088. }
  10089. };
  10090. }
  10091. });
  10092. }
  10093. /**
  10094. * This is a special jqLite.replaceWith, which can replace items which
  10095. * have no parents, provided that the containing jqLite collection is provided.
  10096. *
  10097. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  10098. * in the root of the tree.
  10099. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  10100. * the shell, but replace its DOM node reference.
  10101. * @param {Node} newNode The new DOM node.
  10102. */
  10103. function replaceWith($rootElement, elementsToRemove, newNode) {
  10104. var firstElementToRemove = elementsToRemove[0],
  10105. removeCount = elementsToRemove.length,
  10106. parent = firstElementToRemove.parentNode,
  10107. i, ii;
  10108. if ($rootElement) {
  10109. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  10110. if ($rootElement[i] === firstElementToRemove) {
  10111. $rootElement[i++] = newNode;
  10112. for (var j = i, j2 = j + removeCount - 1,
  10113. jj = $rootElement.length;
  10114. j < jj; j++, j2++) {
  10115. if (j2 < jj) {
  10116. $rootElement[j] = $rootElement[j2];
  10117. } else {
  10118. delete $rootElement[j];
  10119. }
  10120. }
  10121. $rootElement.length -= removeCount - 1;
  10122. // If the replaced element is also the jQuery .context then replace it
  10123. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  10124. // http://api.jquery.com/context/
  10125. if ($rootElement.context === firstElementToRemove) {
  10126. $rootElement.context = newNode;
  10127. }
  10128. break;
  10129. }
  10130. }
  10131. }
  10132. if (parent) {
  10133. parent.replaceChild(newNode, firstElementToRemove);
  10134. }
  10135. // Append all the `elementsToRemove` to a fragment. This will...
  10136. // - remove them from the DOM
  10137. // - allow them to still be traversed with .nextSibling
  10138. // - allow a single fragment.qSA to fetch all elements being removed
  10139. var fragment = window.document.createDocumentFragment();
  10140. for (i = 0; i < removeCount; i++) {
  10141. fragment.appendChild(elementsToRemove[i]);
  10142. }
  10143. if (jqLite.hasData(firstElementToRemove)) {
  10144. // Copy over user data (that includes AngularJS's $scope etc.). Don't copy private
  10145. // data here because there's no public interface in jQuery to do that and copying over
  10146. // event listeners (which is the main use of private data) wouldn't work anyway.
  10147. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  10148. // Remove $destroy event listeners from `firstElementToRemove`
  10149. jqLite(firstElementToRemove).off('$destroy');
  10150. }
  10151. // Cleanup any data/listeners on the elements and children.
  10152. // This includes invoking the $destroy event on any elements with listeners.
  10153. jqLite.cleanData(fragment.querySelectorAll('*'));
  10154. // Update the jqLite collection to only contain the `newNode`
  10155. for (i = 1; i < removeCount; i++) {
  10156. delete elementsToRemove[i];
  10157. }
  10158. elementsToRemove[0] = newNode;
  10159. elementsToRemove.length = 1;
  10160. }
  10161. function cloneAndAnnotateFn(fn, annotation) {
  10162. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  10163. }
  10164. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  10165. try {
  10166. linkFn(scope, $element, attrs, controllers, transcludeFn);
  10167. } catch (e) {
  10168. $exceptionHandler(e, startingTag($element));
  10169. }
  10170. }
  10171. function strictBindingsCheck(attrName, directiveName) {
  10172. if (strictComponentBindingsEnabled) {
  10173. throw $compileMinErr('missingattr',
  10174. 'Attribute \'{0}\' of \'{1}\' is non-optional and must be set!',
  10175. attrName, directiveName);
  10176. }
  10177. }
  10178. // Set up $watches for isolate scope and controller bindings.
  10179. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  10180. var removeWatchCollection = [];
  10181. var initialChanges = {};
  10182. var changes;
  10183. forEach(bindings, function initializeBinding(definition, scopeName) {
  10184. var attrName = definition.attrName,
  10185. optional = definition.optional,
  10186. mode = definition.mode, // @, =, <, or &
  10187. lastValue,
  10188. parentGet, parentSet, compare, removeWatch;
  10189. switch (mode) {
  10190. case '@':
  10191. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  10192. strictBindingsCheck(attrName, directive.name);
  10193. destination[scopeName] = attrs[attrName] = undefined;
  10194. }
  10195. removeWatch = attrs.$observe(attrName, function(value) {
  10196. if (isString(value) || isBoolean(value)) {
  10197. var oldValue = destination[scopeName];
  10198. recordChanges(scopeName, value, oldValue);
  10199. destination[scopeName] = value;
  10200. }
  10201. });
  10202. attrs.$$observers[attrName].$$scope = scope;
  10203. lastValue = attrs[attrName];
  10204. if (isString(lastValue)) {
  10205. // If the attribute has been provided then we trigger an interpolation to ensure
  10206. // the value is there for use in the link fn
  10207. destination[scopeName] = $interpolate(lastValue)(scope);
  10208. } else if (isBoolean(lastValue)) {
  10209. // If the attributes is one of the BOOLEAN_ATTR then AngularJS will have converted
  10210. // the value to boolean rather than a string, so we special case this situation
  10211. destination[scopeName] = lastValue;
  10212. }
  10213. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  10214. removeWatchCollection.push(removeWatch);
  10215. break;
  10216. case '=':
  10217. if (!hasOwnProperty.call(attrs, attrName)) {
  10218. if (optional) break;
  10219. strictBindingsCheck(attrName, directive.name);
  10220. attrs[attrName] = undefined;
  10221. }
  10222. if (optional && !attrs[attrName]) break;
  10223. parentGet = $parse(attrs[attrName]);
  10224. if (parentGet.literal) {
  10225. compare = equals;
  10226. } else {
  10227. compare = simpleCompare;
  10228. }
  10229. parentSet = parentGet.assign || function() {
  10230. // reset the change, or we will throw this exception on every $digest
  10231. lastValue = destination[scopeName] = parentGet(scope);
  10232. throw $compileMinErr('nonassign',
  10233. 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
  10234. attrs[attrName], attrName, directive.name);
  10235. };
  10236. lastValue = destination[scopeName] = parentGet(scope);
  10237. var parentValueWatch = function parentValueWatch(parentValue) {
  10238. if (!compare(parentValue, destination[scopeName])) {
  10239. // we are out of sync and need to copy
  10240. if (!compare(parentValue, lastValue)) {
  10241. // parent changed and it has precedence
  10242. destination[scopeName] = parentValue;
  10243. } else {
  10244. // if the parent can be assigned then do so
  10245. parentSet(scope, parentValue = destination[scopeName]);
  10246. }
  10247. }
  10248. lastValue = parentValue;
  10249. return lastValue;
  10250. };
  10251. parentValueWatch.$stateful = true;
  10252. if (definition.collection) {
  10253. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  10254. } else {
  10255. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  10256. }
  10257. removeWatchCollection.push(removeWatch);
  10258. break;
  10259. case '<':
  10260. if (!hasOwnProperty.call(attrs, attrName)) {
  10261. if (optional) break;
  10262. strictBindingsCheck(attrName, directive.name);
  10263. attrs[attrName] = undefined;
  10264. }
  10265. if (optional && !attrs[attrName]) break;
  10266. parentGet = $parse(attrs[attrName]);
  10267. var isLiteral = parentGet.literal;
  10268. var initialValue = destination[scopeName] = parentGet(scope);
  10269. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  10270. removeWatch = scope[definition.collection ? '$watchCollection' : '$watch'](parentGet, function parentValueWatchAction(newValue, oldValue) {
  10271. if (oldValue === newValue) {
  10272. if (oldValue === initialValue || (isLiteral && equals(oldValue, initialValue))) {
  10273. return;
  10274. }
  10275. oldValue = initialValue;
  10276. }
  10277. recordChanges(scopeName, newValue, oldValue);
  10278. destination[scopeName] = newValue;
  10279. });
  10280. removeWatchCollection.push(removeWatch);
  10281. break;
  10282. case '&':
  10283. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  10284. strictBindingsCheck(attrName, directive.name);
  10285. }
  10286. // Don't assign Object.prototype method to scope
  10287. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  10288. // Don't assign noop to destination if expression is not valid
  10289. if (parentGet === noop && optional) break;
  10290. destination[scopeName] = function(locals) {
  10291. return parentGet(scope, locals);
  10292. };
  10293. break;
  10294. }
  10295. });
  10296. function recordChanges(key, currentValue, previousValue) {
  10297. if (isFunction(destination.$onChanges) && !simpleCompare(currentValue, previousValue)) {
  10298. // If we have not already scheduled the top level onChangesQueue handler then do so now
  10299. if (!onChangesQueue) {
  10300. scope.$$postDigest(flushOnChangesQueue);
  10301. onChangesQueue = [];
  10302. }
  10303. // If we have not already queued a trigger of onChanges for this controller then do so now
  10304. if (!changes) {
  10305. changes = {};
  10306. onChangesQueue.push(triggerOnChangesHook);
  10307. }
  10308. // If the has been a change on this property already then we need to reuse the previous value
  10309. if (changes[key]) {
  10310. previousValue = changes[key].previousValue;
  10311. }
  10312. // Store this change
  10313. changes[key] = new SimpleChange(previousValue, currentValue);
  10314. }
  10315. }
  10316. function triggerOnChangesHook() {
  10317. destination.$onChanges(changes);
  10318. // Now clear the changes so that we schedule onChanges when more changes arrive
  10319. changes = undefined;
  10320. }
  10321. return {
  10322. initialChanges: initialChanges,
  10323. removeWatches: removeWatchCollection.length && function removeWatches() {
  10324. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  10325. removeWatchCollection[i]();
  10326. }
  10327. }
  10328. };
  10329. }
  10330. }];
  10331. }
  10332. function SimpleChange(previous, current) {
  10333. this.previousValue = previous;
  10334. this.currentValue = current;
  10335. }
  10336. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  10337. var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
  10338. var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
  10339. /**
  10340. * Converts all accepted directives format into proper directive name.
  10341. * @param name Name to normalize
  10342. */
  10343. function directiveNormalize(name) {
  10344. return name
  10345. .replace(PREFIX_REGEXP, '')
  10346. .replace(SPECIAL_CHARS_REGEXP, function(_, letter, offset) {
  10347. return offset ? letter.toUpperCase() : letter;
  10348. });
  10349. }
  10350. /**
  10351. * @ngdoc type
  10352. * @name $compile.directive.Attributes
  10353. *
  10354. * @description
  10355. * A shared object between directive compile / linking functions which contains normalized DOM
  10356. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  10357. * needed since all of these are treated as equivalent in AngularJS:
  10358. *
  10359. * ```
  10360. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  10361. * ```
  10362. */
  10363. /**
  10364. * @ngdoc property
  10365. * @name $compile.directive.Attributes#$attr
  10366. *
  10367. * @description
  10368. * A map of DOM element attribute names to the normalized name. This is
  10369. * needed to do reverse lookup from normalized name back to actual name.
  10370. */
  10371. /**
  10372. * @ngdoc method
  10373. * @name $compile.directive.Attributes#$set
  10374. * @kind function
  10375. *
  10376. * @description
  10377. * Set DOM element attribute value.
  10378. *
  10379. *
  10380. * @param {string} name Normalized element attribute name of the property to modify. The name is
  10381. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  10382. * property to the original name.
  10383. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  10384. */
  10385. /**
  10386. * Closure compiler type information
  10387. */
  10388. function nodesetLinkingFn(
  10389. /* angular.Scope */ scope,
  10390. /* NodeList */ nodeList,
  10391. /* Element */ rootElement,
  10392. /* function(Function) */ boundTranscludeFn
  10393. ) {}
  10394. function directiveLinkingFn(
  10395. /* nodesetLinkingFn */ nodesetLinkingFn,
  10396. /* angular.Scope */ scope,
  10397. /* Node */ node,
  10398. /* Element */ rootElement,
  10399. /* function(Function) */ boundTranscludeFn
  10400. ) {}
  10401. function tokenDifference(str1, str2) {
  10402. var values = '',
  10403. tokens1 = str1.split(/\s+/),
  10404. tokens2 = str2.split(/\s+/);
  10405. outer:
  10406. for (var i = 0; i < tokens1.length; i++) {
  10407. var token = tokens1[i];
  10408. for (var j = 0; j < tokens2.length; j++) {
  10409. if (token === tokens2[j]) continue outer;
  10410. }
  10411. values += (values.length > 0 ? ' ' : '') + token;
  10412. }
  10413. return values;
  10414. }
  10415. function removeComments(jqNodes) {
  10416. jqNodes = jqLite(jqNodes);
  10417. var i = jqNodes.length;
  10418. if (i <= 1) {
  10419. return jqNodes;
  10420. }
  10421. while (i--) {
  10422. var node = jqNodes[i];
  10423. if (node.nodeType === NODE_TYPE_COMMENT ||
  10424. (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {
  10425. splice.call(jqNodes, i, 1);
  10426. }
  10427. }
  10428. return jqNodes;
  10429. }
  10430. var $controllerMinErr = minErr('$controller');
  10431. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  10432. function identifierForController(controller, ident) {
  10433. if (ident && isString(ident)) return ident;
  10434. if (isString(controller)) {
  10435. var match = CNTRL_REG.exec(controller);
  10436. if (match) return match[3];
  10437. }
  10438. }
  10439. /**
  10440. * @ngdoc provider
  10441. * @name $controllerProvider
  10442. * @this
  10443. *
  10444. * @description
  10445. * The {@link ng.$controller $controller service} is used by AngularJS to create new
  10446. * controllers.
  10447. *
  10448. * This provider allows controller registration via the
  10449. * {@link ng.$controllerProvider#register register} method.
  10450. */
  10451. function $ControllerProvider() {
  10452. var controllers = {};
  10453. /**
  10454. * @ngdoc method
  10455. * @name $controllerProvider#has
  10456. * @param {string} name Controller name to check.
  10457. */
  10458. this.has = function(name) {
  10459. return controllers.hasOwnProperty(name);
  10460. };
  10461. /**
  10462. * @ngdoc method
  10463. * @name $controllerProvider#register
  10464. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  10465. * the names and the values are the constructors.
  10466. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  10467. * annotations in the array notation).
  10468. */
  10469. this.register = function(name, constructor) {
  10470. assertNotHasOwnProperty(name, 'controller');
  10471. if (isObject(name)) {
  10472. extend(controllers, name);
  10473. } else {
  10474. controllers[name] = constructor;
  10475. }
  10476. };
  10477. this.$get = ['$injector', function($injector) {
  10478. /**
  10479. * @ngdoc service
  10480. * @name $controller
  10481. * @requires $injector
  10482. *
  10483. * @param {Function|string} constructor If called with a function then it's considered to be the
  10484. * controller constructor function. Otherwise it's considered to be a string which is used
  10485. * to retrieve the controller constructor using the following steps:
  10486. *
  10487. * * check if a controller with given name is registered via `$controllerProvider`
  10488. * * check if evaluating the string on the current scope returns a constructor
  10489. *
  10490. * The string can use the `controller as property` syntax, where the controller instance is published
  10491. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  10492. * to work correctly.
  10493. *
  10494. * @param {Object} locals Injection locals for Controller.
  10495. * @return {Object} Instance of given controller.
  10496. *
  10497. * @description
  10498. * `$controller` service is responsible for instantiating controllers.
  10499. *
  10500. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  10501. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  10502. */
  10503. return function $controller(expression, locals, later, ident) {
  10504. // PRIVATE API:
  10505. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  10506. // If true, $controller will allocate the object with the correct
  10507. // prototype chain, but will not invoke the controller until a returned
  10508. // callback is invoked.
  10509. // param `ident` --- An optional label which overrides the label parsed from the controller
  10510. // expression, if any.
  10511. var instance, match, constructor, identifier;
  10512. later = later === true;
  10513. if (ident && isString(ident)) {
  10514. identifier = ident;
  10515. }
  10516. if (isString(expression)) {
  10517. match = expression.match(CNTRL_REG);
  10518. if (!match) {
  10519. throw $controllerMinErr('ctrlfmt',
  10520. 'Badly formed controller string \'{0}\'. ' +
  10521. 'Must match `__name__ as __id__` or `__name__`.', expression);
  10522. }
  10523. constructor = match[1];
  10524. identifier = identifier || match[3];
  10525. expression = controllers.hasOwnProperty(constructor)
  10526. ? controllers[constructor]
  10527. : getter(locals.$scope, constructor, true);
  10528. if (!expression) {
  10529. throw $controllerMinErr('ctrlreg',
  10530. 'The controller with the name \'{0}\' is not registered.', constructor);
  10531. }
  10532. assertArgFn(expression, constructor, true);
  10533. }
  10534. if (later) {
  10535. // Instantiate controller later:
  10536. // This machinery is used to create an instance of the object before calling the
  10537. // controller's constructor itself.
  10538. //
  10539. // This allows properties to be added to the controller before the constructor is
  10540. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  10541. //
  10542. // This feature is not intended for use by applications, and is thus not documented
  10543. // publicly.
  10544. // Object creation: http://jsperf.com/create-constructor/2
  10545. var controllerPrototype = (isArray(expression) ?
  10546. expression[expression.length - 1] : expression).prototype;
  10547. instance = Object.create(controllerPrototype || null);
  10548. if (identifier) {
  10549. addIdentifier(locals, identifier, instance, constructor || expression.name);
  10550. }
  10551. return extend(function $controllerInit() {
  10552. var result = $injector.invoke(expression, instance, locals, constructor);
  10553. if (result !== instance && (isObject(result) || isFunction(result))) {
  10554. instance = result;
  10555. if (identifier) {
  10556. // If result changed, re-assign controllerAs value to scope.
  10557. addIdentifier(locals, identifier, instance, constructor || expression.name);
  10558. }
  10559. }
  10560. return instance;
  10561. }, {
  10562. instance: instance,
  10563. identifier: identifier
  10564. });
  10565. }
  10566. instance = $injector.instantiate(expression, locals, constructor);
  10567. if (identifier) {
  10568. addIdentifier(locals, identifier, instance, constructor || expression.name);
  10569. }
  10570. return instance;
  10571. };
  10572. function addIdentifier(locals, identifier, instance, name) {
  10573. if (!(locals && isObject(locals.$scope))) {
  10574. throw minErr('$controller')('noscp',
  10575. 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
  10576. name, identifier);
  10577. }
  10578. locals.$scope[identifier] = instance;
  10579. }
  10580. }];
  10581. }
  10582. /**
  10583. * @ngdoc service
  10584. * @name $document
  10585. * @requires $window
  10586. * @this
  10587. *
  10588. * @description
  10589. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  10590. *
  10591. * @example
  10592. <example module="documentExample" name="document">
  10593. <file name="index.html">
  10594. <div ng-controller="ExampleController">
  10595. <p>$document title: <b ng-bind="title"></b></p>
  10596. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  10597. </div>
  10598. </file>
  10599. <file name="script.js">
  10600. angular.module('documentExample', [])
  10601. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  10602. $scope.title = $document[0].title;
  10603. $scope.windowTitle = angular.element(window.document)[0].title;
  10604. }]);
  10605. </file>
  10606. </example>
  10607. */
  10608. function $DocumentProvider() {
  10609. this.$get = ['$window', function(window) {
  10610. return jqLite(window.document);
  10611. }];
  10612. }
  10613. /**
  10614. * @private
  10615. * @this
  10616. * Listens for document visibility change and makes the current status accessible.
  10617. */
  10618. function $$IsDocumentHiddenProvider() {
  10619. this.$get = ['$document', '$rootScope', function($document, $rootScope) {
  10620. var doc = $document[0];
  10621. var hidden = doc && doc.hidden;
  10622. $document.on('visibilitychange', changeListener);
  10623. $rootScope.$on('$destroy', function() {
  10624. $document.off('visibilitychange', changeListener);
  10625. });
  10626. function changeListener() {
  10627. hidden = doc.hidden;
  10628. }
  10629. return function() {
  10630. return hidden;
  10631. };
  10632. }];
  10633. }
  10634. /**
  10635. * @ngdoc service
  10636. * @name $exceptionHandler
  10637. * @requires ng.$log
  10638. * @this
  10639. *
  10640. * @description
  10641. * Any uncaught exception in AngularJS expressions is delegated to this service.
  10642. * The default implementation simply delegates to `$log.error` which logs it into
  10643. * the browser console.
  10644. *
  10645. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  10646. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  10647. *
  10648. * ## Example:
  10649. *
  10650. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  10651. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  10652. * of `$log.error()`.
  10653. *
  10654. * ```js
  10655. * angular.
  10656. * module('exceptionOverwrite', []).
  10657. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  10658. * return function myExceptionHandler(exception, cause) {
  10659. * logErrorsToBackend(exception, cause);
  10660. * $log.warn(exception, cause);
  10661. * };
  10662. * }]);
  10663. * ```
  10664. *
  10665. * <hr />
  10666. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  10667. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  10668. * (unless executed during a digest).
  10669. *
  10670. * If you wish, you can manually delegate exceptions, e.g.
  10671. * `try { ... } catch(e) { $exceptionHandler(e); }`
  10672. *
  10673. * @param {Error} exception Exception associated with the error.
  10674. * @param {string=} cause Optional information about the context in which
  10675. * the error was thrown.
  10676. *
  10677. */
  10678. function $ExceptionHandlerProvider() {
  10679. this.$get = ['$log', function($log) {
  10680. return function(exception, cause) {
  10681. $log.error.apply($log, arguments);
  10682. };
  10683. }];
  10684. }
  10685. var $$ForceReflowProvider = /** @this */ function() {
  10686. this.$get = ['$document', function($document) {
  10687. return function(domNode) {
  10688. //the line below will force the browser to perform a repaint so
  10689. //that all the animated elements within the animation frame will
  10690. //be properly updated and drawn on screen. This is required to
  10691. //ensure that the preparation animation is properly flushed so that
  10692. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  10693. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  10694. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  10695. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  10696. if (domNode) {
  10697. if (!domNode.nodeType && domNode instanceof jqLite) {
  10698. domNode = domNode[0];
  10699. }
  10700. } else {
  10701. domNode = $document[0].body;
  10702. }
  10703. return domNode.offsetWidth + 1;
  10704. };
  10705. }];
  10706. };
  10707. var APPLICATION_JSON = 'application/json';
  10708. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  10709. var JSON_START = /^\[|^\{(?!\{)/;
  10710. var JSON_ENDS = {
  10711. '[': /]$/,
  10712. '{': /}$/
  10713. };
  10714. var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/;
  10715. var $httpMinErr = minErr('$http');
  10716. function serializeValue(v) {
  10717. if (isObject(v)) {
  10718. return isDate(v) ? v.toISOString() : toJson(v);
  10719. }
  10720. return v;
  10721. }
  10722. /** @this */
  10723. function $HttpParamSerializerProvider() {
  10724. /**
  10725. * @ngdoc service
  10726. * @name $httpParamSerializer
  10727. * @description
  10728. *
  10729. * Default {@link $http `$http`} params serializer that converts objects to strings
  10730. * according to the following rules:
  10731. *
  10732. * * `{'foo': 'bar'}` results in `foo=bar`
  10733. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  10734. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  10735. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
  10736. *
  10737. * Note that serializer will sort the request parameters alphabetically.
  10738. */
  10739. this.$get = function() {
  10740. return function ngParamSerializer(params) {
  10741. if (!params) return '';
  10742. var parts = [];
  10743. forEachSorted(params, function(value, key) {
  10744. if (value === null || isUndefined(value) || isFunction(value)) return;
  10745. if (isArray(value)) {
  10746. forEach(value, function(v) {
  10747. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  10748. });
  10749. } else {
  10750. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  10751. }
  10752. });
  10753. return parts.join('&');
  10754. };
  10755. };
  10756. }
  10757. /** @this */
  10758. function $HttpParamSerializerJQLikeProvider() {
  10759. /**
  10760. * @ngdoc service
  10761. * @name $httpParamSerializerJQLike
  10762. *
  10763. * @description
  10764. *
  10765. * Alternative {@link $http `$http`} params serializer that follows
  10766. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  10767. * The serializer will also sort the params alphabetically.
  10768. *
  10769. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  10770. *
  10771. * ```js
  10772. * $http({
  10773. * url: myUrl,
  10774. * method: 'GET',
  10775. * params: myParams,
  10776. * paramSerializer: '$httpParamSerializerJQLike'
  10777. * });
  10778. * ```
  10779. *
  10780. * It is also possible to set it as the default `paramSerializer` in the
  10781. * {@link $httpProvider#defaults `$httpProvider`}.
  10782. *
  10783. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  10784. * form data for submission:
  10785. *
  10786. * ```js
  10787. * .controller(function($http, $httpParamSerializerJQLike) {
  10788. * //...
  10789. *
  10790. * $http({
  10791. * url: myUrl,
  10792. * method: 'POST',
  10793. * data: $httpParamSerializerJQLike(myData),
  10794. * headers: {
  10795. * 'Content-Type': 'application/x-www-form-urlencoded'
  10796. * }
  10797. * });
  10798. *
  10799. * });
  10800. * ```
  10801. *
  10802. */
  10803. this.$get = function() {
  10804. return function jQueryLikeParamSerializer(params) {
  10805. if (!params) return '';
  10806. var parts = [];
  10807. serialize(params, '', true);
  10808. return parts.join('&');
  10809. function serialize(toSerialize, prefix, topLevel) {
  10810. if (isArray(toSerialize)) {
  10811. forEach(toSerialize, function(value, index) {
  10812. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  10813. });
  10814. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  10815. forEachSorted(toSerialize, function(value, key) {
  10816. serialize(value, prefix +
  10817. (topLevel ? '' : '[') +
  10818. key +
  10819. (topLevel ? '' : ']'));
  10820. });
  10821. } else {
  10822. if (isFunction(toSerialize)) {
  10823. toSerialize = toSerialize();
  10824. }
  10825. parts.push(encodeUriQuery(prefix) + '=' +
  10826. (toSerialize == null ? '' : encodeUriQuery(serializeValue(toSerialize))));
  10827. }
  10828. }
  10829. };
  10830. };
  10831. }
  10832. function defaultHttpResponseTransform(data, headers) {
  10833. if (isString(data)) {
  10834. // Strip json vulnerability protection prefix and trim whitespace
  10835. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  10836. if (tempData) {
  10837. var contentType = headers('Content-Type');
  10838. var hasJsonContentType = contentType && (contentType.indexOf(APPLICATION_JSON) === 0);
  10839. if (hasJsonContentType || isJsonLike(tempData)) {
  10840. try {
  10841. data = fromJson(tempData);
  10842. } catch (e) {
  10843. if (!hasJsonContentType) {
  10844. return data;
  10845. }
  10846. throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' +
  10847. 'Parse error: "{1}"', data, e);
  10848. }
  10849. }
  10850. }
  10851. }
  10852. return data;
  10853. }
  10854. function isJsonLike(str) {
  10855. var jsonStart = str.match(JSON_START);
  10856. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  10857. }
  10858. /**
  10859. * Parse headers into key value object
  10860. *
  10861. * @param {string} headers Raw headers as a string
  10862. * @returns {Object} Parsed headers as key value object
  10863. */
  10864. function parseHeaders(headers) {
  10865. var parsed = createMap(), i;
  10866. function fillInParsed(key, val) {
  10867. if (key) {
  10868. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  10869. }
  10870. }
  10871. if (isString(headers)) {
  10872. forEach(headers.split('\n'), function(line) {
  10873. i = line.indexOf(':');
  10874. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  10875. });
  10876. } else if (isObject(headers)) {
  10877. forEach(headers, function(headerVal, headerKey) {
  10878. fillInParsed(lowercase(headerKey), trim(headerVal));
  10879. });
  10880. }
  10881. return parsed;
  10882. }
  10883. /**
  10884. * Returns a function that provides access to parsed headers.
  10885. *
  10886. * Headers are lazy parsed when first requested.
  10887. * @see parseHeaders
  10888. *
  10889. * @param {(string|Object)} headers Headers to provide access to.
  10890. * @returns {function(string=)} Returns a getter function which if called with:
  10891. *
  10892. * - if called with an argument returns a single header value or null
  10893. * - if called with no arguments returns an object containing all headers.
  10894. */
  10895. function headersGetter(headers) {
  10896. var headersObj;
  10897. return function(name) {
  10898. if (!headersObj) headersObj = parseHeaders(headers);
  10899. if (name) {
  10900. var value = headersObj[lowercase(name)];
  10901. if (value === undefined) {
  10902. value = null;
  10903. }
  10904. return value;
  10905. }
  10906. return headersObj;
  10907. };
  10908. }
  10909. /**
  10910. * Chain all given functions
  10911. *
  10912. * This function is used for both request and response transforming
  10913. *
  10914. * @param {*} data Data to transform.
  10915. * @param {function(string=)} headers HTTP headers getter fn.
  10916. * @param {number} status HTTP status code of the response.
  10917. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  10918. * @returns {*} Transformed data.
  10919. */
  10920. function transformData(data, headers, status, fns) {
  10921. if (isFunction(fns)) {
  10922. return fns(data, headers, status);
  10923. }
  10924. forEach(fns, function(fn) {
  10925. data = fn(data, headers, status);
  10926. });
  10927. return data;
  10928. }
  10929. function isSuccess(status) {
  10930. return 200 <= status && status < 300;
  10931. }
  10932. /**
  10933. * @ngdoc provider
  10934. * @name $httpProvider
  10935. * @this
  10936. *
  10937. * @description
  10938. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  10939. */
  10940. function $HttpProvider() {
  10941. /**
  10942. * @ngdoc property
  10943. * @name $httpProvider#defaults
  10944. * @description
  10945. *
  10946. * Object containing default values for all {@link ng.$http $http} requests.
  10947. *
  10948. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  10949. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  10950. * by default. See {@link $http#caching $http Caching} for more information.
  10951. *
  10952. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  10953. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  10954. * setting default headers.
  10955. * - **`defaults.headers.common`**
  10956. * - **`defaults.headers.post`**
  10957. * - **`defaults.headers.put`**
  10958. * - **`defaults.headers.patch`**
  10959. *
  10960. * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the
  10961. * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the
  10962. * {@link $jsonpCallbacks} service. Defaults to `'callback'`.
  10963. *
  10964. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  10965. * used to the prepare string representation of request parameters (specified as an object).
  10966. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  10967. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  10968. *
  10969. * - **`defaults.transformRequest`** -
  10970. * `{Array<function(data, headersGetter)>|function(data, headersGetter)}` -
  10971. * An array of functions (or a single function) which are applied to the request data.
  10972. * By default, this is an array with one request transformation function:
  10973. *
  10974. * - If the `data` property of the request configuration object contains an object, serialize it
  10975. * into JSON format.
  10976. *
  10977. * - **`defaults.transformResponse`** -
  10978. * `{Array<function(data, headersGetter, status)>|function(data, headersGetter, status)}` -
  10979. * An array of functions (or a single function) which are applied to the response data. By default,
  10980. * this is an array which applies one response transformation function that does two things:
  10981. *
  10982. * - If XSRF prefix is detected, strip it
  10983. * (see {@link ng.$http#security-considerations Security Considerations in the $http docs}).
  10984. * - If the `Content-Type` is `application/json` or the response looks like JSON,
  10985. * deserialize it using a JSON parser.
  10986. *
  10987. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  10988. * Defaults value is `'XSRF-TOKEN'`.
  10989. *
  10990. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  10991. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  10992. *
  10993. */
  10994. var defaults = this.defaults = {
  10995. // transform incoming response data
  10996. transformResponse: [defaultHttpResponseTransform],
  10997. // transform outgoing request data
  10998. transformRequest: [function(d) {
  10999. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  11000. }],
  11001. // default headers
  11002. headers: {
  11003. common: {
  11004. 'Accept': 'application/json, text/plain, */*'
  11005. },
  11006. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  11007. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  11008. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  11009. },
  11010. xsrfCookieName: 'XSRF-TOKEN',
  11011. xsrfHeaderName: 'X-XSRF-TOKEN',
  11012. paramSerializer: '$httpParamSerializer',
  11013. jsonpCallbackParam: 'callback'
  11014. };
  11015. var useApplyAsync = false;
  11016. /**
  11017. * @ngdoc method
  11018. * @name $httpProvider#useApplyAsync
  11019. * @description
  11020. *
  11021. * Configure $http service to combine processing of multiple http responses received at around
  11022. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  11023. * significant performance improvement for bigger applications that make many HTTP requests
  11024. * concurrently (common during application bootstrap).
  11025. *
  11026. * Defaults to false. If no value is specified, returns the current configured value.
  11027. *
  11028. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  11029. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  11030. * to load and share the same digest cycle.
  11031. *
  11032. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  11033. * otherwise, returns the current configured value.
  11034. */
  11035. this.useApplyAsync = function(value) {
  11036. if (isDefined(value)) {
  11037. useApplyAsync = !!value;
  11038. return this;
  11039. }
  11040. return useApplyAsync;
  11041. };
  11042. /**
  11043. * @ngdoc property
  11044. * @name $httpProvider#interceptors
  11045. * @description
  11046. *
  11047. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  11048. * pre-processing of request or postprocessing of responses.
  11049. *
  11050. * These service factories are ordered by request, i.e. they are applied in the same order as the
  11051. * array, on request, but reverse order, on response.
  11052. *
  11053. * {@link ng.$http#interceptors Interceptors detailed info}
  11054. */
  11055. var interceptorFactories = this.interceptors = [];
  11056. /**
  11057. * @ngdoc property
  11058. * @name $httpProvider#xsrfWhitelistedOrigins
  11059. * @description
  11060. *
  11061. * Array containing URLs whose origins are trusted to receive the XSRF token. See the
  11062. * {@link ng.$http#security-considerations Security Considerations} sections for more details on
  11063. * XSRF.
  11064. *
  11065. * **Note:** An "origin" consists of the [URI scheme](https://en.wikipedia.org/wiki/URI_scheme),
  11066. * the [hostname](https://en.wikipedia.org/wiki/Hostname) and the
  11067. * [port number](https://en.wikipedia.org/wiki/Port_(computer_networking). For `http:` and
  11068. * `https:`, the port number can be omitted if using th default ports (80 and 443 respectively).
  11069. * Examples: `http://example.com`, `https://api.example.com:9876`
  11070. *
  11071. * <div class="alert alert-warning">
  11072. * It is not possible to whitelist specific URLs/paths. The `path`, `query` and `fragment` parts
  11073. * of a URL will be ignored. For example, `https://foo.com/path/bar?query=baz#fragment` will be
  11074. * treated as `https://foo.com`, meaning that **all** requests to URLs starting with
  11075. * `https://foo.com/` will include the XSRF token.
  11076. * </div>
  11077. *
  11078. * @example
  11079. *
  11080. * ```js
  11081. * // App served from `https://example.com/`.
  11082. * angular.
  11083. * module('xsrfWhitelistedOriginsExample', []).
  11084. * config(['$httpProvider', function($httpProvider) {
  11085. * $httpProvider.xsrfWhitelistedOrigins.push('https://api.example.com');
  11086. * }]).
  11087. * run(['$http', function($http) {
  11088. * // The XSRF token will be sent.
  11089. * $http.get('https://api.example.com/preferences').then(...);
  11090. *
  11091. * // The XSRF token will NOT be sent.
  11092. * $http.get('https://stats.example.com/activity').then(...);
  11093. * }]);
  11094. * ```
  11095. */
  11096. var xsrfWhitelistedOrigins = this.xsrfWhitelistedOrigins = [];
  11097. this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
  11098. function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {
  11099. var defaultCache = $cacheFactory('$http');
  11100. /**
  11101. * Make sure that default param serializer is exposed as a function
  11102. */
  11103. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  11104. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  11105. /**
  11106. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  11107. * The reversal is needed so that we can build up the interception chain around the
  11108. * server request.
  11109. */
  11110. var reversedInterceptors = [];
  11111. forEach(interceptorFactories, function(interceptorFactory) {
  11112. reversedInterceptors.unshift(isString(interceptorFactory)
  11113. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  11114. });
  11115. /**
  11116. * A function to check request URLs against a list of allowed origins.
  11117. */
  11118. var urlIsAllowedOrigin = urlIsAllowedOriginFactory(xsrfWhitelistedOrigins);
  11119. /**
  11120. * @ngdoc service
  11121. * @kind function
  11122. * @name $http
  11123. * @requires ng.$httpBackend
  11124. * @requires $cacheFactory
  11125. * @requires $rootScope
  11126. * @requires $q
  11127. * @requires $injector
  11128. *
  11129. * @description
  11130. * The `$http` service is a core AngularJS service that facilitates communication with the remote
  11131. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  11132. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  11133. *
  11134. * For unit testing applications that use `$http` service, see
  11135. * {@link ngMock.$httpBackend $httpBackend mock}.
  11136. *
  11137. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  11138. * $resource} service.
  11139. *
  11140. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  11141. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  11142. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  11143. *
  11144. *
  11145. * ## General usage
  11146. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  11147. * that is used to generate an HTTP request and returns a {@link ng.$q promise} that is
  11148. * resolved (request success) or rejected (request failure) with a
  11149. * {@link ng.$http#$http-returns response} object.
  11150. *
  11151. * ```js
  11152. * // Simple GET request example:
  11153. * $http({
  11154. * method: 'GET',
  11155. * url: '/someUrl'
  11156. * }).then(function successCallback(response) {
  11157. * // this callback will be called asynchronously
  11158. * // when the response is available
  11159. * }, function errorCallback(response) {
  11160. * // called asynchronously if an error occurs
  11161. * // or server returns response with an error status.
  11162. * });
  11163. * ```
  11164. *
  11165. *
  11166. * ## Shortcut methods
  11167. *
  11168. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  11169. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  11170. * last argument.
  11171. *
  11172. * ```js
  11173. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  11174. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  11175. * ```
  11176. *
  11177. * Complete list of shortcut methods:
  11178. *
  11179. * - {@link ng.$http#get $http.get}
  11180. * - {@link ng.$http#head $http.head}
  11181. * - {@link ng.$http#post $http.post}
  11182. * - {@link ng.$http#put $http.put}
  11183. * - {@link ng.$http#delete $http.delete}
  11184. * - {@link ng.$http#jsonp $http.jsonp}
  11185. * - {@link ng.$http#patch $http.patch}
  11186. *
  11187. *
  11188. * ## Writing Unit Tests that use $http
  11189. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  11190. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  11191. * request using trained responses.
  11192. *
  11193. * ```
  11194. * $httpBackend.expectGET(...);
  11195. * $http.get(...);
  11196. * $httpBackend.flush();
  11197. * ```
  11198. *
  11199. * ## Setting HTTP Headers
  11200. *
  11201. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  11202. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  11203. * object, which currently contains this default configuration:
  11204. *
  11205. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  11206. * - <code>Accept: application/json, text/plain, \*&#65279;/&#65279;\*</code>
  11207. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  11208. * - `Content-Type: application/json`
  11209. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  11210. * - `Content-Type: application/json`
  11211. *
  11212. * To add or overwrite these defaults, simply add or remove a property from these configuration
  11213. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  11214. * with the lowercased HTTP method name as the key, e.g.
  11215. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  11216. *
  11217. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  11218. * fashion. For example:
  11219. *
  11220. * ```
  11221. * module.run(function($http) {
  11222. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  11223. * });
  11224. * ```
  11225. *
  11226. * In addition, you can supply a `headers` property in the config object passed when
  11227. * calling `$http(config)`, which overrides the defaults without changing them globally.
  11228. *
  11229. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  11230. * Use the `headers` property, setting the desired header to `undefined`. For example:
  11231. *
  11232. * ```js
  11233. * var req = {
  11234. * method: 'POST',
  11235. * url: 'http://example.com',
  11236. * headers: {
  11237. * 'Content-Type': undefined
  11238. * },
  11239. * data: { test: 'test' }
  11240. * }
  11241. *
  11242. * $http(req).then(function(){...}, function(){...});
  11243. * ```
  11244. *
  11245. * ## Transforming Requests and Responses
  11246. *
  11247. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  11248. * and `transformResponse`. These properties can be a single function that returns
  11249. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  11250. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  11251. *
  11252. * <div class="alert alert-warning">
  11253. * **Note:** AngularJS does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  11254. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  11255. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  11256. * function will be reflected on the scope and in any templates where the object is data-bound.
  11257. * To prevent this, transform functions should have no side-effects.
  11258. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  11259. * </div>
  11260. *
  11261. * ### Default Transformations
  11262. *
  11263. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  11264. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  11265. * then these will be applied.
  11266. *
  11267. * You can augment or replace the default transformations by modifying these properties by adding to or
  11268. * replacing the array.
  11269. *
  11270. * AngularJS provides the following default transformations:
  11271. *
  11272. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`) is
  11273. * an array with one function that does the following:
  11274. *
  11275. * - If the `data` property of the request configuration object contains an object, serialize it
  11276. * into JSON format.
  11277. *
  11278. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`) is
  11279. * an array with one function that does the following:
  11280. *
  11281. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  11282. * - If the `Content-Type` is `application/json` or the response looks like JSON,
  11283. * deserialize it using a JSON parser.
  11284. *
  11285. *
  11286. * ### Overriding the Default Transformations Per Request
  11287. *
  11288. * If you wish to override the request/response transformations only for a single request then provide
  11289. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  11290. * into `$http`.
  11291. *
  11292. * Note that if you provide these properties on the config object the default transformations will be
  11293. * overwritten. If you wish to augment the default transformations then you must include them in your
  11294. * local transformation array.
  11295. *
  11296. * The following code demonstrates adding a new response transformation to be run after the default response
  11297. * transformations have been run.
  11298. *
  11299. * ```js
  11300. * function appendTransform(defaults, transform) {
  11301. *
  11302. * // We can't guarantee that the default transformation is an array
  11303. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  11304. *
  11305. * // Append the new transformation to the defaults
  11306. * return defaults.concat(transform);
  11307. * }
  11308. *
  11309. * $http({
  11310. * url: '...',
  11311. * method: 'GET',
  11312. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  11313. * return doTransform(value);
  11314. * })
  11315. * });
  11316. * ```
  11317. *
  11318. *
  11319. * ## Caching
  11320. *
  11321. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  11322. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  11323. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  11324. * precedence over the default cache value.
  11325. *
  11326. * In order to:
  11327. * * cache all responses - set the default cache value to TRUE or to a cache object
  11328. * * cache a specific response - set config.cache value to TRUE or to a cache object
  11329. *
  11330. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  11331. * then the default `$cacheFactory("$http")` object is used.
  11332. *
  11333. * The default cache value can be set by updating the
  11334. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  11335. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  11336. *
  11337. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  11338. * the relevant cache object. The next time the same request is made, the response is returned
  11339. * from the cache without sending a request to the server.
  11340. *
  11341. * Take note that:
  11342. *
  11343. * * Only GET and JSONP requests are cached.
  11344. * * The cache key is the request URL including search parameters; headers are not considered.
  11345. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  11346. * * If multiple identical requests are made using the same cache, which is not yet populated,
  11347. * one request will be made to the server and remaining requests will return the same response.
  11348. * * A cache-control header on the response does not affect if or how responses are cached.
  11349. *
  11350. *
  11351. * ## Interceptors
  11352. *
  11353. * Before you start creating interceptors, be sure to understand the
  11354. * {@link ng.$q $q and deferred/promise APIs}.
  11355. *
  11356. * For purposes of global error handling, authentication, or any kind of synchronous or
  11357. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  11358. * able to intercept requests before they are handed to the server and
  11359. * responses before they are handed over to the application code that
  11360. * initiated these requests. The interceptors leverage the {@link ng.$q
  11361. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  11362. *
  11363. * The interceptors are service factories that are registered with the `$httpProvider` by
  11364. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  11365. * injected with dependencies (if specified) and returns the interceptor.
  11366. *
  11367. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  11368. *
  11369. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  11370. * modify the `config` object or create a new one. The function needs to return the `config`
  11371. * object directly, or a promise containing the `config` or a new `config` object.
  11372. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  11373. * resolved with a rejection.
  11374. * * `response`: interceptors get called with http `response` object. The function is free to
  11375. * modify the `response` object or create a new one. The function needs to return the `response`
  11376. * object directly, or as a promise containing the `response` or a new `response` object.
  11377. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  11378. * resolved with a rejection.
  11379. *
  11380. *
  11381. * ```js
  11382. * // register the interceptor as a service
  11383. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  11384. * return {
  11385. * // optional method
  11386. * 'request': function(config) {
  11387. * // do something on success
  11388. * return config;
  11389. * },
  11390. *
  11391. * // optional method
  11392. * 'requestError': function(rejection) {
  11393. * // do something on error
  11394. * if (canRecover(rejection)) {
  11395. * return responseOrNewPromise
  11396. * }
  11397. * return $q.reject(rejection);
  11398. * },
  11399. *
  11400. *
  11401. *
  11402. * // optional method
  11403. * 'response': function(response) {
  11404. * // do something on success
  11405. * return response;
  11406. * },
  11407. *
  11408. * // optional method
  11409. * 'responseError': function(rejection) {
  11410. * // do something on error
  11411. * if (canRecover(rejection)) {
  11412. * return responseOrNewPromise
  11413. * }
  11414. * return $q.reject(rejection);
  11415. * }
  11416. * };
  11417. * });
  11418. *
  11419. * $httpProvider.interceptors.push('myHttpInterceptor');
  11420. *
  11421. *
  11422. * // alternatively, register the interceptor via an anonymous factory
  11423. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  11424. * return {
  11425. * 'request': function(config) {
  11426. * // same as above
  11427. * },
  11428. *
  11429. * 'response': function(response) {
  11430. * // same as above
  11431. * }
  11432. * };
  11433. * });
  11434. * ```
  11435. *
  11436. * ## Security Considerations
  11437. *
  11438. * When designing web applications, consider security threats from:
  11439. *
  11440. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  11441. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  11442. *
  11443. * Both server and the client must cooperate in order to eliminate these threats. AngularJS comes
  11444. * pre-configured with strategies that address these issues, but for this to work backend server
  11445. * cooperation is required.
  11446. *
  11447. * ### JSON Vulnerability Protection
  11448. *
  11449. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  11450. * allows third party website to turn your JSON resource URL into
  11451. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  11452. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  11453. * AngularJS will automatically strip the prefix before processing it as JSON.
  11454. *
  11455. * For example if your server needs to return:
  11456. * ```js
  11457. * ['one','two']
  11458. * ```
  11459. *
  11460. * which is vulnerable to attack, your server can return:
  11461. * ```js
  11462. * )]}',
  11463. * ['one','two']
  11464. * ```
  11465. *
  11466. * AngularJS will strip the prefix, before processing the JSON.
  11467. *
  11468. *
  11469. * ### Cross Site Request Forgery (XSRF) Protection
  11470. *
  11471. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  11472. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  11473. * website. AngularJS provides a mechanism to counter XSRF. When performing XHR requests, the
  11474. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  11475. * header (by default `X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read
  11476. * the cookie, your server can be assured that the XHR came from JavaScript running on your
  11477. * domain.
  11478. *
  11479. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  11480. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  11481. * server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be
  11482. * sure that only JavaScript running on your domain could have sent the request. The token must
  11483. * be unique for each user and must be verifiable by the server (to prevent the JavaScript from
  11484. * making up its own tokens). We recommend that the token is a digest of your site's
  11485. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  11486. * for added security.
  11487. *
  11488. * The header will &mdash; by default &mdash; **not** be set for cross-domain requests. This
  11489. * prevents unauthorized servers (e.g. malicious or compromised 3rd-party APIs) from gaining
  11490. * access to your users' XSRF tokens and exposing them to Cross Site Request Forgery. If you
  11491. * want to, you can whitelist additional origins to also receive the XSRF token, by adding them
  11492. * to {@link ng.$httpProvider#xsrfWhitelistedOrigins xsrfWhitelistedOrigins}. This might be
  11493. * useful, for example, if your application, served from `example.com`, needs to access your API
  11494. * at `api.example.com`.
  11495. * See {@link ng.$httpProvider#xsrfWhitelistedOrigins $httpProvider.xsrfWhitelistedOrigins} for
  11496. * more details.
  11497. *
  11498. * <div class="alert alert-danger">
  11499. * **Warning**<br />
  11500. * Only whitelist origins that you have control over and make sure you understand the
  11501. * implications of doing so.
  11502. * </div>
  11503. *
  11504. * The name of the cookie and the header can be specified using the `xsrfCookieName` and
  11505. * `xsrfHeaderName` properties of either `$httpProvider.defaults` at config-time,
  11506. * `$http.defaults` at run-time, or the per-request config object.
  11507. *
  11508. * In order to prevent collisions in environments where multiple AngularJS apps share the
  11509. * same domain or subdomain, we recommend that each application uses a unique cookie name.
  11510. *
  11511. *
  11512. * @param {object} config Object describing the request to be made and how it should be
  11513. * processed. The object has following properties:
  11514. *
  11515. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  11516. * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;
  11517. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11518. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  11519. * with the `paramSerializer` and appended as GET parameters.
  11520. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  11521. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  11522. * HTTP headers to send to the server. If the return value of a function is null, the
  11523. * header will not be sent. Functions accept a config object as an argument.
  11524. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  11525. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  11526. * The handler will be called in the context of a `$apply` block.
  11527. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  11528. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  11529. * The handler will be called in the context of a `$apply` block.
  11530. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  11531. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  11532. * - **transformRequest** –
  11533. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  11534. * transform function or an array of such functions. The transform function takes the http
  11535. * request body and headers and returns its transformed (typically serialized) version.
  11536. * See {@link ng.$http#overriding-the-default-transformations-per-request
  11537. * Overriding the Default Transformations}
  11538. * - **transformResponse** –
  11539. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  11540. * transform function or an array of such functions. The transform function takes the http
  11541. * response body, headers and status and returns its transformed (typically deserialized) version.
  11542. * See {@link ng.$http#overriding-the-default-transformations-per-request
  11543. * Overriding the Default Transformations}
  11544. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  11545. * prepare the string representation of request parameters (specified as an object).
  11546. * If specified as string, it is interpreted as function registered with the
  11547. * {@link $injector $injector}, which means you can create your own serializer
  11548. * by registering it as a {@link auto.$provide#service service}.
  11549. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  11550. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  11551. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  11552. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  11553. * See {@link $http#caching $http Caching} for more information.
  11554. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  11555. * that should abort the request when resolved.
  11556. *
  11557. * A numerical timeout or a promise returned from {@link ng.$timeout $timeout}, will set
  11558. * the `xhrStatus` in the {@link $http#$http-returns response} to "timeout", and any other
  11559. * resolved promise will set it to "abort", following standard XMLHttpRequest behavior.
  11560. *
  11561. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  11562. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  11563. * for more information.
  11564. * - **responseType** - `{string}` - see
  11565. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  11566. *
  11567. * @returns {HttpPromise} A {@link ng.$q `Promise}` that will be resolved (request success)
  11568. * or rejected (request failure) with a response object.
  11569. *
  11570. * The response object has these properties:
  11571. *
  11572. * - **data** – `{string|Object}` – The response body transformed with
  11573. * the transform functions.
  11574. * - **status** – `{number}` – HTTP status code of the response.
  11575. * - **headers** – `{function([headerName])}` – Header getter function.
  11576. * - **config** – `{Object}` – The configuration object that was used
  11577. * to generate the request.
  11578. * - **statusText** – `{string}` – HTTP status text of the response.
  11579. * - **xhrStatus** – `{string}` – Status of the XMLHttpRequest
  11580. * (`complete`, `error`, `timeout` or `abort`).
  11581. *
  11582. *
  11583. * A response status code between 200 and 299 is considered a success status
  11584. * and will result in the success callback being called. Any response status
  11585. * code outside of that range is considered an error status and will result
  11586. * in the error callback being called.
  11587. * Also, status codes less than -1 are normalized to zero. -1 usually means
  11588. * the request was aborted, e.g. using a `config.timeout`. More information
  11589. * about the status might be available in the `xhrStatus` property.
  11590. *
  11591. * Note that if the response is a redirect, XMLHttpRequest will transparently
  11592. * follow it, meaning that the outcome (success or error) will be determined
  11593. * by the final response status code.
  11594. *
  11595. *
  11596. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  11597. * requests. This is primarily meant to be used for debugging purposes.
  11598. *
  11599. *
  11600. * @example
  11601. <example module="httpExample" name="http-service">
  11602. <file name="index.html">
  11603. <div ng-controller="FetchController">
  11604. <select ng-model="method" aria-label="Request method">
  11605. <option>GET</option>
  11606. <option>JSONP</option>
  11607. </select>
  11608. <input type="text" ng-model="url" size="80" aria-label="URL" />
  11609. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  11610. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  11611. <button id="samplejsonpbtn"
  11612. ng-click="updateModel('JSONP',
  11613. 'https://angularjs.org/greet.php?name=Super%20Hero')">
  11614. Sample JSONP
  11615. </button>
  11616. <button id="invalidjsonpbtn"
  11617. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')">
  11618. Invalid JSONP
  11619. </button>
  11620. <pre>http status code: {{status}}</pre>
  11621. <pre>http response data: {{data}}</pre>
  11622. </div>
  11623. </file>
  11624. <file name="script.js">
  11625. angular.module('httpExample', [])
  11626. .config(['$sceDelegateProvider', function($sceDelegateProvider) {
  11627. // We must whitelist the JSONP endpoint that we are using to show that we trust it
  11628. $sceDelegateProvider.resourceUrlWhitelist([
  11629. 'self',
  11630. 'https://angularjs.org/**'
  11631. ]);
  11632. }])
  11633. .controller('FetchController', ['$scope', '$http', '$templateCache',
  11634. function($scope, $http, $templateCache) {
  11635. $scope.method = 'GET';
  11636. $scope.url = 'http-hello.html';
  11637. $scope.fetch = function() {
  11638. $scope.code = null;
  11639. $scope.response = null;
  11640. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  11641. then(function(response) {
  11642. $scope.status = response.status;
  11643. $scope.data = response.data;
  11644. }, function(response) {
  11645. $scope.data = response.data || 'Request failed';
  11646. $scope.status = response.status;
  11647. });
  11648. };
  11649. $scope.updateModel = function(method, url) {
  11650. $scope.method = method;
  11651. $scope.url = url;
  11652. };
  11653. }]);
  11654. </file>
  11655. <file name="http-hello.html">
  11656. Hello, $http!
  11657. </file>
  11658. <file name="protractor.js" type="protractor">
  11659. var status = element(by.binding('status'));
  11660. var data = element(by.binding('data'));
  11661. var fetchBtn = element(by.id('fetchbtn'));
  11662. var sampleGetBtn = element(by.id('samplegetbtn'));
  11663. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  11664. it('should make an xhr GET request', function() {
  11665. sampleGetBtn.click();
  11666. fetchBtn.click();
  11667. expect(status.getText()).toMatch('200');
  11668. expect(data.getText()).toMatch(/Hello, \$http!/);
  11669. });
  11670. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  11671. // it('should make a JSONP request to angularjs.org', function() {
  11672. // var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  11673. // sampleJsonpBtn.click();
  11674. // fetchBtn.click();
  11675. // expect(status.getText()).toMatch('200');
  11676. // expect(data.getText()).toMatch(/Super Hero!/);
  11677. // });
  11678. it('should make JSONP request to invalid URL and invoke the error handler',
  11679. function() {
  11680. invalidJsonpBtn.click();
  11681. fetchBtn.click();
  11682. expect(status.getText()).toMatch('0');
  11683. expect(data.getText()).toMatch('Request failed');
  11684. });
  11685. </file>
  11686. </example>
  11687. */
  11688. function $http(requestConfig) {
  11689. if (!isObject(requestConfig)) {
  11690. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  11691. }
  11692. if (!isString($sce.valueOf(requestConfig.url))) {
  11693. throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);
  11694. }
  11695. var config = extend({
  11696. method: 'get',
  11697. transformRequest: defaults.transformRequest,
  11698. transformResponse: defaults.transformResponse,
  11699. paramSerializer: defaults.paramSerializer,
  11700. jsonpCallbackParam: defaults.jsonpCallbackParam
  11701. }, requestConfig);
  11702. config.headers = mergeHeaders(requestConfig);
  11703. config.method = uppercase(config.method);
  11704. config.paramSerializer = isString(config.paramSerializer) ?
  11705. $injector.get(config.paramSerializer) : config.paramSerializer;
  11706. $browser.$$incOutstandingRequestCount('$http');
  11707. var requestInterceptors = [];
  11708. var responseInterceptors = [];
  11709. var promise = $q.resolve(config);
  11710. // apply interceptors
  11711. forEach(reversedInterceptors, function(interceptor) {
  11712. if (interceptor.request || interceptor.requestError) {
  11713. requestInterceptors.unshift(interceptor.request, interceptor.requestError);
  11714. }
  11715. if (interceptor.response || interceptor.responseError) {
  11716. responseInterceptors.push(interceptor.response, interceptor.responseError);
  11717. }
  11718. });
  11719. promise = chainInterceptors(promise, requestInterceptors);
  11720. promise = promise.then(serverRequest);
  11721. promise = chainInterceptors(promise, responseInterceptors);
  11722. promise = promise.finally(completeOutstandingRequest);
  11723. return promise;
  11724. function chainInterceptors(promise, interceptors) {
  11725. for (var i = 0, ii = interceptors.length; i < ii;) {
  11726. var thenFn = interceptors[i++];
  11727. var rejectFn = interceptors[i++];
  11728. promise = promise.then(thenFn, rejectFn);
  11729. }
  11730. interceptors.length = 0;
  11731. return promise;
  11732. }
  11733. function completeOutstandingRequest() {
  11734. $browser.$$completeOutstandingRequest(noop, '$http');
  11735. }
  11736. function executeHeaderFns(headers, config) {
  11737. var headerContent, processedHeaders = {};
  11738. forEach(headers, function(headerFn, header) {
  11739. if (isFunction(headerFn)) {
  11740. headerContent = headerFn(config);
  11741. if (headerContent != null) {
  11742. processedHeaders[header] = headerContent;
  11743. }
  11744. } else {
  11745. processedHeaders[header] = headerFn;
  11746. }
  11747. });
  11748. return processedHeaders;
  11749. }
  11750. function mergeHeaders(config) {
  11751. var defHeaders = defaults.headers,
  11752. reqHeaders = extend({}, config.headers),
  11753. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  11754. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  11755. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  11756. defaultHeadersIteration:
  11757. for (defHeaderName in defHeaders) {
  11758. lowercaseDefHeaderName = lowercase(defHeaderName);
  11759. for (reqHeaderName in reqHeaders) {
  11760. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  11761. continue defaultHeadersIteration;
  11762. }
  11763. }
  11764. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  11765. }
  11766. // execute if header value is a function for merged headers
  11767. return executeHeaderFns(reqHeaders, shallowCopy(config));
  11768. }
  11769. function serverRequest(config) {
  11770. var headers = config.headers;
  11771. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  11772. // strip content-type if data is undefined
  11773. if (isUndefined(reqData)) {
  11774. forEach(headers, function(value, header) {
  11775. if (lowercase(header) === 'content-type') {
  11776. delete headers[header];
  11777. }
  11778. });
  11779. }
  11780. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  11781. config.withCredentials = defaults.withCredentials;
  11782. }
  11783. // send request
  11784. return sendReq(config, reqData).then(transformResponse, transformResponse);
  11785. }
  11786. function transformResponse(response) {
  11787. // make a copy since the response must be cacheable
  11788. var resp = extend({}, response);
  11789. resp.data = transformData(response.data, response.headers, response.status,
  11790. config.transformResponse);
  11791. return (isSuccess(response.status))
  11792. ? resp
  11793. : $q.reject(resp);
  11794. }
  11795. }
  11796. $http.pendingRequests = [];
  11797. /**
  11798. * @ngdoc method
  11799. * @name $http#get
  11800. *
  11801. * @description
  11802. * Shortcut method to perform `GET` request.
  11803. *
  11804. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11805. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11806. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  11807. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  11808. * See {@link ng.$http#$http-returns `$http()` return value}.
  11809. */
  11810. /**
  11811. * @ngdoc method
  11812. * @name $http#delete
  11813. *
  11814. * @description
  11815. * Shortcut method to perform `DELETE` request.
  11816. *
  11817. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11818. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11819. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  11820. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  11821. * See {@link ng.$http#$http-returns `$http()` return value}.
  11822. */
  11823. /**
  11824. * @ngdoc method
  11825. * @name $http#head
  11826. *
  11827. * @description
  11828. * Shortcut method to perform `HEAD` request.
  11829. *
  11830. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11831. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11832. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  11833. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  11834. * See {@link ng.$http#$http-returns `$http()` return value}.
  11835. */
  11836. /**
  11837. * @ngdoc method
  11838. * @name $http#jsonp
  11839. *
  11840. * @description
  11841. * Shortcut method to perform `JSONP` request.
  11842. *
  11843. * Note that, since JSONP requests are sensitive because the response is given full access to the browser,
  11844. * the url must be declared, via {@link $sce} as a trusted resource URL.
  11845. * You can trust a URL by adding it to the whitelist via
  11846. * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or
  11847. * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.
  11848. *
  11849. * You should avoid generating the URL for the JSONP request from user provided data.
  11850. * Provide additional query parameters via `params` property of the `config` parameter, rather than
  11851. * modifying the URL itself.
  11852. *
  11853. * JSONP requests must specify a callback to be used in the response from the server. This callback
  11854. * is passed as a query parameter in the request. You must specify the name of this parameter by
  11855. * setting the `jsonpCallbackParam` property on the request config object.
  11856. *
  11857. * ```
  11858. * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
  11859. * ```
  11860. *
  11861. * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.
  11862. * Initially this is set to `'callback'`.
  11863. *
  11864. * <div class="alert alert-danger">
  11865. * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback
  11866. * parameter value should go.
  11867. * </div>
  11868. *
  11869. * If you would like to customise where and how the callbacks are stored then try overriding
  11870. * or decorating the {@link $jsonpCallbacks} service.
  11871. *
  11872. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11873. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11874. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  11875. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  11876. * See {@link ng.$http#$http-returns `$http()` return value}.
  11877. */
  11878. createShortMethods('get', 'delete', 'head', 'jsonp');
  11879. /**
  11880. * @ngdoc method
  11881. * @name $http#post
  11882. *
  11883. * @description
  11884. * Shortcut method to perform `POST` request.
  11885. *
  11886. * @param {string} url Relative or absolute URL specifying the destination of the request
  11887. * @param {*} data Request content
  11888. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  11889. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  11890. * See {@link ng.$http#$http-returns `$http()` return value}.
  11891. */
  11892. /**
  11893. * @ngdoc method
  11894. * @name $http#put
  11895. *
  11896. * @description
  11897. * Shortcut method to perform `PUT` request.
  11898. *
  11899. * @param {string} url Relative or absolute URL specifying the destination of the request
  11900. * @param {*} data Request content
  11901. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  11902. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  11903. * See {@link ng.$http#$http-returns `$http()` return value}.
  11904. */
  11905. /**
  11906. * @ngdoc method
  11907. * @name $http#patch
  11908. *
  11909. * @description
  11910. * Shortcut method to perform `PATCH` request.
  11911. *
  11912. * @param {string} url Relative or absolute URL specifying the destination of the request
  11913. * @param {*} data Request content
  11914. * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}.
  11915. * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object.
  11916. * See {@link ng.$http#$http-returns `$http()` return value}.
  11917. */
  11918. createShortMethodsWithData('post', 'put', 'patch');
  11919. /**
  11920. * @ngdoc property
  11921. * @name $http#defaults
  11922. *
  11923. * @description
  11924. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  11925. * default headers, withCredentials as well as request and response transformations.
  11926. *
  11927. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  11928. */
  11929. $http.defaults = defaults;
  11930. return $http;
  11931. function createShortMethods(names) {
  11932. forEach(arguments, function(name) {
  11933. $http[name] = function(url, config) {
  11934. return $http(extend({}, config || {}, {
  11935. method: name,
  11936. url: url
  11937. }));
  11938. };
  11939. });
  11940. }
  11941. function createShortMethodsWithData(name) {
  11942. forEach(arguments, function(name) {
  11943. $http[name] = function(url, data, config) {
  11944. return $http(extend({}, config || {}, {
  11945. method: name,
  11946. url: url,
  11947. data: data
  11948. }));
  11949. };
  11950. });
  11951. }
  11952. /**
  11953. * Makes the request.
  11954. *
  11955. * !!! ACCESSES CLOSURE VARS:
  11956. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  11957. */
  11958. function sendReq(config, reqData) {
  11959. var deferred = $q.defer(),
  11960. promise = deferred.promise,
  11961. cache,
  11962. cachedResp,
  11963. reqHeaders = config.headers,
  11964. isJsonp = lowercase(config.method) === 'jsonp',
  11965. url = config.url;
  11966. if (isJsonp) {
  11967. // JSONP is a pretty sensitive operation where we're allowing a script to have full access to
  11968. // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.
  11969. url = $sce.getTrustedResourceUrl(url);
  11970. } else if (!isString(url)) {
  11971. // If it is not a string then the URL must be a $sce trusted object
  11972. url = $sce.valueOf(url);
  11973. }
  11974. url = buildUrl(url, config.paramSerializer(config.params));
  11975. if (isJsonp) {
  11976. // Check the url and add the JSONP callback placeholder
  11977. url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);
  11978. }
  11979. $http.pendingRequests.push(config);
  11980. promise.then(removePendingReq, removePendingReq);
  11981. if ((config.cache || defaults.cache) && config.cache !== false &&
  11982. (config.method === 'GET' || config.method === 'JSONP')) {
  11983. cache = isObject(config.cache) ? config.cache
  11984. : isObject(/** @type {?} */ (defaults).cache)
  11985. ? /** @type {?} */ (defaults).cache
  11986. : defaultCache;
  11987. }
  11988. if (cache) {
  11989. cachedResp = cache.get(url);
  11990. if (isDefined(cachedResp)) {
  11991. if (isPromiseLike(cachedResp)) {
  11992. // cached request has already been sent, but there is no response yet
  11993. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  11994. } else {
  11995. // serving from cache
  11996. if (isArray(cachedResp)) {
  11997. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3], cachedResp[4]);
  11998. } else {
  11999. resolvePromise(cachedResp, 200, {}, 'OK', 'complete');
  12000. }
  12001. }
  12002. } else {
  12003. // put the promise for the non-transformed response into cache as a placeholder
  12004. cache.put(url, promise);
  12005. }
  12006. }
  12007. // if we won't have the response in cache, set the xsrf headers and
  12008. // send the request to the backend
  12009. if (isUndefined(cachedResp)) {
  12010. var xsrfValue = urlIsAllowedOrigin(config.url)
  12011. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  12012. : undefined;
  12013. if (xsrfValue) {
  12014. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  12015. }
  12016. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  12017. config.withCredentials, config.responseType,
  12018. createApplyHandlers(config.eventHandlers),
  12019. createApplyHandlers(config.uploadEventHandlers));
  12020. }
  12021. return promise;
  12022. function createApplyHandlers(eventHandlers) {
  12023. if (eventHandlers) {
  12024. var applyHandlers = {};
  12025. forEach(eventHandlers, function(eventHandler, key) {
  12026. applyHandlers[key] = function(event) {
  12027. if (useApplyAsync) {
  12028. $rootScope.$applyAsync(callEventHandler);
  12029. } else if ($rootScope.$$phase) {
  12030. callEventHandler();
  12031. } else {
  12032. $rootScope.$apply(callEventHandler);
  12033. }
  12034. function callEventHandler() {
  12035. eventHandler(event);
  12036. }
  12037. };
  12038. });
  12039. return applyHandlers;
  12040. }
  12041. }
  12042. /**
  12043. * Callback registered to $httpBackend():
  12044. * - caches the response if desired
  12045. * - resolves the raw $http promise
  12046. * - calls $apply
  12047. */
  12048. function done(status, response, headersString, statusText, xhrStatus) {
  12049. if (cache) {
  12050. if (isSuccess(status)) {
  12051. cache.put(url, [status, response, parseHeaders(headersString), statusText, xhrStatus]);
  12052. } else {
  12053. // remove promise from the cache
  12054. cache.remove(url);
  12055. }
  12056. }
  12057. function resolveHttpPromise() {
  12058. resolvePromise(response, status, headersString, statusText, xhrStatus);
  12059. }
  12060. if (useApplyAsync) {
  12061. $rootScope.$applyAsync(resolveHttpPromise);
  12062. } else {
  12063. resolveHttpPromise();
  12064. if (!$rootScope.$$phase) $rootScope.$apply();
  12065. }
  12066. }
  12067. /**
  12068. * Resolves the raw $http promise.
  12069. */
  12070. function resolvePromise(response, status, headers, statusText, xhrStatus) {
  12071. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  12072. status = status >= -1 ? status : 0;
  12073. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  12074. data: response,
  12075. status: status,
  12076. headers: headersGetter(headers),
  12077. config: config,
  12078. statusText: statusText,
  12079. xhrStatus: xhrStatus
  12080. });
  12081. }
  12082. function resolvePromiseWithResult(result) {
  12083. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText, result.xhrStatus);
  12084. }
  12085. function removePendingReq() {
  12086. var idx = $http.pendingRequests.indexOf(config);
  12087. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  12088. }
  12089. }
  12090. function buildUrl(url, serializedParams) {
  12091. if (serializedParams.length > 0) {
  12092. url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
  12093. }
  12094. return url;
  12095. }
  12096. function sanitizeJsonpCallbackParam(url, cbKey) {
  12097. var parts = url.split('?');
  12098. if (parts.length > 2) {
  12099. // Throw if the url contains more than one `?` query indicator
  12100. throw $httpMinErr('badjsonp', 'Illegal use more than one "?", in url, "{1}"', url);
  12101. }
  12102. var params = parseKeyValue(parts[1]);
  12103. forEach(params, function(value, key) {
  12104. if (value === 'JSON_CALLBACK') {
  12105. // Throw if the url already contains a reference to JSON_CALLBACK
  12106. throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url);
  12107. }
  12108. if (key === cbKey) {
  12109. // Throw if the callback param was already provided
  12110. throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', cbKey, url);
  12111. }
  12112. });
  12113. // Add in the JSON_CALLBACK callback param value
  12114. url += ((url.indexOf('?') === -1) ? '?' : '&') + cbKey + '=JSON_CALLBACK';
  12115. return url;
  12116. }
  12117. }];
  12118. }
  12119. /**
  12120. * @ngdoc service
  12121. * @name $xhrFactory
  12122. * @this
  12123. *
  12124. * @description
  12125. * Factory function used to create XMLHttpRequest objects.
  12126. *
  12127. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  12128. *
  12129. * ```
  12130. * angular.module('myApp', [])
  12131. * .factory('$xhrFactory', function() {
  12132. * return function createXhr(method, url) {
  12133. * return new window.XMLHttpRequest({mozSystem: true});
  12134. * };
  12135. * });
  12136. * ```
  12137. *
  12138. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  12139. * @param {string} url URL of the request.
  12140. */
  12141. function $xhrFactoryProvider() {
  12142. this.$get = function() {
  12143. return function createXhr() {
  12144. return new window.XMLHttpRequest();
  12145. };
  12146. };
  12147. }
  12148. /**
  12149. * @ngdoc service
  12150. * @name $httpBackend
  12151. * @requires $jsonpCallbacks
  12152. * @requires $document
  12153. * @requires $xhrFactory
  12154. * @this
  12155. *
  12156. * @description
  12157. * HTTP backend used by the {@link ng.$http service} that delegates to
  12158. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  12159. *
  12160. * You should never need to use this service directly, instead use the higher-level abstractions:
  12161. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  12162. *
  12163. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  12164. * $httpBackend} which can be trained with responses.
  12165. */
  12166. function $HttpBackendProvider() {
  12167. this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
  12168. return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
  12169. }];
  12170. }
  12171. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  12172. // TODO(vojta): fix the signature
  12173. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  12174. url = url || $browser.url();
  12175. if (lowercase(method) === 'jsonp') {
  12176. var callbackPath = callbacks.createCallback(url);
  12177. var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
  12178. // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
  12179. var response = (status === 200) && callbacks.getResponse(callbackPath);
  12180. completeRequest(callback, status, response, '', text, 'complete');
  12181. callbacks.removeCallback(callbackPath);
  12182. });
  12183. } else {
  12184. var xhr = createXhr(method, url);
  12185. var abortedByTimeout = false;
  12186. xhr.open(method, url, true);
  12187. forEach(headers, function(value, key) {
  12188. if (isDefined(value)) {
  12189. xhr.setRequestHeader(key, value);
  12190. }
  12191. });
  12192. xhr.onload = function requestLoaded() {
  12193. var statusText = xhr.statusText || '';
  12194. // responseText is the old-school way of retrieving response (supported by IE9)
  12195. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  12196. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  12197. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  12198. var status = xhr.status === 1223 ? 204 : xhr.status;
  12199. // fix status code when it is 0 (0 status is undocumented).
  12200. // Occurs when accessing file resources or on Android 4.1 stock browser
  12201. // while retrieving files from application cache.
  12202. if (status === 0) {
  12203. status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
  12204. }
  12205. completeRequest(callback,
  12206. status,
  12207. response,
  12208. xhr.getAllResponseHeaders(),
  12209. statusText,
  12210. 'complete');
  12211. };
  12212. var requestError = function() {
  12213. // The response is always empty
  12214. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  12215. completeRequest(callback, -1, null, null, '', 'error');
  12216. };
  12217. var requestAborted = function() {
  12218. completeRequest(callback, -1, null, null, '', abortedByTimeout ? 'timeout' : 'abort');
  12219. };
  12220. var requestTimeout = function() {
  12221. // The response is always empty
  12222. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  12223. completeRequest(callback, -1, null, null, '', 'timeout');
  12224. };
  12225. xhr.onerror = requestError;
  12226. xhr.ontimeout = requestTimeout;
  12227. xhr.onabort = requestAborted;
  12228. forEach(eventHandlers, function(value, key) {
  12229. xhr.addEventListener(key, value);
  12230. });
  12231. forEach(uploadEventHandlers, function(value, key) {
  12232. xhr.upload.addEventListener(key, value);
  12233. });
  12234. if (withCredentials) {
  12235. xhr.withCredentials = true;
  12236. }
  12237. if (responseType) {
  12238. try {
  12239. xhr.responseType = responseType;
  12240. } catch (e) {
  12241. // WebKit added support for the json responseType value on 09/03/2013
  12242. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  12243. // known to throw when setting the value "json" as the response type. Other older
  12244. // browsers implementing the responseType
  12245. //
  12246. // The json response type can be ignored if not supported, because JSON payloads are
  12247. // parsed on the client-side regardless.
  12248. if (responseType !== 'json') {
  12249. throw e;
  12250. }
  12251. }
  12252. }
  12253. xhr.send(isUndefined(post) ? null : post);
  12254. }
  12255. // Since we are using xhr.abort() when a request times out, we have to set a flag that
  12256. // indicates to requestAborted if the request timed out or was aborted.
  12257. //
  12258. // http.timeout = numerical timeout timeout
  12259. // http.timeout = $timeout timeout
  12260. // http.timeout = promise abort
  12261. // xhr.abort() abort (The xhr object is normally inaccessible, but
  12262. // can be exposed with the xhrFactory)
  12263. if (timeout > 0) {
  12264. var timeoutId = $browserDefer(function() {
  12265. timeoutRequest('timeout');
  12266. }, timeout);
  12267. } else if (isPromiseLike(timeout)) {
  12268. timeout.then(function() {
  12269. timeoutRequest(isDefined(timeout.$$timeoutId) ? 'timeout' : 'abort');
  12270. });
  12271. }
  12272. function timeoutRequest(reason) {
  12273. abortedByTimeout = reason === 'timeout';
  12274. if (jsonpDone) {
  12275. jsonpDone();
  12276. }
  12277. if (xhr) {
  12278. xhr.abort();
  12279. }
  12280. }
  12281. function completeRequest(callback, status, response, headersString, statusText, xhrStatus) {
  12282. // cancel timeout and subsequent timeout promise resolution
  12283. if (isDefined(timeoutId)) {
  12284. $browserDefer.cancel(timeoutId);
  12285. }
  12286. jsonpDone = xhr = null;
  12287. callback(status, response, headersString, statusText, xhrStatus);
  12288. }
  12289. };
  12290. function jsonpReq(url, callbackPath, done) {
  12291. url = url.replace('JSON_CALLBACK', callbackPath);
  12292. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  12293. // - fetches local scripts via XHR and evals them
  12294. // - adds and immediately removes script elements from the document
  12295. var script = rawDocument.createElement('script'), callback = null;
  12296. script.type = 'text/javascript';
  12297. script.src = url;
  12298. script.async = true;
  12299. callback = function(event) {
  12300. script.removeEventListener('load', callback);
  12301. script.removeEventListener('error', callback);
  12302. rawDocument.body.removeChild(script);
  12303. script = null;
  12304. var status = -1;
  12305. var text = 'unknown';
  12306. if (event) {
  12307. if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
  12308. event = { type: 'error' };
  12309. }
  12310. text = event.type;
  12311. status = event.type === 'error' ? 404 : 200;
  12312. }
  12313. if (done) {
  12314. done(status, text);
  12315. }
  12316. };
  12317. script.addEventListener('load', callback);
  12318. script.addEventListener('error', callback);
  12319. rawDocument.body.appendChild(script);
  12320. return callback;
  12321. }
  12322. }
  12323. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  12324. $interpolateMinErr.throwNoconcat = function(text) {
  12325. throw $interpolateMinErr('noconcat',
  12326. 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
  12327. 'interpolations that concatenate multiple expressions when a trusted value is ' +
  12328. 'required. See http://docs.angularjs.org/api/ng.$sce', text);
  12329. };
  12330. $interpolateMinErr.interr = function(text, err) {
  12331. return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
  12332. };
  12333. /**
  12334. * @ngdoc provider
  12335. * @name $interpolateProvider
  12336. * @this
  12337. *
  12338. * @description
  12339. *
  12340. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  12341. *
  12342. * <div class="alert alert-danger">
  12343. * This feature is sometimes used to mix different markup languages, e.g. to wrap an AngularJS
  12344. * template within a Python Jinja template (or any other template language). Mixing templating
  12345. * languages is **very dangerous**. The embedding template language will not safely escape AngularJS
  12346. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  12347. * security bugs!
  12348. * </div>
  12349. *
  12350. * @example
  12351. <example name="custom-interpolation-markup" module="customInterpolationApp">
  12352. <file name="index.html">
  12353. <script>
  12354. var customInterpolationApp = angular.module('customInterpolationApp', []);
  12355. customInterpolationApp.config(function($interpolateProvider) {
  12356. $interpolateProvider.startSymbol('//');
  12357. $interpolateProvider.endSymbol('//');
  12358. });
  12359. customInterpolationApp.controller('DemoController', function() {
  12360. this.label = "This binding is brought you by // interpolation symbols.";
  12361. });
  12362. </script>
  12363. <div ng-controller="DemoController as demo">
  12364. //demo.label//
  12365. </div>
  12366. </file>
  12367. <file name="protractor.js" type="protractor">
  12368. it('should interpolate binding with custom symbols', function() {
  12369. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  12370. });
  12371. </file>
  12372. </example>
  12373. */
  12374. function $InterpolateProvider() {
  12375. var startSymbol = '{{';
  12376. var endSymbol = '}}';
  12377. /**
  12378. * @ngdoc method
  12379. * @name $interpolateProvider#startSymbol
  12380. * @description
  12381. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  12382. *
  12383. * @param {string=} value new value to set the starting symbol to.
  12384. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  12385. */
  12386. this.startSymbol = function(value) {
  12387. if (value) {
  12388. startSymbol = value;
  12389. return this;
  12390. }
  12391. return startSymbol;
  12392. };
  12393. /**
  12394. * @ngdoc method
  12395. * @name $interpolateProvider#endSymbol
  12396. * @description
  12397. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  12398. *
  12399. * @param {string=} value new value to set the ending symbol to.
  12400. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  12401. */
  12402. this.endSymbol = function(value) {
  12403. if (value) {
  12404. endSymbol = value;
  12405. return this;
  12406. }
  12407. return endSymbol;
  12408. };
  12409. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  12410. var startSymbolLength = startSymbol.length,
  12411. endSymbolLength = endSymbol.length,
  12412. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  12413. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  12414. function escape(ch) {
  12415. return '\\\\\\' + ch;
  12416. }
  12417. function unescapeText(text) {
  12418. return text.replace(escapedStartRegexp, startSymbol).
  12419. replace(escapedEndRegexp, endSymbol);
  12420. }
  12421. // TODO: this is the same as the constantWatchDelegate in parse.js
  12422. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  12423. var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  12424. unwatch();
  12425. return constantInterp(scope);
  12426. }, listener, objectEquality);
  12427. return unwatch;
  12428. }
  12429. /**
  12430. * @ngdoc service
  12431. * @name $interpolate
  12432. * @kind function
  12433. *
  12434. * @requires $parse
  12435. * @requires $sce
  12436. *
  12437. * @description
  12438. *
  12439. * Compiles a string with markup into an interpolation function. This service is used by the
  12440. * HTML {@link ng.$compile $compile} service for data binding. See
  12441. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  12442. * interpolation markup.
  12443. *
  12444. *
  12445. * ```js
  12446. * var $interpolate = ...; // injected
  12447. * var exp = $interpolate('Hello {{name | uppercase}}!');
  12448. * expect(exp({name:'AngularJS'})).toEqual('Hello ANGULARJS!');
  12449. * ```
  12450. *
  12451. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  12452. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  12453. * evaluate to a value other than `undefined`.
  12454. *
  12455. * ```js
  12456. * var $interpolate = ...; // injected
  12457. * var context = {greeting: 'Hello', name: undefined };
  12458. *
  12459. * // default "forgiving" mode
  12460. * var exp = $interpolate('{{greeting}} {{name}}!');
  12461. * expect(exp(context)).toEqual('Hello !');
  12462. *
  12463. * // "allOrNothing" mode
  12464. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  12465. * expect(exp(context)).toBeUndefined();
  12466. * context.name = 'AngularJS';
  12467. * expect(exp(context)).toEqual('Hello AngularJS!');
  12468. * ```
  12469. *
  12470. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  12471. *
  12472. * #### Escaped Interpolation
  12473. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  12474. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  12475. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  12476. * or binding.
  12477. *
  12478. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  12479. * degree, while also enabling code examples to work without relying on the
  12480. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  12481. *
  12482. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  12483. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  12484. * interpolation start/end markers with their escaped counterparts.**
  12485. *
  12486. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  12487. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  12488. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  12489. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  12490. * this is typically useful only when user-data is used in rendering a template from the server, or
  12491. * when otherwise untrusted data is used by a directive.
  12492. *
  12493. * <example name="interpolation">
  12494. * <file name="index.html">
  12495. * <div ng-init="username='A user'">
  12496. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  12497. * </p>
  12498. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  12499. * application, but fails to accomplish their task, because the server has correctly
  12500. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  12501. * characters.</p>
  12502. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  12503. * from the database by an administrator.</p>
  12504. * </div>
  12505. * </file>
  12506. * </example>
  12507. *
  12508. * @knownIssue
  12509. * It is currently not possible for an interpolated expression to contain the interpolation end
  12510. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  12511. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  12512. *
  12513. * @knownIssue
  12514. * All directives and components must use the standard `{{` `}}` interpolation symbols
  12515. * in their templates. If you change the application interpolation symbols the {@link $compile}
  12516. * service will attempt to denormalize the standard symbols to the custom symbols.
  12517. * The denormalization process is not clever enough to know not to replace instances of the standard
  12518. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  12519. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  12520. *
  12521. * ```
  12522. * <div data-context='{"context":{"id":3,"type":"page"}}">
  12523. * ```
  12524. *
  12525. * The workaround is to ensure that such instances are separated by whitespace:
  12526. * ```
  12527. * <div data-context='{"context":{"id":3,"type":"page"} }">
  12528. * ```
  12529. *
  12530. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  12531. *
  12532. * @param {string} text The text with markup to interpolate.
  12533. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  12534. * embedded expression in order to return an interpolation function. Strings with no
  12535. * embedded expression will return null for the interpolation function.
  12536. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  12537. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  12538. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  12539. * provides Strict Contextual Escaping for details.
  12540. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  12541. * unless all embedded expressions evaluate to a value other than `undefined`.
  12542. * @returns {function(context)} an interpolation function which is used to compute the
  12543. * interpolated string. The function has these parameters:
  12544. *
  12545. * - `context`: evaluation context for all expressions embedded in the interpolated text
  12546. */
  12547. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  12548. var contextAllowsConcatenation = trustedContext === $sce.URL || trustedContext === $sce.MEDIA_URL;
  12549. // Provide a quick exit and simplified result function for text with no interpolation
  12550. if (!text.length || text.indexOf(startSymbol) === -1) {
  12551. if (mustHaveExpression && !contextAllowsConcatenation) return;
  12552. var unescapedText = unescapeText(text);
  12553. if (contextAllowsConcatenation) {
  12554. unescapedText = $sce.getTrusted(trustedContext, unescapedText);
  12555. }
  12556. var constantInterp = valueFn(unescapedText);
  12557. constantInterp.exp = text;
  12558. constantInterp.expressions = [];
  12559. constantInterp.$$watchDelegate = constantWatchDelegate;
  12560. return constantInterp;
  12561. }
  12562. allOrNothing = !!allOrNothing;
  12563. var startIndex,
  12564. endIndex,
  12565. index = 0,
  12566. expressions = [],
  12567. parseFns,
  12568. textLength = text.length,
  12569. exp,
  12570. concat = [],
  12571. expressionPositions = [],
  12572. singleExpression;
  12573. while (index < textLength) {
  12574. if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
  12575. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
  12576. if (index !== startIndex) {
  12577. concat.push(unescapeText(text.substring(index, startIndex)));
  12578. }
  12579. exp = text.substring(startIndex + startSymbolLength, endIndex);
  12580. expressions.push(exp);
  12581. index = endIndex + endSymbolLength;
  12582. expressionPositions.push(concat.length);
  12583. concat.push(''); // Placeholder that will get replaced with the evaluated expression.
  12584. } else {
  12585. // we did not find an interpolation, so we have to add the remainder to the separators array
  12586. if (index !== textLength) {
  12587. concat.push(unescapeText(text.substring(index)));
  12588. }
  12589. break;
  12590. }
  12591. }
  12592. singleExpression = concat.length === 1 && expressionPositions.length === 1;
  12593. // Intercept expression if we need to stringify concatenated inputs, which may be SCE trusted
  12594. // objects rather than simple strings
  12595. // (we don't modify the expression if the input consists of only a single trusted input)
  12596. var interceptor = contextAllowsConcatenation && singleExpression ? undefined : parseStringifyInterceptor;
  12597. parseFns = expressions.map(function(exp) { return $parse(exp, interceptor); });
  12598. // Concatenating expressions makes it hard to reason about whether some combination of
  12599. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  12600. // single expression be used for some $sce-managed secure contexts (RESOURCE_URLs mostly),
  12601. // we ensure that the value that's used is assigned or constructed by some JS code somewhere
  12602. // that is more testable or make it obvious that you bound the value to some user controlled
  12603. // value. This helps reduce the load when auditing for XSS issues.
  12604. // Note that URL and MEDIA_URL $sce contexts do not need this, since `$sce` can sanitize the values
  12605. // passed to it. In that case, `$sce.getTrusted` will be called on either the single expression
  12606. // or on the overall concatenated string (losing trusted types used in the mix, by design).
  12607. // Both these methods will sanitize plain strings. Also, HTML could be included, but since it's
  12608. // only used in srcdoc attributes, this would not be very useful.
  12609. if (!mustHaveExpression || expressions.length) {
  12610. var compute = function(values) {
  12611. for (var i = 0, ii = expressions.length; i < ii; i++) {
  12612. if (allOrNothing && isUndefined(values[i])) return;
  12613. concat[expressionPositions[i]] = values[i];
  12614. }
  12615. if (contextAllowsConcatenation) {
  12616. // If `singleExpression` then `concat[0]` might be a "trusted" value or `null`, rather than a string
  12617. return $sce.getTrusted(trustedContext, singleExpression ? concat[0] : concat.join(''));
  12618. } else if (trustedContext && concat.length > 1) {
  12619. // This context does not allow more than one part, e.g. expr + string or exp + exp.
  12620. $interpolateMinErr.throwNoconcat(text);
  12621. }
  12622. // In an unprivileged context or only one part: just concatenate and return.
  12623. return concat.join('');
  12624. };
  12625. return extend(function interpolationFn(context) {
  12626. var i = 0;
  12627. var ii = expressions.length;
  12628. var values = new Array(ii);
  12629. try {
  12630. for (; i < ii; i++) {
  12631. values[i] = parseFns[i](context);
  12632. }
  12633. return compute(values);
  12634. } catch (err) {
  12635. $exceptionHandler($interpolateMinErr.interr(text, err));
  12636. }
  12637. }, {
  12638. // all of these properties are undocumented for now
  12639. exp: text, //just for compatibility with regular watchers created via $watch
  12640. expressions: expressions,
  12641. $$watchDelegate: function(scope, listener) {
  12642. var lastValue;
  12643. return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
  12644. var currValue = compute(values);
  12645. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  12646. lastValue = currValue;
  12647. });
  12648. }
  12649. });
  12650. }
  12651. function parseStringifyInterceptor(value) {
  12652. try {
  12653. // In concatenable contexts, getTrusted comes at the end, to avoid sanitizing individual
  12654. // parts of a full URL. We don't care about losing the trustedness here.
  12655. // In non-concatenable contexts, where there is only one expression, this interceptor is
  12656. // not applied to the expression.
  12657. value = (trustedContext && !contextAllowsConcatenation) ?
  12658. $sce.getTrusted(trustedContext, value) :
  12659. $sce.valueOf(value);
  12660. return allOrNothing && !isDefined(value) ? value : stringify(value);
  12661. } catch (err) {
  12662. $exceptionHandler($interpolateMinErr.interr(text, err));
  12663. }
  12664. }
  12665. }
  12666. /**
  12667. * @ngdoc method
  12668. * @name $interpolate#startSymbol
  12669. * @description
  12670. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  12671. *
  12672. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  12673. * the symbol.
  12674. *
  12675. * @returns {string} start symbol.
  12676. */
  12677. $interpolate.startSymbol = function() {
  12678. return startSymbol;
  12679. };
  12680. /**
  12681. * @ngdoc method
  12682. * @name $interpolate#endSymbol
  12683. * @description
  12684. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  12685. *
  12686. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  12687. * the symbol.
  12688. *
  12689. * @returns {string} end symbol.
  12690. */
  12691. $interpolate.endSymbol = function() {
  12692. return endSymbol;
  12693. };
  12694. return $interpolate;
  12695. }];
  12696. }
  12697. var $intervalMinErr = minErr('$interval');
  12698. /** @this */
  12699. function $IntervalProvider() {
  12700. this.$get = ['$$intervalFactory', '$window',
  12701. function($$intervalFactory, $window) {
  12702. var intervals = {};
  12703. var setIntervalFn = function(tick, delay, deferred) {
  12704. var id = $window.setInterval(tick, delay);
  12705. intervals[id] = deferred;
  12706. return id;
  12707. };
  12708. var clearIntervalFn = function(id) {
  12709. $window.clearInterval(id);
  12710. delete intervals[id];
  12711. };
  12712. /**
  12713. * @ngdoc service
  12714. * @name $interval
  12715. *
  12716. * @description
  12717. * AngularJS's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  12718. * milliseconds.
  12719. *
  12720. * The return value of registering an interval function is a promise. This promise will be
  12721. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  12722. * run indefinitely if `count` is not defined. The value of the notification will be the
  12723. * number of iterations that have run.
  12724. * To cancel an interval, call `$interval.cancel(promise)`.
  12725. *
  12726. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  12727. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  12728. * time.
  12729. *
  12730. * <div class="alert alert-warning">
  12731. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  12732. * with them. In particular they are not automatically destroyed when a controller's scope or a
  12733. * directive's element are destroyed.
  12734. * You should take this into consideration and make sure to always cancel the interval at the
  12735. * appropriate moment. See the example below for more details on how and when to do this.
  12736. * </div>
  12737. *
  12738. * @param {function()} fn A function that should be called repeatedly. If no additional arguments
  12739. * are passed (see below), the function is called with the current iteration count.
  12740. * @param {number} delay Number of milliseconds between each function call.
  12741. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  12742. * indefinitely.
  12743. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  12744. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  12745. * @param {...*=} Pass additional parameters to the executed function.
  12746. * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete.
  12747. *
  12748. * @example
  12749. * <example module="intervalExample" name="interval-service">
  12750. * <file name="index.html">
  12751. * <script>
  12752. * angular.module('intervalExample', [])
  12753. * .controller('ExampleController', ['$scope', '$interval',
  12754. * function($scope, $interval) {
  12755. * $scope.format = 'M/d/yy h:mm:ss a';
  12756. * $scope.blood_1 = 100;
  12757. * $scope.blood_2 = 120;
  12758. *
  12759. * var stop;
  12760. * $scope.fight = function() {
  12761. * // Don't start a new fight if we are already fighting
  12762. * if ( angular.isDefined(stop) ) return;
  12763. *
  12764. * stop = $interval(function() {
  12765. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  12766. * $scope.blood_1 = $scope.blood_1 - 3;
  12767. * $scope.blood_2 = $scope.blood_2 - 4;
  12768. * } else {
  12769. * $scope.stopFight();
  12770. * }
  12771. * }, 100);
  12772. * };
  12773. *
  12774. * $scope.stopFight = function() {
  12775. * if (angular.isDefined(stop)) {
  12776. * $interval.cancel(stop);
  12777. * stop = undefined;
  12778. * }
  12779. * };
  12780. *
  12781. * $scope.resetFight = function() {
  12782. * $scope.blood_1 = 100;
  12783. * $scope.blood_2 = 120;
  12784. * };
  12785. *
  12786. * $scope.$on('$destroy', function() {
  12787. * // Make sure that the interval is destroyed too
  12788. * $scope.stopFight();
  12789. * });
  12790. * }])
  12791. * // Register the 'myCurrentTime' directive factory method.
  12792. * // We inject $interval and dateFilter service since the factory method is DI.
  12793. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  12794. * function($interval, dateFilter) {
  12795. * // return the directive link function. (compile function not needed)
  12796. * return function(scope, element, attrs) {
  12797. * var format, // date format
  12798. * stopTime; // so that we can cancel the time updates
  12799. *
  12800. * // used to update the UI
  12801. * function updateTime() {
  12802. * element.text(dateFilter(new Date(), format));
  12803. * }
  12804. *
  12805. * // watch the expression, and update the UI on change.
  12806. * scope.$watch(attrs.myCurrentTime, function(value) {
  12807. * format = value;
  12808. * updateTime();
  12809. * });
  12810. *
  12811. * stopTime = $interval(updateTime, 1000);
  12812. *
  12813. * // listen on DOM destroy (removal) event, and cancel the next UI update
  12814. * // to prevent updating time after the DOM element was removed.
  12815. * element.on('$destroy', function() {
  12816. * $interval.cancel(stopTime);
  12817. * });
  12818. * }
  12819. * }]);
  12820. * </script>
  12821. *
  12822. * <div>
  12823. * <div ng-controller="ExampleController">
  12824. * <label>Date format: <input ng-model="format"></label> <hr/>
  12825. * Current time is: <span my-current-time="format"></span>
  12826. * <hr/>
  12827. * Blood 1 : <font color='red'>{{blood_1}}</font>
  12828. * Blood 2 : <font color='red'>{{blood_2}}</font>
  12829. * <button type="button" data-ng-click="fight()">Fight</button>
  12830. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  12831. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  12832. * </div>
  12833. * </div>
  12834. *
  12835. * </file>
  12836. * </example>
  12837. */
  12838. var interval = $$intervalFactory(setIntervalFn, clearIntervalFn);
  12839. /**
  12840. * @ngdoc method
  12841. * @name $interval#cancel
  12842. *
  12843. * @description
  12844. * Cancels a task associated with the `promise`.
  12845. *
  12846. * @param {Promise=} promise returned by the `$interval` function.
  12847. * @returns {boolean} Returns `true` if the task was successfully canceled.
  12848. */
  12849. interval.cancel = function(promise) {
  12850. if (!promise) return false;
  12851. if (!promise.hasOwnProperty('$$intervalId')) {
  12852. throw $intervalMinErr('badprom',
  12853. '`$interval.cancel()` called with a promise that was not generated by `$interval()`.');
  12854. }
  12855. if (!intervals.hasOwnProperty(promise.$$intervalId)) return false;
  12856. var id = promise.$$intervalId;
  12857. var deferred = intervals[id];
  12858. // Interval cancels should not report an unhandled promise.
  12859. markQExceptionHandled(deferred.promise);
  12860. deferred.reject('canceled');
  12861. clearIntervalFn(id);
  12862. return true;
  12863. };
  12864. return interval;
  12865. }];
  12866. }
  12867. /** @this */
  12868. function $$IntervalFactoryProvider() {
  12869. this.$get = ['$browser', '$q', '$$q', '$rootScope',
  12870. function($browser, $q, $$q, $rootScope) {
  12871. return function intervalFactory(setIntervalFn, clearIntervalFn) {
  12872. return function intervalFn(fn, delay, count, invokeApply) {
  12873. var hasParams = arguments.length > 4,
  12874. args = hasParams ? sliceArgs(arguments, 4) : [],
  12875. iteration = 0,
  12876. skipApply = isDefined(invokeApply) && !invokeApply,
  12877. deferred = (skipApply ? $$q : $q).defer(),
  12878. promise = deferred.promise;
  12879. count = isDefined(count) ? count : 0;
  12880. function callback() {
  12881. if (!hasParams) {
  12882. fn(iteration);
  12883. } else {
  12884. fn.apply(null, args);
  12885. }
  12886. }
  12887. function tick() {
  12888. if (skipApply) {
  12889. $browser.defer(callback);
  12890. } else {
  12891. $rootScope.$evalAsync(callback);
  12892. }
  12893. deferred.notify(iteration++);
  12894. if (count > 0 && iteration >= count) {
  12895. deferred.resolve(iteration);
  12896. clearIntervalFn(promise.$$intervalId);
  12897. }
  12898. if (!skipApply) $rootScope.$apply();
  12899. }
  12900. promise.$$intervalId = setIntervalFn(tick, delay, deferred, skipApply);
  12901. return promise;
  12902. };
  12903. };
  12904. }];
  12905. }
  12906. /**
  12907. * @ngdoc service
  12908. * @name $jsonpCallbacks
  12909. * @requires $window
  12910. * @description
  12911. * This service handles the lifecycle of callbacks to handle JSONP requests.
  12912. * Override this service if you wish to customise where the callbacks are stored and
  12913. * how they vary compared to the requested url.
  12914. */
  12915. var $jsonpCallbacksProvider = /** @this */ function() {
  12916. this.$get = function() {
  12917. var callbacks = angular.callbacks;
  12918. var callbackMap = {};
  12919. function createCallback(callbackId) {
  12920. var callback = function(data) {
  12921. callback.data = data;
  12922. callback.called = true;
  12923. };
  12924. callback.id = callbackId;
  12925. return callback;
  12926. }
  12927. return {
  12928. /**
  12929. * @ngdoc method
  12930. * @name $jsonpCallbacks#createCallback
  12931. * @param {string} url the url of the JSONP request
  12932. * @returns {string} the callback path to send to the server as part of the JSONP request
  12933. * @description
  12934. * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
  12935. * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
  12936. */
  12937. createCallback: function(url) {
  12938. var callbackId = '_' + (callbacks.$$counter++).toString(36);
  12939. var callbackPath = 'angular.callbacks.' + callbackId;
  12940. var callback = createCallback(callbackId);
  12941. callbackMap[callbackPath] = callbacks[callbackId] = callback;
  12942. return callbackPath;
  12943. },
  12944. /**
  12945. * @ngdoc method
  12946. * @name $jsonpCallbacks#wasCalled
  12947. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12948. * @returns {boolean} whether the callback has been called, as a result of the JSONP response
  12949. * @description
  12950. * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
  12951. * callback that was passed in the request.
  12952. */
  12953. wasCalled: function(callbackPath) {
  12954. return callbackMap[callbackPath].called;
  12955. },
  12956. /**
  12957. * @ngdoc method
  12958. * @name $jsonpCallbacks#getResponse
  12959. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12960. * @returns {*} the data received from the response via the registered callback
  12961. * @description
  12962. * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
  12963. * in the JSONP response.
  12964. */
  12965. getResponse: function(callbackPath) {
  12966. return callbackMap[callbackPath].data;
  12967. },
  12968. /**
  12969. * @ngdoc method
  12970. * @name $jsonpCallbacks#removeCallback
  12971. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12972. * @description
  12973. * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
  12974. * completed or timed-out.
  12975. */
  12976. removeCallback: function(callbackPath) {
  12977. var callback = callbackMap[callbackPath];
  12978. delete callbacks[callback.id];
  12979. delete callbackMap[callbackPath];
  12980. }
  12981. };
  12982. };
  12983. };
  12984. /**
  12985. * @ngdoc service
  12986. * @name $locale
  12987. *
  12988. * @description
  12989. * $locale service provides localization rules for various AngularJS components. As of right now the
  12990. * only public api is:
  12991. *
  12992. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  12993. */
  12994. /* global stripHash: true */
  12995. var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
  12996. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  12997. var $locationMinErr = minErr('$location');
  12998. /**
  12999. * Encode path using encodeUriSegment, ignoring forward slashes
  13000. *
  13001. * @param {string} path Path to encode
  13002. * @returns {string}
  13003. */
  13004. function encodePath(path) {
  13005. var segments = path.split('/'),
  13006. i = segments.length;
  13007. while (i--) {
  13008. // decode forward slashes to prevent them from being double encoded
  13009. segments[i] = encodeUriSegment(segments[i].replace(/%2F/g, '/'));
  13010. }
  13011. return segments.join('/');
  13012. }
  13013. function decodePath(path, html5Mode) {
  13014. var segments = path.split('/'),
  13015. i = segments.length;
  13016. while (i--) {
  13017. segments[i] = decodeURIComponent(segments[i]);
  13018. if (html5Mode) {
  13019. // encode forward slashes to prevent them from being mistaken for path separators
  13020. segments[i] = segments[i].replace(/\//g, '%2F');
  13021. }
  13022. }
  13023. return segments.join('/');
  13024. }
  13025. function normalizePath(pathValue, searchValue, hashValue) {
  13026. var search = toKeyValue(searchValue),
  13027. hash = hashValue ? '#' + encodeUriSegment(hashValue) : '',
  13028. path = encodePath(pathValue);
  13029. return path + (search ? '?' + search : '') + hash;
  13030. }
  13031. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  13032. var parsedUrl = urlResolve(absoluteUrl);
  13033. locationObj.$$protocol = parsedUrl.protocol;
  13034. locationObj.$$host = parsedUrl.hostname;
  13035. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  13036. }
  13037. var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
  13038. function parseAppUrl(url, locationObj, html5Mode) {
  13039. if (DOUBLE_SLASH_REGEX.test(url)) {
  13040. throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
  13041. }
  13042. var prefixed = (url.charAt(0) !== '/');
  13043. if (prefixed) {
  13044. url = '/' + url;
  13045. }
  13046. var match = urlResolve(url);
  13047. var path = prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname;
  13048. locationObj.$$path = decodePath(path, html5Mode);
  13049. locationObj.$$search = parseKeyValue(match.search);
  13050. locationObj.$$hash = decodeURIComponent(match.hash);
  13051. // make sure path starts with '/';
  13052. if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
  13053. locationObj.$$path = '/' + locationObj.$$path;
  13054. }
  13055. }
  13056. function startsWith(str, search) {
  13057. return str.slice(0, search.length) === search;
  13058. }
  13059. /**
  13060. *
  13061. * @param {string} base
  13062. * @param {string} url
  13063. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  13064. * the expected string.
  13065. */
  13066. function stripBaseUrl(base, url) {
  13067. if (startsWith(url, base)) {
  13068. return url.substr(base.length);
  13069. }
  13070. }
  13071. function stripHash(url) {
  13072. var index = url.indexOf('#');
  13073. return index === -1 ? url : url.substr(0, index);
  13074. }
  13075. function stripFile(url) {
  13076. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  13077. }
  13078. /* return the server only (scheme://host:port) */
  13079. function serverBase(url) {
  13080. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  13081. }
  13082. /**
  13083. * LocationHtml5Url represents a URL
  13084. * This object is exposed as $location service when HTML5 mode is enabled and supported
  13085. *
  13086. * @constructor
  13087. * @param {string} appBase application base URL
  13088. * @param {string} appBaseNoFile application base URL stripped of any filename
  13089. * @param {string} basePrefix URL path prefix
  13090. */
  13091. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  13092. this.$$html5 = true;
  13093. basePrefix = basePrefix || '';
  13094. parseAbsoluteUrl(appBase, this);
  13095. /**
  13096. * Parse given HTML5 (regular) URL string into properties
  13097. * @param {string} url HTML5 URL
  13098. * @private
  13099. */
  13100. this.$$parse = function(url) {
  13101. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  13102. if (!isString(pathUrl)) {
  13103. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  13104. appBaseNoFile);
  13105. }
  13106. parseAppUrl(pathUrl, this, true);
  13107. if (!this.$$path) {
  13108. this.$$path = '/';
  13109. }
  13110. this.$$compose();
  13111. };
  13112. this.$$normalizeUrl = function(url) {
  13113. return appBaseNoFile + url.substr(1); // first char is always '/'
  13114. };
  13115. this.$$parseLinkUrl = function(url, relHref) {
  13116. if (relHref && relHref[0] === '#') {
  13117. // special case for links to hash fragments:
  13118. // keep the old url and only replace the hash fragment
  13119. this.hash(relHref.slice(1));
  13120. return true;
  13121. }
  13122. var appUrl, prevAppUrl;
  13123. var rewrittenUrl;
  13124. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  13125. prevAppUrl = appUrl;
  13126. if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  13127. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  13128. } else {
  13129. rewrittenUrl = appBase + prevAppUrl;
  13130. }
  13131. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  13132. rewrittenUrl = appBaseNoFile + appUrl;
  13133. } else if (appBaseNoFile === url + '/') {
  13134. rewrittenUrl = appBaseNoFile;
  13135. }
  13136. if (rewrittenUrl) {
  13137. this.$$parse(rewrittenUrl);
  13138. }
  13139. return !!rewrittenUrl;
  13140. };
  13141. }
  13142. /**
  13143. * LocationHashbangUrl represents URL
  13144. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  13145. * It also serves as the base class for html5 mode fallback on legacy browsers.
  13146. *
  13147. * @constructor
  13148. * @param {string} appBase application base URL
  13149. * @param {string} appBaseNoFile application base URL stripped of any filename
  13150. * @param {string} hashPrefix hashbang prefix
  13151. */
  13152. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  13153. parseAbsoluteUrl(appBase, this);
  13154. /**
  13155. * Parse given hashbang URL into properties
  13156. * @param {string} url Hashbang URL
  13157. * @private
  13158. */
  13159. this.$$parse = function(url) {
  13160. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  13161. var withoutHashUrl;
  13162. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  13163. // The rest of the URL starts with a hash so we have
  13164. // got either a hashbang path or a plain hash fragment
  13165. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  13166. if (isUndefined(withoutHashUrl)) {
  13167. // There was no hashbang prefix so we just have a hash fragment
  13168. withoutHashUrl = withoutBaseUrl;
  13169. }
  13170. } else {
  13171. // There was no hashbang path nor hash fragment:
  13172. // If we are in HTML5 mode we use what is left as the path;
  13173. // Otherwise we ignore what is left
  13174. if (this.$$html5) {
  13175. withoutHashUrl = withoutBaseUrl;
  13176. } else {
  13177. withoutHashUrl = '';
  13178. if (isUndefined(withoutBaseUrl)) {
  13179. appBase = url;
  13180. /** @type {?} */ (this).replace();
  13181. }
  13182. }
  13183. }
  13184. parseAppUrl(withoutHashUrl, this, false);
  13185. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  13186. this.$$compose();
  13187. /*
  13188. * In Windows, on an anchor node on documents loaded from
  13189. * the filesystem, the browser will return a pathname
  13190. * prefixed with the drive name ('/C:/path') when a
  13191. * pathname without a drive is set:
  13192. * * a.setAttribute('href', '/foo')
  13193. * * a.pathname === '/C:/foo' //true
  13194. *
  13195. * Inside of AngularJS, we're always using pathnames that
  13196. * do not include drive names for routing.
  13197. */
  13198. function removeWindowsDriveName(path, url, base) {
  13199. /*
  13200. Matches paths for file protocol on windows,
  13201. such as /C:/foo/bar, and captures only /foo/bar.
  13202. */
  13203. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  13204. var firstPathSegmentMatch;
  13205. //Get the relative path from the input URL.
  13206. if (startsWith(url, base)) {
  13207. url = url.replace(base, '');
  13208. }
  13209. // The input URL intentionally contains a first path segment that ends with a colon.
  13210. if (windowsFilePathExp.exec(url)) {
  13211. return path;
  13212. }
  13213. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  13214. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  13215. }
  13216. };
  13217. this.$$normalizeUrl = function(url) {
  13218. return appBase + (url ? hashPrefix + url : '');
  13219. };
  13220. this.$$parseLinkUrl = function(url, relHref) {
  13221. if (stripHash(appBase) === stripHash(url)) {
  13222. this.$$parse(url);
  13223. return true;
  13224. }
  13225. return false;
  13226. };
  13227. }
  13228. /**
  13229. * LocationHashbangUrl represents URL
  13230. * This object is exposed as $location service when html5 history api is enabled but the browser
  13231. * does not support it.
  13232. *
  13233. * @constructor
  13234. * @param {string} appBase application base URL
  13235. * @param {string} appBaseNoFile application base URL stripped of any filename
  13236. * @param {string} hashPrefix hashbang prefix
  13237. */
  13238. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  13239. this.$$html5 = true;
  13240. LocationHashbangUrl.apply(this, arguments);
  13241. this.$$parseLinkUrl = function(url, relHref) {
  13242. if (relHref && relHref[0] === '#') {
  13243. // special case for links to hash fragments:
  13244. // keep the old url and only replace the hash fragment
  13245. this.hash(relHref.slice(1));
  13246. return true;
  13247. }
  13248. var rewrittenUrl;
  13249. var appUrl;
  13250. if (appBase === stripHash(url)) {
  13251. rewrittenUrl = url;
  13252. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  13253. rewrittenUrl = appBase + hashPrefix + appUrl;
  13254. } else if (appBaseNoFile === url + '/') {
  13255. rewrittenUrl = appBaseNoFile;
  13256. }
  13257. if (rewrittenUrl) {
  13258. this.$$parse(rewrittenUrl);
  13259. }
  13260. return !!rewrittenUrl;
  13261. };
  13262. this.$$normalizeUrl = function(url) {
  13263. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  13264. return appBase + hashPrefix + url;
  13265. };
  13266. }
  13267. var locationPrototype = {
  13268. /**
  13269. * Ensure absolute URL is initialized.
  13270. * @private
  13271. */
  13272. $$absUrl:'',
  13273. /**
  13274. * Are we in html5 mode?
  13275. * @private
  13276. */
  13277. $$html5: false,
  13278. /**
  13279. * Has any change been replacing?
  13280. * @private
  13281. */
  13282. $$replace: false,
  13283. /**
  13284. * Compose url and update `url` and `absUrl` property
  13285. * @private
  13286. */
  13287. $$compose: function() {
  13288. this.$$url = normalizePath(this.$$path, this.$$search, this.$$hash);
  13289. this.$$absUrl = this.$$normalizeUrl(this.$$url);
  13290. this.$$urlUpdatedByLocation = true;
  13291. },
  13292. /**
  13293. * @ngdoc method
  13294. * @name $location#absUrl
  13295. *
  13296. * @description
  13297. * This method is getter only.
  13298. *
  13299. * Return full URL representation with all segments encoded according to rules specified in
  13300. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  13301. *
  13302. *
  13303. * ```js
  13304. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13305. * var absUrl = $location.absUrl();
  13306. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  13307. * ```
  13308. *
  13309. * @return {string} full URL
  13310. */
  13311. absUrl: locationGetter('$$absUrl'),
  13312. /**
  13313. * @ngdoc method
  13314. * @name $location#url
  13315. *
  13316. * @description
  13317. * This method is getter / setter.
  13318. *
  13319. * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
  13320. *
  13321. * Change path, search and hash, when called with parameter and return `$location`.
  13322. *
  13323. *
  13324. * ```js
  13325. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13326. * var url = $location.url();
  13327. * // => "/some/path?foo=bar&baz=xoxo"
  13328. * ```
  13329. *
  13330. * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
  13331. * @return {string} url
  13332. */
  13333. url: function(url) {
  13334. if (isUndefined(url)) {
  13335. return this.$$url;
  13336. }
  13337. var match = PATH_MATCH.exec(url);
  13338. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  13339. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  13340. this.hash(match[5] || '');
  13341. return this;
  13342. },
  13343. /**
  13344. * @ngdoc method
  13345. * @name $location#protocol
  13346. *
  13347. * @description
  13348. * This method is getter only.
  13349. *
  13350. * Return protocol of current URL.
  13351. *
  13352. *
  13353. * ```js
  13354. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13355. * var protocol = $location.protocol();
  13356. * // => "http"
  13357. * ```
  13358. *
  13359. * @return {string} protocol of current URL
  13360. */
  13361. protocol: locationGetter('$$protocol'),
  13362. /**
  13363. * @ngdoc method
  13364. * @name $location#host
  13365. *
  13366. * @description
  13367. * This method is getter only.
  13368. *
  13369. * Return host of current URL.
  13370. *
  13371. * Note: compared to the non-AngularJS version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  13372. *
  13373. *
  13374. * ```js
  13375. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13376. * var host = $location.host();
  13377. * // => "example.com"
  13378. *
  13379. * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  13380. * host = $location.host();
  13381. * // => "example.com"
  13382. * host = location.host;
  13383. * // => "example.com:8080"
  13384. * ```
  13385. *
  13386. * @return {string} host of current URL.
  13387. */
  13388. host: locationGetter('$$host'),
  13389. /**
  13390. * @ngdoc method
  13391. * @name $location#port
  13392. *
  13393. * @description
  13394. * This method is getter only.
  13395. *
  13396. * Return port of current URL.
  13397. *
  13398. *
  13399. * ```js
  13400. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13401. * var port = $location.port();
  13402. * // => 80
  13403. * ```
  13404. *
  13405. * @return {Number} port
  13406. */
  13407. port: locationGetter('$$port'),
  13408. /**
  13409. * @ngdoc method
  13410. * @name $location#path
  13411. *
  13412. * @description
  13413. * This method is getter / setter.
  13414. *
  13415. * Return path of current URL when called without any parameter.
  13416. *
  13417. * Change path when called with parameter and return `$location`.
  13418. *
  13419. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  13420. * if it is missing.
  13421. *
  13422. *
  13423. * ```js
  13424. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13425. * var path = $location.path();
  13426. * // => "/some/path"
  13427. * ```
  13428. *
  13429. * @param {(string|number)=} path New path
  13430. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  13431. */
  13432. path: locationGetterSetter('$$path', function(path) {
  13433. path = path !== null ? path.toString() : '';
  13434. return path.charAt(0) === '/' ? path : '/' + path;
  13435. }),
  13436. /**
  13437. * @ngdoc method
  13438. * @name $location#search
  13439. *
  13440. * @description
  13441. * This method is getter / setter.
  13442. *
  13443. * Return search part (as object) of current URL when called without any parameter.
  13444. *
  13445. * Change search part when called with parameter and return `$location`.
  13446. *
  13447. *
  13448. * ```js
  13449. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  13450. * var searchObject = $location.search();
  13451. * // => {foo: 'bar', baz: 'xoxo'}
  13452. *
  13453. * // set foo to 'yipee'
  13454. * $location.search('foo', 'yipee');
  13455. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  13456. * ```
  13457. *
  13458. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  13459. * hash object.
  13460. *
  13461. * When called with a single argument the method acts as a setter, setting the `search` component
  13462. * of `$location` to the specified value.
  13463. *
  13464. * If the argument is a hash object containing an array of values, these values will be encoded
  13465. * as duplicate search parameters in the URL.
  13466. *
  13467. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  13468. * will override only a single search property.
  13469. *
  13470. * If `paramValue` is an array, it will override the property of the `search` component of
  13471. * `$location` specified via the first argument.
  13472. *
  13473. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  13474. *
  13475. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  13476. * value nor trailing equal sign.
  13477. *
  13478. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  13479. * one or more arguments returns `$location` object itself.
  13480. */
  13481. search: function(search, paramValue) {
  13482. switch (arguments.length) {
  13483. case 0:
  13484. return this.$$search;
  13485. case 1:
  13486. if (isString(search) || isNumber(search)) {
  13487. search = search.toString();
  13488. this.$$search = parseKeyValue(search);
  13489. } else if (isObject(search)) {
  13490. search = copy(search, {});
  13491. // remove object undefined or null properties
  13492. forEach(search, function(value, key) {
  13493. if (value == null) delete search[key];
  13494. });
  13495. this.$$search = search;
  13496. } else {
  13497. throw $locationMinErr('isrcharg',
  13498. 'The first argument of the `$location#search()` call must be a string or an object.');
  13499. }
  13500. break;
  13501. default:
  13502. if (isUndefined(paramValue) || paramValue === null) {
  13503. delete this.$$search[search];
  13504. } else {
  13505. this.$$search[search] = paramValue;
  13506. }
  13507. }
  13508. this.$$compose();
  13509. return this;
  13510. },
  13511. /**
  13512. * @ngdoc method
  13513. * @name $location#hash
  13514. *
  13515. * @description
  13516. * This method is getter / setter.
  13517. *
  13518. * Returns the hash fragment when called without any parameters.
  13519. *
  13520. * Changes the hash fragment when called with a parameter and returns `$location`.
  13521. *
  13522. *
  13523. * ```js
  13524. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  13525. * var hash = $location.hash();
  13526. * // => "hashValue"
  13527. * ```
  13528. *
  13529. * @param {(string|number)=} hash New hash fragment
  13530. * @return {string} hash
  13531. */
  13532. hash: locationGetterSetter('$$hash', function(hash) {
  13533. return hash !== null ? hash.toString() : '';
  13534. }),
  13535. /**
  13536. * @ngdoc method
  13537. * @name $location#replace
  13538. *
  13539. * @description
  13540. * If called, all changes to $location during the current `$digest` will replace the current history
  13541. * record, instead of adding a new one.
  13542. */
  13543. replace: function() {
  13544. this.$$replace = true;
  13545. return this;
  13546. }
  13547. };
  13548. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  13549. Location.prototype = Object.create(locationPrototype);
  13550. /**
  13551. * @ngdoc method
  13552. * @name $location#state
  13553. *
  13554. * @description
  13555. * This method is getter / setter.
  13556. *
  13557. * Return the history state object when called without any parameter.
  13558. *
  13559. * Change the history state object when called with one parameter and return `$location`.
  13560. * The state object is later passed to `pushState` or `replaceState`.
  13561. *
  13562. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  13563. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  13564. * older browsers (like IE9 or Android < 4.0), don't use this method.
  13565. *
  13566. * @param {object=} state State object for pushState or replaceState
  13567. * @return {object} state
  13568. */
  13569. Location.prototype.state = function(state) {
  13570. if (!arguments.length) {
  13571. return this.$$state;
  13572. }
  13573. if (Location !== LocationHtml5Url || !this.$$html5) {
  13574. throw $locationMinErr('nostate', 'History API state support is available only ' +
  13575. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  13576. }
  13577. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  13578. // but we're changing the $$state reference to $browser.state() during the $digest
  13579. // so the modification window is narrow.
  13580. this.$$state = isUndefined(state) ? null : state;
  13581. this.$$urlUpdatedByLocation = true;
  13582. return this;
  13583. };
  13584. });
  13585. function locationGetter(property) {
  13586. return /** @this */ function() {
  13587. return this[property];
  13588. };
  13589. }
  13590. function locationGetterSetter(property, preprocess) {
  13591. return /** @this */ function(value) {
  13592. if (isUndefined(value)) {
  13593. return this[property];
  13594. }
  13595. this[property] = preprocess(value);
  13596. this.$$compose();
  13597. return this;
  13598. };
  13599. }
  13600. /**
  13601. * @ngdoc service
  13602. * @name $location
  13603. *
  13604. * @requires $rootElement
  13605. *
  13606. * @description
  13607. * The $location service parses the URL in the browser address bar (based on the
  13608. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  13609. * available to your application. Changes to the URL in the address bar are reflected into
  13610. * $location service and changes to $location are reflected into the browser address bar.
  13611. *
  13612. * **The $location service:**
  13613. *
  13614. * - Exposes the current URL in the browser address bar, so you can
  13615. * - Watch and observe the URL.
  13616. * - Change the URL.
  13617. * - Synchronizes the URL with the browser when the user
  13618. * - Changes the address bar.
  13619. * - Clicks the back or forward button (or clicks a History link).
  13620. * - Clicks on a link.
  13621. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  13622. *
  13623. * For more information see {@link guide/$location Developer Guide: Using $location}
  13624. */
  13625. /**
  13626. * @ngdoc provider
  13627. * @name $locationProvider
  13628. * @this
  13629. *
  13630. * @description
  13631. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  13632. */
  13633. function $LocationProvider() {
  13634. var hashPrefix = '!',
  13635. html5Mode = {
  13636. enabled: false,
  13637. requireBase: true,
  13638. rewriteLinks: true
  13639. };
  13640. /**
  13641. * @ngdoc method
  13642. * @name $locationProvider#hashPrefix
  13643. * @description
  13644. * The default value for the prefix is `'!'`.
  13645. * @param {string=} prefix Prefix for hash part (containing path and search)
  13646. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  13647. */
  13648. this.hashPrefix = function(prefix) {
  13649. if (isDefined(prefix)) {
  13650. hashPrefix = prefix;
  13651. return this;
  13652. } else {
  13653. return hashPrefix;
  13654. }
  13655. };
  13656. /**
  13657. * @ngdoc method
  13658. * @name $locationProvider#html5Mode
  13659. * @description
  13660. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  13661. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  13662. * properties:
  13663. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  13664. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  13665. * support `pushState`.
  13666. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  13667. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  13668. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  13669. * See the {@link guide/$location $location guide for more information}
  13670. * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
  13671. * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
  13672. * only happen on links with an attribute that matches the given string. For example, if set
  13673. * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
  13674. * Note that [attribute name normalization](guide/directive#normalization) does not apply
  13675. * here, so `'internalLink'` will **not** match `'internal-link'`.
  13676. *
  13677. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  13678. */
  13679. this.html5Mode = function(mode) {
  13680. if (isBoolean(mode)) {
  13681. html5Mode.enabled = mode;
  13682. return this;
  13683. } else if (isObject(mode)) {
  13684. if (isBoolean(mode.enabled)) {
  13685. html5Mode.enabled = mode.enabled;
  13686. }
  13687. if (isBoolean(mode.requireBase)) {
  13688. html5Mode.requireBase = mode.requireBase;
  13689. }
  13690. if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
  13691. html5Mode.rewriteLinks = mode.rewriteLinks;
  13692. }
  13693. return this;
  13694. } else {
  13695. return html5Mode;
  13696. }
  13697. };
  13698. /**
  13699. * @ngdoc event
  13700. * @name $location#$locationChangeStart
  13701. * @eventType broadcast on root scope
  13702. * @description
  13703. * Broadcasted before a URL will change.
  13704. *
  13705. * This change can be prevented by calling
  13706. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  13707. * details about event object. Upon successful change
  13708. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  13709. *
  13710. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  13711. * the browser supports the HTML5 History API.
  13712. *
  13713. * @param {Object} angularEvent Synthetic event object.
  13714. * @param {string} newUrl New URL
  13715. * @param {string=} oldUrl URL that was before it was changed.
  13716. * @param {string=} newState New history state object
  13717. * @param {string=} oldState History state object that was before it was changed.
  13718. */
  13719. /**
  13720. * @ngdoc event
  13721. * @name $location#$locationChangeSuccess
  13722. * @eventType broadcast on root scope
  13723. * @description
  13724. * Broadcasted after a URL was changed.
  13725. *
  13726. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  13727. * the browser supports the HTML5 History API.
  13728. *
  13729. * @param {Object} angularEvent Synthetic event object.
  13730. * @param {string} newUrl New URL
  13731. * @param {string=} oldUrl URL that was before it was changed.
  13732. * @param {string=} newState New history state object
  13733. * @param {string=} oldState History state object that was before it was changed.
  13734. */
  13735. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  13736. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  13737. var $location,
  13738. LocationMode,
  13739. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  13740. initialUrl = $browser.url(),
  13741. appBase;
  13742. if (html5Mode.enabled) {
  13743. if (!baseHref && html5Mode.requireBase) {
  13744. throw $locationMinErr('nobase',
  13745. '$location in HTML5 mode requires a <base> tag to be present!');
  13746. }
  13747. appBase = serverBase(initialUrl) + (baseHref || '/');
  13748. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  13749. } else {
  13750. appBase = stripHash(initialUrl);
  13751. LocationMode = LocationHashbangUrl;
  13752. }
  13753. var appBaseNoFile = stripFile(appBase);
  13754. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  13755. $location.$$parseLinkUrl(initialUrl, initialUrl);
  13756. $location.$$state = $browser.state();
  13757. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  13758. // Determine if two URLs are equal despite potentially having different encoding/normalizing
  13759. // such as $location.absUrl() vs $browser.url()
  13760. // See https://github.com/angular/angular.js/issues/16592
  13761. function urlsEqual(a, b) {
  13762. return a === b || urlResolve(a).href === urlResolve(b).href;
  13763. }
  13764. function setBrowserUrlWithFallback(url, replace, state) {
  13765. var oldUrl = $location.url();
  13766. var oldState = $location.$$state;
  13767. try {
  13768. $browser.url(url, replace, state);
  13769. // Make sure $location.state() returns referentially identical (not just deeply equal)
  13770. // state object; this makes possible quick checking if the state changed in the digest
  13771. // loop. Checking deep equality would be too expensive.
  13772. $location.$$state = $browser.state();
  13773. } catch (e) {
  13774. // Restore old values if pushState fails
  13775. $location.url(oldUrl);
  13776. $location.$$state = oldState;
  13777. throw e;
  13778. }
  13779. }
  13780. $rootElement.on('click', function(event) {
  13781. var rewriteLinks = html5Mode.rewriteLinks;
  13782. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  13783. // currently we open nice url link and redirect then
  13784. if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
  13785. var elm = jqLite(event.target);
  13786. // traverse the DOM up to find first A tag
  13787. while (nodeName_(elm[0]) !== 'a') {
  13788. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  13789. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  13790. }
  13791. if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
  13792. var absHref = elm.prop('href');
  13793. // get the actual href attribute - see
  13794. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  13795. var relHref = elm.attr('href') || elm.attr('xlink:href');
  13796. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  13797. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  13798. // an animation.
  13799. absHref = urlResolve(absHref.animVal).href;
  13800. }
  13801. // Ignore when url is started with javascript: or mailto:
  13802. if (IGNORE_URI_REGEXP.test(absHref)) return;
  13803. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  13804. if ($location.$$parseLinkUrl(absHref, relHref)) {
  13805. // We do a preventDefault for all urls that are part of the AngularJS application,
  13806. // in html5mode and also without, so that we are able to abort navigation without
  13807. // getting double entries in the location history.
  13808. event.preventDefault();
  13809. // update location manually
  13810. if ($location.absUrl() !== $browser.url()) {
  13811. $rootScope.$apply();
  13812. }
  13813. }
  13814. }
  13815. });
  13816. // rewrite hashbang url <> html5 url
  13817. if ($location.absUrl() !== initialUrl) {
  13818. $browser.url($location.absUrl(), true);
  13819. }
  13820. var initializing = true;
  13821. // update $location when $browser url changes
  13822. $browser.onUrlChange(function(newUrl, newState) {
  13823. if (!startsWith(newUrl, appBaseNoFile)) {
  13824. // If we are navigating outside of the app then force a reload
  13825. $window.location.href = newUrl;
  13826. return;
  13827. }
  13828. $rootScope.$evalAsync(function() {
  13829. var oldUrl = $location.absUrl();
  13830. var oldState = $location.$$state;
  13831. var defaultPrevented;
  13832. $location.$$parse(newUrl);
  13833. $location.$$state = newState;
  13834. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  13835. newState, oldState).defaultPrevented;
  13836. // if the location was changed by a `$locationChangeStart` handler then stop
  13837. // processing this location change
  13838. if ($location.absUrl() !== newUrl) return;
  13839. if (defaultPrevented) {
  13840. $location.$$parse(oldUrl);
  13841. $location.$$state = oldState;
  13842. setBrowserUrlWithFallback(oldUrl, false, oldState);
  13843. } else {
  13844. initializing = false;
  13845. afterLocationChange(oldUrl, oldState);
  13846. }
  13847. });
  13848. if (!$rootScope.$$phase) $rootScope.$digest();
  13849. });
  13850. // update browser
  13851. $rootScope.$watch(function $locationWatch() {
  13852. if (initializing || $location.$$urlUpdatedByLocation) {
  13853. $location.$$urlUpdatedByLocation = false;
  13854. var oldUrl = $browser.url();
  13855. var newUrl = $location.absUrl();
  13856. var oldState = $browser.state();
  13857. var currentReplace = $location.$$replace;
  13858. var urlOrStateChanged = !urlsEqual(oldUrl, newUrl) ||
  13859. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  13860. if (initializing || urlOrStateChanged) {
  13861. initializing = false;
  13862. $rootScope.$evalAsync(function() {
  13863. var newUrl = $location.absUrl();
  13864. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  13865. $location.$$state, oldState).defaultPrevented;
  13866. // if the location was changed by a `$locationChangeStart` handler then stop
  13867. // processing this location change
  13868. if ($location.absUrl() !== newUrl) return;
  13869. if (defaultPrevented) {
  13870. $location.$$parse(oldUrl);
  13871. $location.$$state = oldState;
  13872. } else {
  13873. if (urlOrStateChanged) {
  13874. setBrowserUrlWithFallback(newUrl, currentReplace,
  13875. oldState === $location.$$state ? null : $location.$$state);
  13876. }
  13877. afterLocationChange(oldUrl, oldState);
  13878. }
  13879. });
  13880. }
  13881. }
  13882. $location.$$replace = false;
  13883. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  13884. // there is a change
  13885. });
  13886. return $location;
  13887. function afterLocationChange(oldUrl, oldState) {
  13888. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  13889. $location.$$state, oldState);
  13890. }
  13891. }];
  13892. }
  13893. /**
  13894. * @ngdoc service
  13895. * @name $log
  13896. * @requires $window
  13897. *
  13898. * @description
  13899. * Simple service for logging. Default implementation safely writes the message
  13900. * into the browser's console (if present).
  13901. *
  13902. * The main purpose of this service is to simplify debugging and troubleshooting.
  13903. *
  13904. * To reveal the location of the calls to `$log` in the JavaScript console,
  13905. * you can "blackbox" the AngularJS source in your browser:
  13906. *
  13907. * [Mozilla description of blackboxing](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Black_box_a_source).
  13908. * [Chrome description of blackboxing](https://developer.chrome.com/devtools/docs/blackboxing).
  13909. *
  13910. * Note: Not all browsers support blackboxing.
  13911. *
  13912. * The default is to log `debug` messages. You can use
  13913. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  13914. *
  13915. * @example
  13916. <example module="logExample" name="log-service">
  13917. <file name="script.js">
  13918. angular.module('logExample', [])
  13919. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  13920. $scope.$log = $log;
  13921. $scope.message = 'Hello World!';
  13922. }]);
  13923. </file>
  13924. <file name="index.html">
  13925. <div ng-controller="LogController">
  13926. <p>Reload this page with open console, enter text and hit the log button...</p>
  13927. <label>Message:
  13928. <input type="text" ng-model="message" /></label>
  13929. <button ng-click="$log.log(message)">log</button>
  13930. <button ng-click="$log.warn(message)">warn</button>
  13931. <button ng-click="$log.info(message)">info</button>
  13932. <button ng-click="$log.error(message)">error</button>
  13933. <button ng-click="$log.debug(message)">debug</button>
  13934. </div>
  13935. </file>
  13936. </example>
  13937. */
  13938. /**
  13939. * @ngdoc provider
  13940. * @name $logProvider
  13941. * @this
  13942. *
  13943. * @description
  13944. * Use the `$logProvider` to configure how the application logs messages
  13945. */
  13946. function $LogProvider() {
  13947. var debug = true,
  13948. self = this;
  13949. /**
  13950. * @ngdoc method
  13951. * @name $logProvider#debugEnabled
  13952. * @description
  13953. * @param {boolean=} flag enable or disable debug level messages
  13954. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  13955. */
  13956. this.debugEnabled = function(flag) {
  13957. if (isDefined(flag)) {
  13958. debug = flag;
  13959. return this;
  13960. } else {
  13961. return debug;
  13962. }
  13963. };
  13964. this.$get = ['$window', function($window) {
  13965. // Support: IE 9-11, Edge 12-14+
  13966. // IE/Edge display errors in such a way that it requires the user to click in 4 places
  13967. // to see the stack trace. There is no way to feature-detect it so there's a chance
  13968. // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't
  13969. // break apps. Other browsers display errors in a sensible way and some of them map stack
  13970. // traces along source maps if available so it makes sense to let browsers display it
  13971. // as they want.
  13972. var formatStackTrace = msie || /\bEdge\//.test($window.navigator && $window.navigator.userAgent);
  13973. return {
  13974. /**
  13975. * @ngdoc method
  13976. * @name $log#log
  13977. *
  13978. * @description
  13979. * Write a log message
  13980. */
  13981. log: consoleLog('log'),
  13982. /**
  13983. * @ngdoc method
  13984. * @name $log#info
  13985. *
  13986. * @description
  13987. * Write an information message
  13988. */
  13989. info: consoleLog('info'),
  13990. /**
  13991. * @ngdoc method
  13992. * @name $log#warn
  13993. *
  13994. * @description
  13995. * Write a warning message
  13996. */
  13997. warn: consoleLog('warn'),
  13998. /**
  13999. * @ngdoc method
  14000. * @name $log#error
  14001. *
  14002. * @description
  14003. * Write an error message
  14004. */
  14005. error: consoleLog('error'),
  14006. /**
  14007. * @ngdoc method
  14008. * @name $log#debug
  14009. *
  14010. * @description
  14011. * Write a debug message
  14012. */
  14013. debug: (function() {
  14014. var fn = consoleLog('debug');
  14015. return function() {
  14016. if (debug) {
  14017. fn.apply(self, arguments);
  14018. }
  14019. };
  14020. })()
  14021. };
  14022. function formatError(arg) {
  14023. if (isError(arg)) {
  14024. if (arg.stack && formatStackTrace) {
  14025. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  14026. ? 'Error: ' + arg.message + '\n' + arg.stack
  14027. : arg.stack;
  14028. } else if (arg.sourceURL) {
  14029. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  14030. }
  14031. }
  14032. return arg;
  14033. }
  14034. function consoleLog(type) {
  14035. var console = $window.console || {},
  14036. logFn = console[type] || console.log || noop;
  14037. return function() {
  14038. var args = [];
  14039. forEach(arguments, function(arg) {
  14040. args.push(formatError(arg));
  14041. });
  14042. // Support: IE 9 only
  14043. // console methods don't inherit from Function.prototype in IE 9 so we can't
  14044. // call `logFn.apply(console, args)` directly.
  14045. return Function.prototype.apply.call(logFn, console, args);
  14046. };
  14047. }
  14048. }];
  14049. }
  14050. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  14051. * Any commits to this file should be reviewed with security in mind. *
  14052. * Changes to this file can potentially create security vulnerabilities. *
  14053. * An approval from 2 Core members with history of modifying *
  14054. * this file is required. *
  14055. * *
  14056. * Does the change somehow allow for arbitrary javascript to be executed? *
  14057. * Or allows for someone to change the prototype of built-in objects? *
  14058. * Or gives undesired access to variables likes document or window? *
  14059. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  14060. var $parseMinErr = minErr('$parse');
  14061. var objectValueOf = {}.constructor.prototype.valueOf;
  14062. // Sandboxing AngularJS Expressions
  14063. // ------------------------------
  14064. // AngularJS expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by
  14065. // various means such as obtaining a reference to native JS functions like the Function constructor.
  14066. //
  14067. // As an example, consider the following AngularJS expression:
  14068. //
  14069. // {}.toString.constructor('alert("evil JS code")')
  14070. //
  14071. // It is important to realize that if you create an expression from a string that contains user provided
  14072. // content then it is possible that your application contains a security vulnerability to an XSS style attack.
  14073. //
  14074. // See https://docs.angularjs.org/guide/security
  14075. function getStringValue(name) {
  14076. // Property names must be strings. This means that non-string objects cannot be used
  14077. // as keys in an object. Any non-string object, including a number, is typecasted
  14078. // into a string via the toString method.
  14079. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  14080. //
  14081. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  14082. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  14083. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  14084. //
  14085. // TypeError: Cannot convert object to primitive value
  14086. //
  14087. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  14088. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  14089. // such a 'broken' object as a key.
  14090. return name + '';
  14091. }
  14092. var OPERATORS = createMap();
  14093. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  14094. var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
  14095. /////////////////////////////////////////
  14096. /**
  14097. * @constructor
  14098. */
  14099. var Lexer = function Lexer(options) {
  14100. this.options = options;
  14101. };
  14102. Lexer.prototype = {
  14103. constructor: Lexer,
  14104. lex: function(text) {
  14105. this.text = text;
  14106. this.index = 0;
  14107. this.tokens = [];
  14108. while (this.index < this.text.length) {
  14109. var ch = this.text.charAt(this.index);
  14110. if (ch === '"' || ch === '\'') {
  14111. this.readString(ch);
  14112. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  14113. this.readNumber();
  14114. } else if (this.isIdentifierStart(this.peekMultichar())) {
  14115. this.readIdent();
  14116. } else if (this.is(ch, '(){}[].,;:?')) {
  14117. this.tokens.push({index: this.index, text: ch});
  14118. this.index++;
  14119. } else if (this.isWhitespace(ch)) {
  14120. this.index++;
  14121. } else {
  14122. var ch2 = ch + this.peek();
  14123. var ch3 = ch2 + this.peek(2);
  14124. var op1 = OPERATORS[ch];
  14125. var op2 = OPERATORS[ch2];
  14126. var op3 = OPERATORS[ch3];
  14127. if (op1 || op2 || op3) {
  14128. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  14129. this.tokens.push({index: this.index, text: token, operator: true});
  14130. this.index += token.length;
  14131. } else {
  14132. this.throwError('Unexpected next character ', this.index, this.index + 1);
  14133. }
  14134. }
  14135. }
  14136. return this.tokens;
  14137. },
  14138. is: function(ch, chars) {
  14139. return chars.indexOf(ch) !== -1;
  14140. },
  14141. peek: function(i) {
  14142. var num = i || 1;
  14143. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  14144. },
  14145. isNumber: function(ch) {
  14146. return ('0' <= ch && ch <= '9') && typeof ch === 'string';
  14147. },
  14148. isWhitespace: function(ch) {
  14149. // IE treats non-breaking space as \u00A0
  14150. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  14151. ch === '\n' || ch === '\v' || ch === '\u00A0');
  14152. },
  14153. isIdentifierStart: function(ch) {
  14154. return this.options.isIdentifierStart ?
  14155. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  14156. this.isValidIdentifierStart(ch);
  14157. },
  14158. isValidIdentifierStart: function(ch) {
  14159. return ('a' <= ch && ch <= 'z' ||
  14160. 'A' <= ch && ch <= 'Z' ||
  14161. '_' === ch || ch === '$');
  14162. },
  14163. isIdentifierContinue: function(ch) {
  14164. return this.options.isIdentifierContinue ?
  14165. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  14166. this.isValidIdentifierContinue(ch);
  14167. },
  14168. isValidIdentifierContinue: function(ch, cp) {
  14169. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  14170. },
  14171. codePointAt: function(ch) {
  14172. if (ch.length === 1) return ch.charCodeAt(0);
  14173. // eslint-disable-next-line no-bitwise
  14174. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  14175. },
  14176. peekMultichar: function() {
  14177. var ch = this.text.charAt(this.index);
  14178. var peek = this.peek();
  14179. if (!peek) {
  14180. return ch;
  14181. }
  14182. var cp1 = ch.charCodeAt(0);
  14183. var cp2 = peek.charCodeAt(0);
  14184. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  14185. return ch + peek;
  14186. }
  14187. return ch;
  14188. },
  14189. isExpOperator: function(ch) {
  14190. return (ch === '-' || ch === '+' || this.isNumber(ch));
  14191. },
  14192. throwError: function(error, start, end) {
  14193. end = end || this.index;
  14194. var colStr = (isDefined(start)
  14195. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  14196. : ' ' + end);
  14197. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  14198. error, colStr, this.text);
  14199. },
  14200. readNumber: function() {
  14201. var number = '';
  14202. var start = this.index;
  14203. while (this.index < this.text.length) {
  14204. var ch = lowercase(this.text.charAt(this.index));
  14205. if (ch === '.' || this.isNumber(ch)) {
  14206. number += ch;
  14207. } else {
  14208. var peekCh = this.peek();
  14209. if (ch === 'e' && this.isExpOperator(peekCh)) {
  14210. number += ch;
  14211. } else if (this.isExpOperator(ch) &&
  14212. peekCh && this.isNumber(peekCh) &&
  14213. number.charAt(number.length - 1) === 'e') {
  14214. number += ch;
  14215. } else if (this.isExpOperator(ch) &&
  14216. (!peekCh || !this.isNumber(peekCh)) &&
  14217. number.charAt(number.length - 1) === 'e') {
  14218. this.throwError('Invalid exponent');
  14219. } else {
  14220. break;
  14221. }
  14222. }
  14223. this.index++;
  14224. }
  14225. this.tokens.push({
  14226. index: start,
  14227. text: number,
  14228. constant: true,
  14229. value: Number(number)
  14230. });
  14231. },
  14232. readIdent: function() {
  14233. var start = this.index;
  14234. this.index += this.peekMultichar().length;
  14235. while (this.index < this.text.length) {
  14236. var ch = this.peekMultichar();
  14237. if (!this.isIdentifierContinue(ch)) {
  14238. break;
  14239. }
  14240. this.index += ch.length;
  14241. }
  14242. this.tokens.push({
  14243. index: start,
  14244. text: this.text.slice(start, this.index),
  14245. identifier: true
  14246. });
  14247. },
  14248. readString: function(quote) {
  14249. var start = this.index;
  14250. this.index++;
  14251. var string = '';
  14252. var rawString = quote;
  14253. var escape = false;
  14254. while (this.index < this.text.length) {
  14255. var ch = this.text.charAt(this.index);
  14256. rawString += ch;
  14257. if (escape) {
  14258. if (ch === 'u') {
  14259. var hex = this.text.substring(this.index + 1, this.index + 5);
  14260. if (!hex.match(/[\da-f]{4}/i)) {
  14261. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  14262. }
  14263. this.index += 4;
  14264. string += String.fromCharCode(parseInt(hex, 16));
  14265. } else {
  14266. var rep = ESCAPE[ch];
  14267. string = string + (rep || ch);
  14268. }
  14269. escape = false;
  14270. } else if (ch === '\\') {
  14271. escape = true;
  14272. } else if (ch === quote) {
  14273. this.index++;
  14274. this.tokens.push({
  14275. index: start,
  14276. text: rawString,
  14277. constant: true,
  14278. value: string
  14279. });
  14280. return;
  14281. } else {
  14282. string += ch;
  14283. }
  14284. this.index++;
  14285. }
  14286. this.throwError('Unterminated quote', start);
  14287. }
  14288. };
  14289. var AST = function AST(lexer, options) {
  14290. this.lexer = lexer;
  14291. this.options = options;
  14292. };
  14293. AST.Program = 'Program';
  14294. AST.ExpressionStatement = 'ExpressionStatement';
  14295. AST.AssignmentExpression = 'AssignmentExpression';
  14296. AST.ConditionalExpression = 'ConditionalExpression';
  14297. AST.LogicalExpression = 'LogicalExpression';
  14298. AST.BinaryExpression = 'BinaryExpression';
  14299. AST.UnaryExpression = 'UnaryExpression';
  14300. AST.CallExpression = 'CallExpression';
  14301. AST.MemberExpression = 'MemberExpression';
  14302. AST.Identifier = 'Identifier';
  14303. AST.Literal = 'Literal';
  14304. AST.ArrayExpression = 'ArrayExpression';
  14305. AST.Property = 'Property';
  14306. AST.ObjectExpression = 'ObjectExpression';
  14307. AST.ThisExpression = 'ThisExpression';
  14308. AST.LocalsExpression = 'LocalsExpression';
  14309. // Internal use only
  14310. AST.NGValueParameter = 'NGValueParameter';
  14311. AST.prototype = {
  14312. ast: function(text) {
  14313. this.text = text;
  14314. this.tokens = this.lexer.lex(text);
  14315. var value = this.program();
  14316. if (this.tokens.length !== 0) {
  14317. this.throwError('is an unexpected token', this.tokens[0]);
  14318. }
  14319. return value;
  14320. },
  14321. program: function() {
  14322. var body = [];
  14323. while (true) {
  14324. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  14325. body.push(this.expressionStatement());
  14326. if (!this.expect(';')) {
  14327. return { type: AST.Program, body: body};
  14328. }
  14329. }
  14330. },
  14331. expressionStatement: function() {
  14332. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  14333. },
  14334. filterChain: function() {
  14335. var left = this.expression();
  14336. while (this.expect('|')) {
  14337. left = this.filter(left);
  14338. }
  14339. return left;
  14340. },
  14341. expression: function() {
  14342. return this.assignment();
  14343. },
  14344. assignment: function() {
  14345. var result = this.ternary();
  14346. if (this.expect('=')) {
  14347. if (!isAssignable(result)) {
  14348. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  14349. }
  14350. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  14351. }
  14352. return result;
  14353. },
  14354. ternary: function() {
  14355. var test = this.logicalOR();
  14356. var alternate;
  14357. var consequent;
  14358. if (this.expect('?')) {
  14359. alternate = this.expression();
  14360. if (this.consume(':')) {
  14361. consequent = this.expression();
  14362. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  14363. }
  14364. }
  14365. return test;
  14366. },
  14367. logicalOR: function() {
  14368. var left = this.logicalAND();
  14369. while (this.expect('||')) {
  14370. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  14371. }
  14372. return left;
  14373. },
  14374. logicalAND: function() {
  14375. var left = this.equality();
  14376. while (this.expect('&&')) {
  14377. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  14378. }
  14379. return left;
  14380. },
  14381. equality: function() {
  14382. var left = this.relational();
  14383. var token;
  14384. while ((token = this.expect('==','!=','===','!=='))) {
  14385. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  14386. }
  14387. return left;
  14388. },
  14389. relational: function() {
  14390. var left = this.additive();
  14391. var token;
  14392. while ((token = this.expect('<', '>', '<=', '>='))) {
  14393. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  14394. }
  14395. return left;
  14396. },
  14397. additive: function() {
  14398. var left = this.multiplicative();
  14399. var token;
  14400. while ((token = this.expect('+','-'))) {
  14401. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  14402. }
  14403. return left;
  14404. },
  14405. multiplicative: function() {
  14406. var left = this.unary();
  14407. var token;
  14408. while ((token = this.expect('*','/','%'))) {
  14409. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  14410. }
  14411. return left;
  14412. },
  14413. unary: function() {
  14414. var token;
  14415. if ((token = this.expect('+', '-', '!'))) {
  14416. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  14417. } else {
  14418. return this.primary();
  14419. }
  14420. },
  14421. primary: function() {
  14422. var primary;
  14423. if (this.expect('(')) {
  14424. primary = this.filterChain();
  14425. this.consume(')');
  14426. } else if (this.expect('[')) {
  14427. primary = this.arrayDeclaration();
  14428. } else if (this.expect('{')) {
  14429. primary = this.object();
  14430. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  14431. primary = copy(this.selfReferential[this.consume().text]);
  14432. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  14433. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  14434. } else if (this.peek().identifier) {
  14435. primary = this.identifier();
  14436. } else if (this.peek().constant) {
  14437. primary = this.constant();
  14438. } else {
  14439. this.throwError('not a primary expression', this.peek());
  14440. }
  14441. var next;
  14442. while ((next = this.expect('(', '[', '.'))) {
  14443. if (next.text === '(') {
  14444. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  14445. this.consume(')');
  14446. } else if (next.text === '[') {
  14447. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  14448. this.consume(']');
  14449. } else if (next.text === '.') {
  14450. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  14451. } else {
  14452. this.throwError('IMPOSSIBLE');
  14453. }
  14454. }
  14455. return primary;
  14456. },
  14457. filter: function(baseExpression) {
  14458. var args = [baseExpression];
  14459. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  14460. while (this.expect(':')) {
  14461. args.push(this.expression());
  14462. }
  14463. return result;
  14464. },
  14465. parseArguments: function() {
  14466. var args = [];
  14467. if (this.peekToken().text !== ')') {
  14468. do {
  14469. args.push(this.filterChain());
  14470. } while (this.expect(','));
  14471. }
  14472. return args;
  14473. },
  14474. identifier: function() {
  14475. var token = this.consume();
  14476. if (!token.identifier) {
  14477. this.throwError('is not a valid identifier', token);
  14478. }
  14479. return { type: AST.Identifier, name: token.text };
  14480. },
  14481. constant: function() {
  14482. // TODO check that it is a constant
  14483. return { type: AST.Literal, value: this.consume().value };
  14484. },
  14485. arrayDeclaration: function() {
  14486. var elements = [];
  14487. if (this.peekToken().text !== ']') {
  14488. do {
  14489. if (this.peek(']')) {
  14490. // Support trailing commas per ES5.1.
  14491. break;
  14492. }
  14493. elements.push(this.expression());
  14494. } while (this.expect(','));
  14495. }
  14496. this.consume(']');
  14497. return { type: AST.ArrayExpression, elements: elements };
  14498. },
  14499. object: function() {
  14500. var properties = [], property;
  14501. if (this.peekToken().text !== '}') {
  14502. do {
  14503. if (this.peek('}')) {
  14504. // Support trailing commas per ES5.1.
  14505. break;
  14506. }
  14507. property = {type: AST.Property, kind: 'init'};
  14508. if (this.peek().constant) {
  14509. property.key = this.constant();
  14510. property.computed = false;
  14511. this.consume(':');
  14512. property.value = this.expression();
  14513. } else if (this.peek().identifier) {
  14514. property.key = this.identifier();
  14515. property.computed = false;
  14516. if (this.peek(':')) {
  14517. this.consume(':');
  14518. property.value = this.expression();
  14519. } else {
  14520. property.value = property.key;
  14521. }
  14522. } else if (this.peek('[')) {
  14523. this.consume('[');
  14524. property.key = this.expression();
  14525. this.consume(']');
  14526. property.computed = true;
  14527. this.consume(':');
  14528. property.value = this.expression();
  14529. } else {
  14530. this.throwError('invalid key', this.peek());
  14531. }
  14532. properties.push(property);
  14533. } while (this.expect(','));
  14534. }
  14535. this.consume('}');
  14536. return {type: AST.ObjectExpression, properties: properties };
  14537. },
  14538. throwError: function(msg, token) {
  14539. throw $parseMinErr('syntax',
  14540. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  14541. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  14542. },
  14543. consume: function(e1) {
  14544. if (this.tokens.length === 0) {
  14545. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  14546. }
  14547. var token = this.expect(e1);
  14548. if (!token) {
  14549. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  14550. }
  14551. return token;
  14552. },
  14553. peekToken: function() {
  14554. if (this.tokens.length === 0) {
  14555. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  14556. }
  14557. return this.tokens[0];
  14558. },
  14559. peek: function(e1, e2, e3, e4) {
  14560. return this.peekAhead(0, e1, e2, e3, e4);
  14561. },
  14562. peekAhead: function(i, e1, e2, e3, e4) {
  14563. if (this.tokens.length > i) {
  14564. var token = this.tokens[i];
  14565. var t = token.text;
  14566. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  14567. (!e1 && !e2 && !e3 && !e4)) {
  14568. return token;
  14569. }
  14570. }
  14571. return false;
  14572. },
  14573. expect: function(e1, e2, e3, e4) {
  14574. var token = this.peek(e1, e2, e3, e4);
  14575. if (token) {
  14576. this.tokens.shift();
  14577. return token;
  14578. }
  14579. return false;
  14580. },
  14581. selfReferential: {
  14582. 'this': {type: AST.ThisExpression },
  14583. '$locals': {type: AST.LocalsExpression }
  14584. }
  14585. };
  14586. function ifDefined(v, d) {
  14587. return typeof v !== 'undefined' ? v : d;
  14588. }
  14589. function plusFn(l, r) {
  14590. if (typeof l === 'undefined') return r;
  14591. if (typeof r === 'undefined') return l;
  14592. return l + r;
  14593. }
  14594. function isStateless($filter, filterName) {
  14595. var fn = $filter(filterName);
  14596. return !fn.$stateful;
  14597. }
  14598. var PURITY_ABSOLUTE = 1;
  14599. var PURITY_RELATIVE = 2;
  14600. // Detect nodes which could depend on non-shallow state of objects
  14601. function isPure(node, parentIsPure) {
  14602. switch (node.type) {
  14603. // Computed members might invoke a stateful toString()
  14604. case AST.MemberExpression:
  14605. if (node.computed) {
  14606. return false;
  14607. }
  14608. break;
  14609. // Unary always convert to primative
  14610. case AST.UnaryExpression:
  14611. return PURITY_ABSOLUTE;
  14612. // The binary + operator can invoke a stateful toString().
  14613. case AST.BinaryExpression:
  14614. return node.operator !== '+' ? PURITY_ABSOLUTE : false;
  14615. // Functions / filters probably read state from within objects
  14616. case AST.CallExpression:
  14617. return false;
  14618. }
  14619. return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure;
  14620. }
  14621. function findConstantAndWatchExpressions(ast, $filter, parentIsPure) {
  14622. var allConstants;
  14623. var argsToWatch;
  14624. var isStatelessFilter;
  14625. var astIsPure = ast.isPure = isPure(ast, parentIsPure);
  14626. switch (ast.type) {
  14627. case AST.Program:
  14628. allConstants = true;
  14629. forEach(ast.body, function(expr) {
  14630. findConstantAndWatchExpressions(expr.expression, $filter, astIsPure);
  14631. allConstants = allConstants && expr.expression.constant;
  14632. });
  14633. ast.constant = allConstants;
  14634. break;
  14635. case AST.Literal:
  14636. ast.constant = true;
  14637. ast.toWatch = [];
  14638. break;
  14639. case AST.UnaryExpression:
  14640. findConstantAndWatchExpressions(ast.argument, $filter, astIsPure);
  14641. ast.constant = ast.argument.constant;
  14642. ast.toWatch = ast.argument.toWatch;
  14643. break;
  14644. case AST.BinaryExpression:
  14645. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  14646. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  14647. ast.constant = ast.left.constant && ast.right.constant;
  14648. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  14649. break;
  14650. case AST.LogicalExpression:
  14651. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  14652. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  14653. ast.constant = ast.left.constant && ast.right.constant;
  14654. ast.toWatch = ast.constant ? [] : [ast];
  14655. break;
  14656. case AST.ConditionalExpression:
  14657. findConstantAndWatchExpressions(ast.test, $filter, astIsPure);
  14658. findConstantAndWatchExpressions(ast.alternate, $filter, astIsPure);
  14659. findConstantAndWatchExpressions(ast.consequent, $filter, astIsPure);
  14660. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  14661. ast.toWatch = ast.constant ? [] : [ast];
  14662. break;
  14663. case AST.Identifier:
  14664. ast.constant = false;
  14665. ast.toWatch = [ast];
  14666. break;
  14667. case AST.MemberExpression:
  14668. findConstantAndWatchExpressions(ast.object, $filter, astIsPure);
  14669. if (ast.computed) {
  14670. findConstantAndWatchExpressions(ast.property, $filter, astIsPure);
  14671. }
  14672. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  14673. ast.toWatch = ast.constant ? [] : [ast];
  14674. break;
  14675. case AST.CallExpression:
  14676. isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
  14677. allConstants = isStatelessFilter;
  14678. argsToWatch = [];
  14679. forEach(ast.arguments, function(expr) {
  14680. findConstantAndWatchExpressions(expr, $filter, astIsPure);
  14681. allConstants = allConstants && expr.constant;
  14682. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  14683. });
  14684. ast.constant = allConstants;
  14685. ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
  14686. break;
  14687. case AST.AssignmentExpression:
  14688. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  14689. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  14690. ast.constant = ast.left.constant && ast.right.constant;
  14691. ast.toWatch = [ast];
  14692. break;
  14693. case AST.ArrayExpression:
  14694. allConstants = true;
  14695. argsToWatch = [];
  14696. forEach(ast.elements, function(expr) {
  14697. findConstantAndWatchExpressions(expr, $filter, astIsPure);
  14698. allConstants = allConstants && expr.constant;
  14699. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  14700. });
  14701. ast.constant = allConstants;
  14702. ast.toWatch = argsToWatch;
  14703. break;
  14704. case AST.ObjectExpression:
  14705. allConstants = true;
  14706. argsToWatch = [];
  14707. forEach(ast.properties, function(property) {
  14708. findConstantAndWatchExpressions(property.value, $filter, astIsPure);
  14709. allConstants = allConstants && property.value.constant;
  14710. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  14711. if (property.computed) {
  14712. //`{[key]: value}` implicitly does `key.toString()` which may be non-pure
  14713. findConstantAndWatchExpressions(property.key, $filter, /*parentIsPure=*/false);
  14714. allConstants = allConstants && property.key.constant;
  14715. argsToWatch.push.apply(argsToWatch, property.key.toWatch);
  14716. }
  14717. });
  14718. ast.constant = allConstants;
  14719. ast.toWatch = argsToWatch;
  14720. break;
  14721. case AST.ThisExpression:
  14722. ast.constant = false;
  14723. ast.toWatch = [];
  14724. break;
  14725. case AST.LocalsExpression:
  14726. ast.constant = false;
  14727. ast.toWatch = [];
  14728. break;
  14729. }
  14730. }
  14731. function getInputs(body) {
  14732. if (body.length !== 1) return;
  14733. var lastExpression = body[0].expression;
  14734. var candidate = lastExpression.toWatch;
  14735. if (candidate.length !== 1) return candidate;
  14736. return candidate[0] !== lastExpression ? candidate : undefined;
  14737. }
  14738. function isAssignable(ast) {
  14739. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  14740. }
  14741. function assignableAST(ast) {
  14742. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  14743. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  14744. }
  14745. }
  14746. function isLiteral(ast) {
  14747. return ast.body.length === 0 ||
  14748. ast.body.length === 1 && (
  14749. ast.body[0].expression.type === AST.Literal ||
  14750. ast.body[0].expression.type === AST.ArrayExpression ||
  14751. ast.body[0].expression.type === AST.ObjectExpression);
  14752. }
  14753. function isConstant(ast) {
  14754. return ast.constant;
  14755. }
  14756. function ASTCompiler($filter) {
  14757. this.$filter = $filter;
  14758. }
  14759. ASTCompiler.prototype = {
  14760. compile: function(ast) {
  14761. var self = this;
  14762. this.state = {
  14763. nextId: 0,
  14764. filters: {},
  14765. fn: {vars: [], body: [], own: {}},
  14766. assign: {vars: [], body: [], own: {}},
  14767. inputs: []
  14768. };
  14769. findConstantAndWatchExpressions(ast, self.$filter);
  14770. var extra = '';
  14771. var assignable;
  14772. this.stage = 'assign';
  14773. if ((assignable = assignableAST(ast))) {
  14774. this.state.computing = 'assign';
  14775. var result = this.nextId();
  14776. this.recurse(assignable, result);
  14777. this.return_(result);
  14778. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  14779. }
  14780. var toWatch = getInputs(ast.body);
  14781. self.stage = 'inputs';
  14782. forEach(toWatch, function(watch, key) {
  14783. var fnKey = 'fn' + key;
  14784. self.state[fnKey] = {vars: [], body: [], own: {}};
  14785. self.state.computing = fnKey;
  14786. var intoId = self.nextId();
  14787. self.recurse(watch, intoId);
  14788. self.return_(intoId);
  14789. self.state.inputs.push({name: fnKey, isPure: watch.isPure});
  14790. watch.watchId = key;
  14791. });
  14792. this.state.computing = 'fn';
  14793. this.stage = 'main';
  14794. this.recurse(ast);
  14795. var fnString =
  14796. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  14797. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  14798. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  14799. this.filterPrefix() +
  14800. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  14801. extra +
  14802. this.watchFns() +
  14803. 'return fn;';
  14804. // eslint-disable-next-line no-new-func
  14805. var fn = (new Function('$filter',
  14806. 'getStringValue',
  14807. 'ifDefined',
  14808. 'plus',
  14809. fnString))(
  14810. this.$filter,
  14811. getStringValue,
  14812. ifDefined,
  14813. plusFn);
  14814. this.state = this.stage = undefined;
  14815. return fn;
  14816. },
  14817. USE: 'use',
  14818. STRICT: 'strict',
  14819. watchFns: function() {
  14820. var result = [];
  14821. var inputs = this.state.inputs;
  14822. var self = this;
  14823. forEach(inputs, function(input) {
  14824. result.push('var ' + input.name + '=' + self.generateFunction(input.name, 's'));
  14825. if (input.isPure) {
  14826. result.push(input.name, '.isPure=' + JSON.stringify(input.isPure) + ';');
  14827. }
  14828. });
  14829. if (inputs.length) {
  14830. result.push('fn.inputs=[' + inputs.map(function(i) { return i.name; }).join(',') + '];');
  14831. }
  14832. return result.join('');
  14833. },
  14834. generateFunction: function(name, params) {
  14835. return 'function(' + params + '){' +
  14836. this.varsPrefix(name) +
  14837. this.body(name) +
  14838. '};';
  14839. },
  14840. filterPrefix: function() {
  14841. var parts = [];
  14842. var self = this;
  14843. forEach(this.state.filters, function(id, filter) {
  14844. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  14845. });
  14846. if (parts.length) return 'var ' + parts.join(',') + ';';
  14847. return '';
  14848. },
  14849. varsPrefix: function(section) {
  14850. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  14851. },
  14852. body: function(section) {
  14853. return this.state[section].body.join('');
  14854. },
  14855. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14856. var left, right, self = this, args, expression, computed;
  14857. recursionFn = recursionFn || noop;
  14858. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  14859. intoId = intoId || this.nextId();
  14860. this.if_('i',
  14861. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  14862. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  14863. );
  14864. return;
  14865. }
  14866. switch (ast.type) {
  14867. case AST.Program:
  14868. forEach(ast.body, function(expression, pos) {
  14869. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  14870. if (pos !== ast.body.length - 1) {
  14871. self.current().body.push(right, ';');
  14872. } else {
  14873. self.return_(right);
  14874. }
  14875. });
  14876. break;
  14877. case AST.Literal:
  14878. expression = this.escape(ast.value);
  14879. this.assign(intoId, expression);
  14880. recursionFn(intoId || expression);
  14881. break;
  14882. case AST.UnaryExpression:
  14883. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  14884. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  14885. this.assign(intoId, expression);
  14886. recursionFn(expression);
  14887. break;
  14888. case AST.BinaryExpression:
  14889. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  14890. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  14891. if (ast.operator === '+') {
  14892. expression = this.plus(left, right);
  14893. } else if (ast.operator === '-') {
  14894. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  14895. } else {
  14896. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  14897. }
  14898. this.assign(intoId, expression);
  14899. recursionFn(expression);
  14900. break;
  14901. case AST.LogicalExpression:
  14902. intoId = intoId || this.nextId();
  14903. self.recurse(ast.left, intoId);
  14904. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  14905. recursionFn(intoId);
  14906. break;
  14907. case AST.ConditionalExpression:
  14908. intoId = intoId || this.nextId();
  14909. self.recurse(ast.test, intoId);
  14910. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  14911. recursionFn(intoId);
  14912. break;
  14913. case AST.Identifier:
  14914. intoId = intoId || this.nextId();
  14915. if (nameId) {
  14916. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  14917. nameId.computed = false;
  14918. nameId.name = ast.name;
  14919. }
  14920. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  14921. function() {
  14922. self.if_(self.stage === 'inputs' || 's', function() {
  14923. if (create && create !== 1) {
  14924. self.if_(
  14925. self.isNull(self.nonComputedMember('s', ast.name)),
  14926. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  14927. }
  14928. self.assign(intoId, self.nonComputedMember('s', ast.name));
  14929. });
  14930. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  14931. );
  14932. recursionFn(intoId);
  14933. break;
  14934. case AST.MemberExpression:
  14935. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  14936. intoId = intoId || this.nextId();
  14937. self.recurse(ast.object, left, undefined, function() {
  14938. self.if_(self.notNull(left), function() {
  14939. if (ast.computed) {
  14940. right = self.nextId();
  14941. self.recurse(ast.property, right);
  14942. self.getStringValue(right);
  14943. if (create && create !== 1) {
  14944. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  14945. }
  14946. expression = self.computedMember(left, right);
  14947. self.assign(intoId, expression);
  14948. if (nameId) {
  14949. nameId.computed = true;
  14950. nameId.name = right;
  14951. }
  14952. } else {
  14953. if (create && create !== 1) {
  14954. self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  14955. }
  14956. expression = self.nonComputedMember(left, ast.property.name);
  14957. self.assign(intoId, expression);
  14958. if (nameId) {
  14959. nameId.computed = false;
  14960. nameId.name = ast.property.name;
  14961. }
  14962. }
  14963. }, function() {
  14964. self.assign(intoId, 'undefined');
  14965. });
  14966. recursionFn(intoId);
  14967. }, !!create);
  14968. break;
  14969. case AST.CallExpression:
  14970. intoId = intoId || this.nextId();
  14971. if (ast.filter) {
  14972. right = self.filter(ast.callee.name);
  14973. args = [];
  14974. forEach(ast.arguments, function(expr) {
  14975. var argument = self.nextId();
  14976. self.recurse(expr, argument);
  14977. args.push(argument);
  14978. });
  14979. expression = right + '(' + args.join(',') + ')';
  14980. self.assign(intoId, expression);
  14981. recursionFn(intoId);
  14982. } else {
  14983. right = self.nextId();
  14984. left = {};
  14985. args = [];
  14986. self.recurse(ast.callee, right, left, function() {
  14987. self.if_(self.notNull(right), function() {
  14988. forEach(ast.arguments, function(expr) {
  14989. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  14990. args.push(argument);
  14991. });
  14992. });
  14993. if (left.name) {
  14994. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  14995. } else {
  14996. expression = right + '(' + args.join(',') + ')';
  14997. }
  14998. self.assign(intoId, expression);
  14999. }, function() {
  15000. self.assign(intoId, 'undefined');
  15001. });
  15002. recursionFn(intoId);
  15003. });
  15004. }
  15005. break;
  15006. case AST.AssignmentExpression:
  15007. right = this.nextId();
  15008. left = {};
  15009. this.recurse(ast.left, undefined, left, function() {
  15010. self.if_(self.notNull(left.context), function() {
  15011. self.recurse(ast.right, right);
  15012. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  15013. self.assign(intoId, expression);
  15014. recursionFn(intoId || expression);
  15015. });
  15016. }, 1);
  15017. break;
  15018. case AST.ArrayExpression:
  15019. args = [];
  15020. forEach(ast.elements, function(expr) {
  15021. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  15022. args.push(argument);
  15023. });
  15024. });
  15025. expression = '[' + args.join(',') + ']';
  15026. this.assign(intoId, expression);
  15027. recursionFn(intoId || expression);
  15028. break;
  15029. case AST.ObjectExpression:
  15030. args = [];
  15031. computed = false;
  15032. forEach(ast.properties, function(property) {
  15033. if (property.computed) {
  15034. computed = true;
  15035. }
  15036. });
  15037. if (computed) {
  15038. intoId = intoId || this.nextId();
  15039. this.assign(intoId, '{}');
  15040. forEach(ast.properties, function(property) {
  15041. if (property.computed) {
  15042. left = self.nextId();
  15043. self.recurse(property.key, left);
  15044. } else {
  15045. left = property.key.type === AST.Identifier ?
  15046. property.key.name :
  15047. ('' + property.key.value);
  15048. }
  15049. right = self.nextId();
  15050. self.recurse(property.value, right);
  15051. self.assign(self.member(intoId, left, property.computed), right);
  15052. });
  15053. } else {
  15054. forEach(ast.properties, function(property) {
  15055. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  15056. args.push(self.escape(
  15057. property.key.type === AST.Identifier ? property.key.name :
  15058. ('' + property.key.value)) +
  15059. ':' + expr);
  15060. });
  15061. });
  15062. expression = '{' + args.join(',') + '}';
  15063. this.assign(intoId, expression);
  15064. }
  15065. recursionFn(intoId || expression);
  15066. break;
  15067. case AST.ThisExpression:
  15068. this.assign(intoId, 's');
  15069. recursionFn(intoId || 's');
  15070. break;
  15071. case AST.LocalsExpression:
  15072. this.assign(intoId, 'l');
  15073. recursionFn(intoId || 'l');
  15074. break;
  15075. case AST.NGValueParameter:
  15076. this.assign(intoId, 'v');
  15077. recursionFn(intoId || 'v');
  15078. break;
  15079. }
  15080. },
  15081. getHasOwnProperty: function(element, property) {
  15082. var key = element + '.' + property;
  15083. var own = this.current().own;
  15084. if (!own.hasOwnProperty(key)) {
  15085. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  15086. }
  15087. return own[key];
  15088. },
  15089. assign: function(id, value) {
  15090. if (!id) return;
  15091. this.current().body.push(id, '=', value, ';');
  15092. return id;
  15093. },
  15094. filter: function(filterName) {
  15095. if (!this.state.filters.hasOwnProperty(filterName)) {
  15096. this.state.filters[filterName] = this.nextId(true);
  15097. }
  15098. return this.state.filters[filterName];
  15099. },
  15100. ifDefined: function(id, defaultValue) {
  15101. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  15102. },
  15103. plus: function(left, right) {
  15104. return 'plus(' + left + ',' + right + ')';
  15105. },
  15106. return_: function(id) {
  15107. this.current().body.push('return ', id, ';');
  15108. },
  15109. if_: function(test, alternate, consequent) {
  15110. if (test === true) {
  15111. alternate();
  15112. } else {
  15113. var body = this.current().body;
  15114. body.push('if(', test, '){');
  15115. alternate();
  15116. body.push('}');
  15117. if (consequent) {
  15118. body.push('else{');
  15119. consequent();
  15120. body.push('}');
  15121. }
  15122. }
  15123. },
  15124. not: function(expression) {
  15125. return '!(' + expression + ')';
  15126. },
  15127. isNull: function(expression) {
  15128. return expression + '==null';
  15129. },
  15130. notNull: function(expression) {
  15131. return expression + '!=null';
  15132. },
  15133. nonComputedMember: function(left, right) {
  15134. var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
  15135. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  15136. if (SAFE_IDENTIFIER.test(right)) {
  15137. return left + '.' + right;
  15138. } else {
  15139. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  15140. }
  15141. },
  15142. computedMember: function(left, right) {
  15143. return left + '[' + right + ']';
  15144. },
  15145. member: function(left, right, computed) {
  15146. if (computed) return this.computedMember(left, right);
  15147. return this.nonComputedMember(left, right);
  15148. },
  15149. getStringValue: function(item) {
  15150. this.assign(item, 'getStringValue(' + item + ')');
  15151. },
  15152. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  15153. var self = this;
  15154. return function() {
  15155. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  15156. };
  15157. },
  15158. lazyAssign: function(id, value) {
  15159. var self = this;
  15160. return function() {
  15161. self.assign(id, value);
  15162. };
  15163. },
  15164. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  15165. stringEscapeFn: function(c) {
  15166. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  15167. },
  15168. escape: function(value) {
  15169. if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
  15170. if (isNumber(value)) return value.toString();
  15171. if (value === true) return 'true';
  15172. if (value === false) return 'false';
  15173. if (value === null) return 'null';
  15174. if (typeof value === 'undefined') return 'undefined';
  15175. throw $parseMinErr('esc', 'IMPOSSIBLE');
  15176. },
  15177. nextId: function(skip, init) {
  15178. var id = 'v' + (this.state.nextId++);
  15179. if (!skip) {
  15180. this.current().vars.push(id + (init ? '=' + init : ''));
  15181. }
  15182. return id;
  15183. },
  15184. current: function() {
  15185. return this.state[this.state.computing];
  15186. }
  15187. };
  15188. function ASTInterpreter($filter) {
  15189. this.$filter = $filter;
  15190. }
  15191. ASTInterpreter.prototype = {
  15192. compile: function(ast) {
  15193. var self = this;
  15194. findConstantAndWatchExpressions(ast, self.$filter);
  15195. var assignable;
  15196. var assign;
  15197. if ((assignable = assignableAST(ast))) {
  15198. assign = this.recurse(assignable);
  15199. }
  15200. var toWatch = getInputs(ast.body);
  15201. var inputs;
  15202. if (toWatch) {
  15203. inputs = [];
  15204. forEach(toWatch, function(watch, key) {
  15205. var input = self.recurse(watch);
  15206. input.isPure = watch.isPure;
  15207. watch.input = input;
  15208. inputs.push(input);
  15209. watch.watchId = key;
  15210. });
  15211. }
  15212. var expressions = [];
  15213. forEach(ast.body, function(expression) {
  15214. expressions.push(self.recurse(expression.expression));
  15215. });
  15216. var fn = ast.body.length === 0 ? noop :
  15217. ast.body.length === 1 ? expressions[0] :
  15218. function(scope, locals) {
  15219. var lastValue;
  15220. forEach(expressions, function(exp) {
  15221. lastValue = exp(scope, locals);
  15222. });
  15223. return lastValue;
  15224. };
  15225. if (assign) {
  15226. fn.assign = function(scope, value, locals) {
  15227. return assign(scope, locals, value);
  15228. };
  15229. }
  15230. if (inputs) {
  15231. fn.inputs = inputs;
  15232. }
  15233. return fn;
  15234. },
  15235. recurse: function(ast, context, create) {
  15236. var left, right, self = this, args;
  15237. if (ast.input) {
  15238. return this.inputs(ast.input, ast.watchId);
  15239. }
  15240. switch (ast.type) {
  15241. case AST.Literal:
  15242. return this.value(ast.value, context);
  15243. case AST.UnaryExpression:
  15244. right = this.recurse(ast.argument);
  15245. return this['unary' + ast.operator](right, context);
  15246. case AST.BinaryExpression:
  15247. left = this.recurse(ast.left);
  15248. right = this.recurse(ast.right);
  15249. return this['binary' + ast.operator](left, right, context);
  15250. case AST.LogicalExpression:
  15251. left = this.recurse(ast.left);
  15252. right = this.recurse(ast.right);
  15253. return this['binary' + ast.operator](left, right, context);
  15254. case AST.ConditionalExpression:
  15255. return this['ternary?:'](
  15256. this.recurse(ast.test),
  15257. this.recurse(ast.alternate),
  15258. this.recurse(ast.consequent),
  15259. context
  15260. );
  15261. case AST.Identifier:
  15262. return self.identifier(ast.name, context, create);
  15263. case AST.MemberExpression:
  15264. left = this.recurse(ast.object, false, !!create);
  15265. if (!ast.computed) {
  15266. right = ast.property.name;
  15267. }
  15268. if (ast.computed) right = this.recurse(ast.property);
  15269. return ast.computed ?
  15270. this.computedMember(left, right, context, create) :
  15271. this.nonComputedMember(left, right, context, create);
  15272. case AST.CallExpression:
  15273. args = [];
  15274. forEach(ast.arguments, function(expr) {
  15275. args.push(self.recurse(expr));
  15276. });
  15277. if (ast.filter) right = this.$filter(ast.callee.name);
  15278. if (!ast.filter) right = this.recurse(ast.callee, true);
  15279. return ast.filter ?
  15280. function(scope, locals, assign, inputs) {
  15281. var values = [];
  15282. for (var i = 0; i < args.length; ++i) {
  15283. values.push(args[i](scope, locals, assign, inputs));
  15284. }
  15285. var value = right.apply(undefined, values, inputs);
  15286. return context ? {context: undefined, name: undefined, value: value} : value;
  15287. } :
  15288. function(scope, locals, assign, inputs) {
  15289. var rhs = right(scope, locals, assign, inputs);
  15290. var value;
  15291. if (rhs.value != null) {
  15292. var values = [];
  15293. for (var i = 0; i < args.length; ++i) {
  15294. values.push(args[i](scope, locals, assign, inputs));
  15295. }
  15296. value = rhs.value.apply(rhs.context, values);
  15297. }
  15298. return context ? {value: value} : value;
  15299. };
  15300. case AST.AssignmentExpression:
  15301. left = this.recurse(ast.left, true, 1);
  15302. right = this.recurse(ast.right);
  15303. return function(scope, locals, assign, inputs) {
  15304. var lhs = left(scope, locals, assign, inputs);
  15305. var rhs = right(scope, locals, assign, inputs);
  15306. lhs.context[lhs.name] = rhs;
  15307. return context ? {value: rhs} : rhs;
  15308. };
  15309. case AST.ArrayExpression:
  15310. args = [];
  15311. forEach(ast.elements, function(expr) {
  15312. args.push(self.recurse(expr));
  15313. });
  15314. return function(scope, locals, assign, inputs) {
  15315. var value = [];
  15316. for (var i = 0; i < args.length; ++i) {
  15317. value.push(args[i](scope, locals, assign, inputs));
  15318. }
  15319. return context ? {value: value} : value;
  15320. };
  15321. case AST.ObjectExpression:
  15322. args = [];
  15323. forEach(ast.properties, function(property) {
  15324. if (property.computed) {
  15325. args.push({key: self.recurse(property.key),
  15326. computed: true,
  15327. value: self.recurse(property.value)
  15328. });
  15329. } else {
  15330. args.push({key: property.key.type === AST.Identifier ?
  15331. property.key.name :
  15332. ('' + property.key.value),
  15333. computed: false,
  15334. value: self.recurse(property.value)
  15335. });
  15336. }
  15337. });
  15338. return function(scope, locals, assign, inputs) {
  15339. var value = {};
  15340. for (var i = 0; i < args.length; ++i) {
  15341. if (args[i].computed) {
  15342. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  15343. } else {
  15344. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  15345. }
  15346. }
  15347. return context ? {value: value} : value;
  15348. };
  15349. case AST.ThisExpression:
  15350. return function(scope) {
  15351. return context ? {value: scope} : scope;
  15352. };
  15353. case AST.LocalsExpression:
  15354. return function(scope, locals) {
  15355. return context ? {value: locals} : locals;
  15356. };
  15357. case AST.NGValueParameter:
  15358. return function(scope, locals, assign) {
  15359. return context ? {value: assign} : assign;
  15360. };
  15361. }
  15362. },
  15363. 'unary+': function(argument, context) {
  15364. return function(scope, locals, assign, inputs) {
  15365. var arg = argument(scope, locals, assign, inputs);
  15366. if (isDefined(arg)) {
  15367. arg = +arg;
  15368. } else {
  15369. arg = 0;
  15370. }
  15371. return context ? {value: arg} : arg;
  15372. };
  15373. },
  15374. 'unary-': function(argument, context) {
  15375. return function(scope, locals, assign, inputs) {
  15376. var arg = argument(scope, locals, assign, inputs);
  15377. if (isDefined(arg)) {
  15378. arg = -arg;
  15379. } else {
  15380. arg = -0;
  15381. }
  15382. return context ? {value: arg} : arg;
  15383. };
  15384. },
  15385. 'unary!': function(argument, context) {
  15386. return function(scope, locals, assign, inputs) {
  15387. var arg = !argument(scope, locals, assign, inputs);
  15388. return context ? {value: arg} : arg;
  15389. };
  15390. },
  15391. 'binary+': function(left, right, context) {
  15392. return function(scope, locals, assign, inputs) {
  15393. var lhs = left(scope, locals, assign, inputs);
  15394. var rhs = right(scope, locals, assign, inputs);
  15395. var arg = plusFn(lhs, rhs);
  15396. return context ? {value: arg} : arg;
  15397. };
  15398. },
  15399. 'binary-': function(left, right, context) {
  15400. return function(scope, locals, assign, inputs) {
  15401. var lhs = left(scope, locals, assign, inputs);
  15402. var rhs = right(scope, locals, assign, inputs);
  15403. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  15404. return context ? {value: arg} : arg;
  15405. };
  15406. },
  15407. 'binary*': function(left, right, context) {
  15408. return function(scope, locals, assign, inputs) {
  15409. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  15410. return context ? {value: arg} : arg;
  15411. };
  15412. },
  15413. 'binary/': function(left, right, context) {
  15414. return function(scope, locals, assign, inputs) {
  15415. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  15416. return context ? {value: arg} : arg;
  15417. };
  15418. },
  15419. 'binary%': function(left, right, context) {
  15420. return function(scope, locals, assign, inputs) {
  15421. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  15422. return context ? {value: arg} : arg;
  15423. };
  15424. },
  15425. 'binary===': function(left, right, context) {
  15426. return function(scope, locals, assign, inputs) {
  15427. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  15428. return context ? {value: arg} : arg;
  15429. };
  15430. },
  15431. 'binary!==': function(left, right, context) {
  15432. return function(scope, locals, assign, inputs) {
  15433. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  15434. return context ? {value: arg} : arg;
  15435. };
  15436. },
  15437. 'binary==': function(left, right, context) {
  15438. return function(scope, locals, assign, inputs) {
  15439. // eslint-disable-next-line eqeqeq
  15440. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  15441. return context ? {value: arg} : arg;
  15442. };
  15443. },
  15444. 'binary!=': function(left, right, context) {
  15445. return function(scope, locals, assign, inputs) {
  15446. // eslint-disable-next-line eqeqeq
  15447. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  15448. return context ? {value: arg} : arg;
  15449. };
  15450. },
  15451. 'binary<': function(left, right, context) {
  15452. return function(scope, locals, assign, inputs) {
  15453. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  15454. return context ? {value: arg} : arg;
  15455. };
  15456. },
  15457. 'binary>': function(left, right, context) {
  15458. return function(scope, locals, assign, inputs) {
  15459. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  15460. return context ? {value: arg} : arg;
  15461. };
  15462. },
  15463. 'binary<=': function(left, right, context) {
  15464. return function(scope, locals, assign, inputs) {
  15465. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  15466. return context ? {value: arg} : arg;
  15467. };
  15468. },
  15469. 'binary>=': function(left, right, context) {
  15470. return function(scope, locals, assign, inputs) {
  15471. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  15472. return context ? {value: arg} : arg;
  15473. };
  15474. },
  15475. 'binary&&': function(left, right, context) {
  15476. return function(scope, locals, assign, inputs) {
  15477. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  15478. return context ? {value: arg} : arg;
  15479. };
  15480. },
  15481. 'binary||': function(left, right, context) {
  15482. return function(scope, locals, assign, inputs) {
  15483. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  15484. return context ? {value: arg} : arg;
  15485. };
  15486. },
  15487. 'ternary?:': function(test, alternate, consequent, context) {
  15488. return function(scope, locals, assign, inputs) {
  15489. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  15490. return context ? {value: arg} : arg;
  15491. };
  15492. },
  15493. value: function(value, context) {
  15494. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  15495. },
  15496. identifier: function(name, context, create) {
  15497. return function(scope, locals, assign, inputs) {
  15498. var base = locals && (name in locals) ? locals : scope;
  15499. if (create && create !== 1 && base && base[name] == null) {
  15500. base[name] = {};
  15501. }
  15502. var value = base ? base[name] : undefined;
  15503. if (context) {
  15504. return {context: base, name: name, value: value};
  15505. } else {
  15506. return value;
  15507. }
  15508. };
  15509. },
  15510. computedMember: function(left, right, context, create) {
  15511. return function(scope, locals, assign, inputs) {
  15512. var lhs = left(scope, locals, assign, inputs);
  15513. var rhs;
  15514. var value;
  15515. if (lhs != null) {
  15516. rhs = right(scope, locals, assign, inputs);
  15517. rhs = getStringValue(rhs);
  15518. if (create && create !== 1) {
  15519. if (lhs && !(lhs[rhs])) {
  15520. lhs[rhs] = {};
  15521. }
  15522. }
  15523. value = lhs[rhs];
  15524. }
  15525. if (context) {
  15526. return {context: lhs, name: rhs, value: value};
  15527. } else {
  15528. return value;
  15529. }
  15530. };
  15531. },
  15532. nonComputedMember: function(left, right, context, create) {
  15533. return function(scope, locals, assign, inputs) {
  15534. var lhs = left(scope, locals, assign, inputs);
  15535. if (create && create !== 1) {
  15536. if (lhs && lhs[right] == null) {
  15537. lhs[right] = {};
  15538. }
  15539. }
  15540. var value = lhs != null ? lhs[right] : undefined;
  15541. if (context) {
  15542. return {context: lhs, name: right, value: value};
  15543. } else {
  15544. return value;
  15545. }
  15546. };
  15547. },
  15548. inputs: function(input, watchId) {
  15549. return function(scope, value, locals, inputs) {
  15550. if (inputs) return inputs[watchId];
  15551. return input(scope, value, locals);
  15552. };
  15553. }
  15554. };
  15555. /**
  15556. * @constructor
  15557. */
  15558. function Parser(lexer, $filter, options) {
  15559. this.ast = new AST(lexer, options);
  15560. this.astCompiler = options.csp ? new ASTInterpreter($filter) :
  15561. new ASTCompiler($filter);
  15562. }
  15563. Parser.prototype = {
  15564. constructor: Parser,
  15565. parse: function(text) {
  15566. var ast = this.getAst(text);
  15567. var fn = this.astCompiler.compile(ast.ast);
  15568. fn.literal = isLiteral(ast.ast);
  15569. fn.constant = isConstant(ast.ast);
  15570. fn.oneTime = ast.oneTime;
  15571. return fn;
  15572. },
  15573. getAst: function(exp) {
  15574. var oneTime = false;
  15575. exp = exp.trim();
  15576. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  15577. oneTime = true;
  15578. exp = exp.substring(2);
  15579. }
  15580. return {
  15581. ast: this.ast.ast(exp),
  15582. oneTime: oneTime
  15583. };
  15584. }
  15585. };
  15586. function getValueOf(value) {
  15587. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  15588. }
  15589. ///////////////////////////////////
  15590. /**
  15591. * @ngdoc service
  15592. * @name $parse
  15593. * @kind function
  15594. *
  15595. * @description
  15596. *
  15597. * Converts AngularJS {@link guide/expression expression} into a function.
  15598. *
  15599. * ```js
  15600. * var getter = $parse('user.name');
  15601. * var setter = getter.assign;
  15602. * var context = {user:{name:'AngularJS'}};
  15603. * var locals = {user:{name:'local'}};
  15604. *
  15605. * expect(getter(context)).toEqual('AngularJS');
  15606. * setter(context, 'newValue');
  15607. * expect(context.user.name).toEqual('newValue');
  15608. * expect(getter(context, locals)).toEqual('local');
  15609. * ```
  15610. *
  15611. *
  15612. * @param {string} expression String expression to compile.
  15613. * @returns {function(context, locals)} a function which represents the compiled expression:
  15614. *
  15615. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15616. * are evaluated against (typically a scope object).
  15617. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15618. * `context`.
  15619. *
  15620. * The returned function also has the following properties:
  15621. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  15622. * literal.
  15623. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  15624. * constant literals.
  15625. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  15626. * set to a function to change its value on the given context.
  15627. *
  15628. */
  15629. /**
  15630. * @ngdoc provider
  15631. * @name $parseProvider
  15632. * @this
  15633. *
  15634. * @description
  15635. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  15636. * service.
  15637. */
  15638. function $ParseProvider() {
  15639. var cache = createMap();
  15640. var literals = {
  15641. 'true': true,
  15642. 'false': false,
  15643. 'null': null,
  15644. 'undefined': undefined
  15645. };
  15646. var identStart, identContinue;
  15647. /**
  15648. * @ngdoc method
  15649. * @name $parseProvider#addLiteral
  15650. * @description
  15651. *
  15652. * Configure $parse service to add literal values that will be present as literal at expressions.
  15653. *
  15654. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  15655. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  15656. *
  15657. **/
  15658. this.addLiteral = function(literalName, literalValue) {
  15659. literals[literalName] = literalValue;
  15660. };
  15661. /**
  15662. * @ngdoc method
  15663. * @name $parseProvider#setIdentifierFns
  15664. *
  15665. * @description
  15666. *
  15667. * Allows defining the set of characters that are allowed in AngularJS expressions. The function
  15668. * `identifierStart` will get called to know if a given character is a valid character to be the
  15669. * first character for an identifier. The function `identifierContinue` will get called to know if
  15670. * a given character is a valid character to be a follow-up identifier character. The functions
  15671. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  15672. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  15673. * mind that the `string` parameter can be two characters long depending on the character
  15674. * representation. It is expected for the function to return `true` or `false`, whether that
  15675. * character is allowed or not.
  15676. *
  15677. * Since this function will be called extensively, keep the implementation of these functions fast,
  15678. * as the performance of these functions have a direct impact on the expressions parsing speed.
  15679. *
  15680. * @param {function=} identifierStart The function that will decide whether the given character is
  15681. * a valid identifier start character.
  15682. * @param {function=} identifierContinue The function that will decide whether the given character is
  15683. * a valid identifier continue character.
  15684. */
  15685. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  15686. identStart = identifierStart;
  15687. identContinue = identifierContinue;
  15688. return this;
  15689. };
  15690. this.$get = ['$filter', function($filter) {
  15691. var noUnsafeEval = csp().noUnsafeEval;
  15692. var $parseOptions = {
  15693. csp: noUnsafeEval,
  15694. literals: copy(literals),
  15695. isIdentifierStart: isFunction(identStart) && identStart,
  15696. isIdentifierContinue: isFunction(identContinue) && identContinue
  15697. };
  15698. $parse.$$getAst = $$getAst;
  15699. return $parse;
  15700. function $parse(exp, interceptorFn) {
  15701. var parsedExpression, cacheKey;
  15702. switch (typeof exp) {
  15703. case 'string':
  15704. exp = exp.trim();
  15705. cacheKey = exp;
  15706. parsedExpression = cache[cacheKey];
  15707. if (!parsedExpression) {
  15708. var lexer = new Lexer($parseOptions);
  15709. var parser = new Parser(lexer, $filter, $parseOptions);
  15710. parsedExpression = parser.parse(exp);
  15711. cache[cacheKey] = addWatchDelegate(parsedExpression);
  15712. }
  15713. return addInterceptor(parsedExpression, interceptorFn);
  15714. case 'function':
  15715. return addInterceptor(exp, interceptorFn);
  15716. default:
  15717. return addInterceptor(noop, interceptorFn);
  15718. }
  15719. }
  15720. function $$getAst(exp) {
  15721. var lexer = new Lexer($parseOptions);
  15722. var parser = new Parser(lexer, $filter, $parseOptions);
  15723. return parser.getAst(exp).ast;
  15724. }
  15725. function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) {
  15726. if (newValue == null || oldValueOfValue == null) { // null/undefined
  15727. return newValue === oldValueOfValue;
  15728. }
  15729. if (typeof newValue === 'object') {
  15730. // attempt to convert the value to a primitive type
  15731. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  15732. // be cheaply dirty-checked
  15733. newValue = getValueOf(newValue);
  15734. if (typeof newValue === 'object' && !compareObjectIdentity) {
  15735. // objects/arrays are not supported - deep-watching them would be too expensive
  15736. return false;
  15737. }
  15738. // fall-through to the primitive equality check
  15739. }
  15740. //Primitive or NaN
  15741. // eslint-disable-next-line no-self-compare
  15742. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  15743. }
  15744. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  15745. var inputExpressions = parsedExpression.inputs;
  15746. var lastResult;
  15747. if (inputExpressions.length === 1) {
  15748. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  15749. inputExpressions = inputExpressions[0];
  15750. return scope.$watch(function expressionInputWatch(scope) {
  15751. var newInputValue = inputExpressions(scope);
  15752. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, inputExpressions.isPure)) {
  15753. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  15754. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  15755. }
  15756. return lastResult;
  15757. }, listener, objectEquality, prettyPrintExpression);
  15758. }
  15759. var oldInputValueOfValues = [];
  15760. var oldInputValues = [];
  15761. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  15762. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  15763. oldInputValues[i] = null;
  15764. }
  15765. return scope.$watch(function expressionInputsWatch(scope) {
  15766. var changed = false;
  15767. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  15768. var newInputValue = inputExpressions[i](scope);
  15769. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], inputExpressions[i].isPure))) {
  15770. oldInputValues[i] = newInputValue;
  15771. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  15772. }
  15773. }
  15774. if (changed) {
  15775. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  15776. }
  15777. return lastResult;
  15778. }, listener, objectEquality, prettyPrintExpression);
  15779. }
  15780. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  15781. var isDone = parsedExpression.literal ? isAllDefined : isDefined;
  15782. var unwatch, lastValue;
  15783. var exp = parsedExpression.$$intercepted || parsedExpression;
  15784. var post = parsedExpression.$$interceptor || identity;
  15785. var useInputs = parsedExpression.inputs && !exp.inputs;
  15786. // Propogate the literal/inputs/constant attributes
  15787. // ... but not oneTime since we are handling it
  15788. oneTimeWatch.literal = parsedExpression.literal;
  15789. oneTimeWatch.constant = parsedExpression.constant;
  15790. oneTimeWatch.inputs = parsedExpression.inputs;
  15791. // Allow other delegates to run on this wrapped expression
  15792. addWatchDelegate(oneTimeWatch);
  15793. unwatch = scope.$watch(oneTimeWatch, listener, objectEquality, prettyPrintExpression);
  15794. return unwatch;
  15795. function unwatchIfDone() {
  15796. if (isDone(lastValue)) {
  15797. unwatch();
  15798. }
  15799. }
  15800. function oneTimeWatch(scope, locals, assign, inputs) {
  15801. lastValue = useInputs && inputs ? inputs[0] : exp(scope, locals, assign, inputs);
  15802. if (isDone(lastValue)) {
  15803. scope.$$postDigest(unwatchIfDone);
  15804. }
  15805. return post(lastValue);
  15806. }
  15807. }
  15808. function isAllDefined(value) {
  15809. var allDefined = true;
  15810. forEach(value, function(val) {
  15811. if (!isDefined(val)) allDefined = false;
  15812. });
  15813. return allDefined;
  15814. }
  15815. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  15816. var unwatch = scope.$watch(function constantWatch(scope) {
  15817. unwatch();
  15818. return parsedExpression(scope);
  15819. }, listener, objectEquality);
  15820. return unwatch;
  15821. }
  15822. function addWatchDelegate(parsedExpression) {
  15823. if (parsedExpression.constant) {
  15824. parsedExpression.$$watchDelegate = constantWatchDelegate;
  15825. } else if (parsedExpression.oneTime) {
  15826. parsedExpression.$$watchDelegate = oneTimeWatchDelegate;
  15827. } else if (parsedExpression.inputs) {
  15828. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  15829. }
  15830. return parsedExpression;
  15831. }
  15832. function chainInterceptors(first, second) {
  15833. function chainedInterceptor(value) {
  15834. return second(first(value));
  15835. }
  15836. chainedInterceptor.$stateful = first.$stateful || second.$stateful;
  15837. chainedInterceptor.$$pure = first.$$pure && second.$$pure;
  15838. return chainedInterceptor;
  15839. }
  15840. function addInterceptor(parsedExpression, interceptorFn) {
  15841. if (!interceptorFn) return parsedExpression;
  15842. // Extract any existing interceptors out of the parsedExpression
  15843. // to ensure the original parsedExpression is always the $$intercepted
  15844. if (parsedExpression.$$interceptor) {
  15845. interceptorFn = chainInterceptors(parsedExpression.$$interceptor, interceptorFn);
  15846. parsedExpression = parsedExpression.$$intercepted;
  15847. }
  15848. var useInputs = false;
  15849. var fn = function interceptedExpression(scope, locals, assign, inputs) {
  15850. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  15851. return interceptorFn(value);
  15852. };
  15853. // Maintain references to the interceptor/intercepted
  15854. fn.$$intercepted = parsedExpression;
  15855. fn.$$interceptor = interceptorFn;
  15856. // Propogate the literal/oneTime/constant attributes
  15857. fn.literal = parsedExpression.literal;
  15858. fn.oneTime = parsedExpression.oneTime;
  15859. fn.constant = parsedExpression.constant;
  15860. // Treat the interceptor like filters.
  15861. // If it is not $stateful then only watch its inputs.
  15862. // If the expression itself has no inputs then use the full expression as an input.
  15863. if (!interceptorFn.$stateful) {
  15864. useInputs = !parsedExpression.inputs;
  15865. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  15866. if (!interceptorFn.$$pure) {
  15867. fn.inputs = fn.inputs.map(function(e) {
  15868. // Remove the isPure flag of inputs when it is not absolute because they are now wrapped in a
  15869. // non-pure interceptor function.
  15870. if (e.isPure === PURITY_RELATIVE) {
  15871. return function depurifier(s) { return e(s); };
  15872. }
  15873. return e;
  15874. });
  15875. }
  15876. }
  15877. return addWatchDelegate(fn);
  15878. }
  15879. }];
  15880. }
  15881. /**
  15882. * @ngdoc service
  15883. * @name $q
  15884. * @requires $rootScope
  15885. *
  15886. * @description
  15887. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  15888. * when they are done processing.
  15889. *
  15890. * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred
  15891. * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  15892. *
  15893. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  15894. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  15895. *
  15896. * ## $q constructor
  15897. *
  15898. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  15899. * function as the first argument. This is similar to the native Promise implementation from ES6,
  15900. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  15901. *
  15902. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  15903. * available yet.
  15904. *
  15905. * It can be used like so:
  15906. *
  15907. * ```js
  15908. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  15909. * // are available in the current lexical scope (they could have been injected or passed in).
  15910. *
  15911. * function asyncGreet(name) {
  15912. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  15913. * return $q(function(resolve, reject) {
  15914. * setTimeout(function() {
  15915. * if (okToGreet(name)) {
  15916. * resolve('Hello, ' + name + '!');
  15917. * } else {
  15918. * reject('Greeting ' + name + ' is not allowed.');
  15919. * }
  15920. * }, 1000);
  15921. * });
  15922. * }
  15923. *
  15924. * var promise = asyncGreet('Robin Hood');
  15925. * promise.then(function(greeting) {
  15926. * alert('Success: ' + greeting);
  15927. * }, function(reason) {
  15928. * alert('Failed: ' + reason);
  15929. * });
  15930. * ```
  15931. *
  15932. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  15933. *
  15934. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  15935. *
  15936. * However, the more traditional CommonJS-style usage is still available, and documented below.
  15937. *
  15938. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  15939. * interface for interacting with an object that represents the result of an action that is
  15940. * performed asynchronously, and may or may not be finished at any given point in time.
  15941. *
  15942. * From the perspective of dealing with error handling, deferred and promise APIs are to
  15943. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  15944. *
  15945. * ```js
  15946. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  15947. * // are available in the current lexical scope (they could have been injected or passed in).
  15948. *
  15949. * function asyncGreet(name) {
  15950. * var deferred = $q.defer();
  15951. *
  15952. * setTimeout(function() {
  15953. * deferred.notify('About to greet ' + name + '.');
  15954. *
  15955. * if (okToGreet(name)) {
  15956. * deferred.resolve('Hello, ' + name + '!');
  15957. * } else {
  15958. * deferred.reject('Greeting ' + name + ' is not allowed.');
  15959. * }
  15960. * }, 1000);
  15961. *
  15962. * return deferred.promise;
  15963. * }
  15964. *
  15965. * var promise = asyncGreet('Robin Hood');
  15966. * promise.then(function(greeting) {
  15967. * alert('Success: ' + greeting);
  15968. * }, function(reason) {
  15969. * alert('Failed: ' + reason);
  15970. * }, function(update) {
  15971. * alert('Got notification: ' + update);
  15972. * });
  15973. * ```
  15974. *
  15975. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  15976. * comes in the way of guarantees that promise and deferred APIs make, see
  15977. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  15978. *
  15979. * Additionally the promise api allows for composition that is very hard to do with the
  15980. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  15981. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  15982. * section on serial or parallel joining of promises.
  15983. *
  15984. * ## The Deferred API
  15985. *
  15986. * A new instance of deferred is constructed by calling `$q.defer()`.
  15987. *
  15988. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  15989. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  15990. * of the task.
  15991. *
  15992. * **Methods**
  15993. *
  15994. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  15995. * constructed via `$q.reject`, the promise will be rejected instead.
  15996. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  15997. * resolving it with a rejection constructed via `$q.reject`.
  15998. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  15999. * multiple times before the promise is either resolved or rejected.
  16000. *
  16001. * **Properties**
  16002. *
  16003. * - promise – `{Promise}` – promise object associated with this deferred.
  16004. *
  16005. *
  16006. * ## The Promise API
  16007. *
  16008. * A new promise instance is created when a deferred instance is created and can be retrieved by
  16009. * calling `deferred.promise`.
  16010. *
  16011. * The purpose of the promise object is to allow for interested parties to get access to the result
  16012. * of the deferred task when it completes.
  16013. *
  16014. * **Methods**
  16015. *
  16016. * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
  16017. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  16018. * as soon as the result is available. The callbacks are called with a single argument: the result
  16019. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  16020. * provide a progress indication, before the promise is resolved or rejected.
  16021. *
  16022. * This method *returns a new promise* which is resolved or rejected via the return value of the
  16023. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  16024. * with the value which is resolved in that promise using
  16025. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  16026. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  16027. * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
  16028. * arguments are optional.
  16029. *
  16030. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  16031. *
  16032. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  16033. * but to do so without modifying the final value. This is useful to release resources or do some
  16034. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  16035. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  16036. * more information.
  16037. *
  16038. * ## Chaining promises
  16039. *
  16040. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  16041. * possible to create a chain of promises:
  16042. *
  16043. * ```js
  16044. * promiseB = promiseA.then(function(result) {
  16045. * return result + 1;
  16046. * });
  16047. *
  16048. * // promiseB will be resolved immediately after promiseA is resolved and its value
  16049. * // will be the result of promiseA incremented by 1
  16050. * ```
  16051. *
  16052. * It is possible to create chains of any length and since a promise can be resolved with another
  16053. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  16054. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  16055. * $http's response interceptors.
  16056. *
  16057. *
  16058. * ## Differences between Kris Kowal's Q and $q
  16059. *
  16060. * There are two main differences:
  16061. *
  16062. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  16063. * mechanism in AngularJS, which means faster propagation of resolution or rejection into your
  16064. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  16065. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  16066. * all the important functionality needed for common async tasks.
  16067. *
  16068. * ## Testing
  16069. *
  16070. * ```js
  16071. * it('should simulate promise', inject(function($q, $rootScope) {
  16072. * var deferred = $q.defer();
  16073. * var promise = deferred.promise;
  16074. * var resolvedValue;
  16075. *
  16076. * promise.then(function(value) { resolvedValue = value; });
  16077. * expect(resolvedValue).toBeUndefined();
  16078. *
  16079. * // Simulate resolving of promise
  16080. * deferred.resolve(123);
  16081. * // Note that the 'then' function does not get called synchronously.
  16082. * // This is because we want the promise API to always be async, whether or not
  16083. * // it got called synchronously or asynchronously.
  16084. * expect(resolvedValue).toBeUndefined();
  16085. *
  16086. * // Propagate promise resolution to 'then' functions using $apply().
  16087. * $rootScope.$apply();
  16088. * expect(resolvedValue).toEqual(123);
  16089. * }));
  16090. * ```
  16091. *
  16092. * @param {function(function, function)} resolver Function which is responsible for resolving or
  16093. * rejecting the newly created promise. The first parameter is a function which resolves the
  16094. * promise, the second parameter is a function which rejects the promise.
  16095. *
  16096. * @returns {Promise} The newly created promise.
  16097. */
  16098. /**
  16099. * @ngdoc provider
  16100. * @name $qProvider
  16101. * @this
  16102. *
  16103. * @description
  16104. */
  16105. function $QProvider() {
  16106. var errorOnUnhandledRejections = true;
  16107. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  16108. return qFactory(function(callback) {
  16109. $rootScope.$evalAsync(callback);
  16110. }, $exceptionHandler, errorOnUnhandledRejections);
  16111. }];
  16112. /**
  16113. * @ngdoc method
  16114. * @name $qProvider#errorOnUnhandledRejections
  16115. * @kind function
  16116. *
  16117. * @description
  16118. * Retrieves or overrides whether to generate an error when a rejected promise is not handled.
  16119. * This feature is enabled by default.
  16120. *
  16121. * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.
  16122. * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for
  16123. * chaining otherwise.
  16124. */
  16125. this.errorOnUnhandledRejections = function(value) {
  16126. if (isDefined(value)) {
  16127. errorOnUnhandledRejections = value;
  16128. return this;
  16129. } else {
  16130. return errorOnUnhandledRejections;
  16131. }
  16132. };
  16133. }
  16134. /** @this */
  16135. function $$QProvider() {
  16136. var errorOnUnhandledRejections = true;
  16137. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  16138. return qFactory(function(callback) {
  16139. $browser.defer(callback);
  16140. }, $exceptionHandler, errorOnUnhandledRejections);
  16141. }];
  16142. this.errorOnUnhandledRejections = function(value) {
  16143. if (isDefined(value)) {
  16144. errorOnUnhandledRejections = value;
  16145. return this;
  16146. } else {
  16147. return errorOnUnhandledRejections;
  16148. }
  16149. };
  16150. }
  16151. /**
  16152. * Constructs a promise manager.
  16153. *
  16154. * @param {function(function)} nextTick Function for executing functions in the next turn.
  16155. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  16156. * debugging purposes.
  16157. * @param {boolean=} errorOnUnhandledRejections Whether an error should be generated on unhandled
  16158. * promises rejections.
  16159. * @returns {object} Promise manager.
  16160. */
  16161. function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {
  16162. var $qMinErr = minErr('$q', TypeError);
  16163. var queueSize = 0;
  16164. var checkQueue = [];
  16165. /**
  16166. * @ngdoc method
  16167. * @name ng.$q#defer
  16168. * @kind function
  16169. *
  16170. * @description
  16171. * Creates a `Deferred` object which represents a task which will finish in the future.
  16172. *
  16173. * @returns {Deferred} Returns a new instance of deferred.
  16174. */
  16175. function defer() {
  16176. return new Deferred();
  16177. }
  16178. function Deferred() {
  16179. var promise = this.promise = new Promise();
  16180. //Non prototype methods necessary to support unbound execution :/
  16181. this.resolve = function(val) { resolvePromise(promise, val); };
  16182. this.reject = function(reason) { rejectPromise(promise, reason); };
  16183. this.notify = function(progress) { notifyPromise(promise, progress); };
  16184. }
  16185. function Promise() {
  16186. this.$$state = { status: 0 };
  16187. }
  16188. extend(Promise.prototype, {
  16189. then: function(onFulfilled, onRejected, progressBack) {
  16190. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  16191. return this;
  16192. }
  16193. var result = new Promise();
  16194. this.$$state.pending = this.$$state.pending || [];
  16195. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  16196. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  16197. return result;
  16198. },
  16199. 'catch': function(callback) {
  16200. return this.then(null, callback);
  16201. },
  16202. 'finally': function(callback, progressBack) {
  16203. return this.then(function(value) {
  16204. return handleCallback(value, resolve, callback);
  16205. }, function(error) {
  16206. return handleCallback(error, reject, callback);
  16207. }, progressBack);
  16208. }
  16209. });
  16210. function processQueue(state) {
  16211. var fn, promise, pending;
  16212. pending = state.pending;
  16213. state.processScheduled = false;
  16214. state.pending = undefined;
  16215. try {
  16216. for (var i = 0, ii = pending.length; i < ii; ++i) {
  16217. markQStateExceptionHandled(state);
  16218. promise = pending[i][0];
  16219. fn = pending[i][state.status];
  16220. try {
  16221. if (isFunction(fn)) {
  16222. resolvePromise(promise, fn(state.value));
  16223. } else if (state.status === 1) {
  16224. resolvePromise(promise, state.value);
  16225. } else {
  16226. rejectPromise(promise, state.value);
  16227. }
  16228. } catch (e) {
  16229. rejectPromise(promise, e);
  16230. // This error is explicitly marked for being passed to the $exceptionHandler
  16231. if (e && e.$$passToExceptionHandler === true) {
  16232. exceptionHandler(e);
  16233. }
  16234. }
  16235. }
  16236. } finally {
  16237. --queueSize;
  16238. if (errorOnUnhandledRejections && queueSize === 0) {
  16239. nextTick(processChecks);
  16240. }
  16241. }
  16242. }
  16243. function processChecks() {
  16244. // eslint-disable-next-line no-unmodified-loop-condition
  16245. while (!queueSize && checkQueue.length) {
  16246. var toCheck = checkQueue.shift();
  16247. if (!isStateExceptionHandled(toCheck)) {
  16248. markQStateExceptionHandled(toCheck);
  16249. var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);
  16250. if (isError(toCheck.value)) {
  16251. exceptionHandler(toCheck.value, errorMessage);
  16252. } else {
  16253. exceptionHandler(errorMessage);
  16254. }
  16255. }
  16256. }
  16257. }
  16258. function scheduleProcessQueue(state) {
  16259. if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !isStateExceptionHandled(state)) {
  16260. if (queueSize === 0 && checkQueue.length === 0) {
  16261. nextTick(processChecks);
  16262. }
  16263. checkQueue.push(state);
  16264. }
  16265. if (state.processScheduled || !state.pending) return;
  16266. state.processScheduled = true;
  16267. ++queueSize;
  16268. nextTick(function() { processQueue(state); });
  16269. }
  16270. function resolvePromise(promise, val) {
  16271. if (promise.$$state.status) return;
  16272. if (val === promise) {
  16273. $$reject(promise, $qMinErr(
  16274. 'qcycle',
  16275. 'Expected promise to be resolved with value other than itself \'{0}\'',
  16276. val));
  16277. } else {
  16278. $$resolve(promise, val);
  16279. }
  16280. }
  16281. function $$resolve(promise, val) {
  16282. var then;
  16283. var done = false;
  16284. try {
  16285. if (isObject(val) || isFunction(val)) then = val.then;
  16286. if (isFunction(then)) {
  16287. promise.$$state.status = -1;
  16288. then.call(val, doResolve, doReject, doNotify);
  16289. } else {
  16290. promise.$$state.value = val;
  16291. promise.$$state.status = 1;
  16292. scheduleProcessQueue(promise.$$state);
  16293. }
  16294. } catch (e) {
  16295. doReject(e);
  16296. }
  16297. function doResolve(val) {
  16298. if (done) return;
  16299. done = true;
  16300. $$resolve(promise, val);
  16301. }
  16302. function doReject(val) {
  16303. if (done) return;
  16304. done = true;
  16305. $$reject(promise, val);
  16306. }
  16307. function doNotify(progress) {
  16308. notifyPromise(promise, progress);
  16309. }
  16310. }
  16311. function rejectPromise(promise, reason) {
  16312. if (promise.$$state.status) return;
  16313. $$reject(promise, reason);
  16314. }
  16315. function $$reject(promise, reason) {
  16316. promise.$$state.value = reason;
  16317. promise.$$state.status = 2;
  16318. scheduleProcessQueue(promise.$$state);
  16319. }
  16320. function notifyPromise(promise, progress) {
  16321. var callbacks = promise.$$state.pending;
  16322. if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {
  16323. nextTick(function() {
  16324. var callback, result;
  16325. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  16326. result = callbacks[i][0];
  16327. callback = callbacks[i][3];
  16328. try {
  16329. notifyPromise(result, isFunction(callback) ? callback(progress) : progress);
  16330. } catch (e) {
  16331. exceptionHandler(e);
  16332. }
  16333. }
  16334. });
  16335. }
  16336. }
  16337. /**
  16338. * @ngdoc method
  16339. * @name $q#reject
  16340. * @kind function
  16341. *
  16342. * @description
  16343. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  16344. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  16345. * a promise chain, you don't need to worry about it.
  16346. *
  16347. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  16348. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  16349. * a promise error callback and you want to forward the error to the promise derived from the
  16350. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  16351. * `reject`.
  16352. *
  16353. * ```js
  16354. * promiseB = promiseA.then(function(result) {
  16355. * // success: do something and resolve promiseB
  16356. * // with the old or a new result
  16357. * return result;
  16358. * }, function(reason) {
  16359. * // error: handle the error if possible and
  16360. * // resolve promiseB with newPromiseOrValue,
  16361. * // otherwise forward the rejection to promiseB
  16362. * if (canHandle(reason)) {
  16363. * // handle the error and recover
  16364. * return newPromiseOrValue;
  16365. * }
  16366. * return $q.reject(reason);
  16367. * });
  16368. * ```
  16369. *
  16370. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  16371. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  16372. */
  16373. function reject(reason) {
  16374. var result = new Promise();
  16375. rejectPromise(result, reason);
  16376. return result;
  16377. }
  16378. function handleCallback(value, resolver, callback) {
  16379. var callbackOutput = null;
  16380. try {
  16381. if (isFunction(callback)) callbackOutput = callback();
  16382. } catch (e) {
  16383. return reject(e);
  16384. }
  16385. if (isPromiseLike(callbackOutput)) {
  16386. return callbackOutput.then(function() {
  16387. return resolver(value);
  16388. }, reject);
  16389. } else {
  16390. return resolver(value);
  16391. }
  16392. }
  16393. /**
  16394. * @ngdoc method
  16395. * @name $q#when
  16396. * @kind function
  16397. *
  16398. * @description
  16399. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  16400. * This is useful when you are dealing with an object that might or might not be a promise, or if
  16401. * the promise comes from a source that can't be trusted.
  16402. *
  16403. * @param {*} value Value or a promise
  16404. * @param {Function=} successCallback
  16405. * @param {Function=} errorCallback
  16406. * @param {Function=} progressCallback
  16407. * @returns {Promise} Returns a promise of the passed value or promise
  16408. */
  16409. function when(value, callback, errback, progressBack) {
  16410. var result = new Promise();
  16411. resolvePromise(result, value);
  16412. return result.then(callback, errback, progressBack);
  16413. }
  16414. /**
  16415. * @ngdoc method
  16416. * @name $q#resolve
  16417. * @kind function
  16418. *
  16419. * @description
  16420. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  16421. *
  16422. * @param {*} value Value or a promise
  16423. * @param {Function=} successCallback
  16424. * @param {Function=} errorCallback
  16425. * @param {Function=} progressCallback
  16426. * @returns {Promise} Returns a promise of the passed value or promise
  16427. */
  16428. var resolve = when;
  16429. /**
  16430. * @ngdoc method
  16431. * @name $q#all
  16432. * @kind function
  16433. *
  16434. * @description
  16435. * Combines multiple promises into a single promise that is resolved when all of the input
  16436. * promises are resolved.
  16437. *
  16438. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  16439. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  16440. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  16441. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  16442. * with the same rejection value.
  16443. */
  16444. function all(promises) {
  16445. var result = new Promise(),
  16446. counter = 0,
  16447. results = isArray(promises) ? [] : {};
  16448. forEach(promises, function(promise, key) {
  16449. counter++;
  16450. when(promise).then(function(value) {
  16451. results[key] = value;
  16452. if (!(--counter)) resolvePromise(result, results);
  16453. }, function(reason) {
  16454. rejectPromise(result, reason);
  16455. });
  16456. });
  16457. if (counter === 0) {
  16458. resolvePromise(result, results);
  16459. }
  16460. return result;
  16461. }
  16462. /**
  16463. * @ngdoc method
  16464. * @name $q#race
  16465. * @kind function
  16466. *
  16467. * @description
  16468. * Returns a promise that resolves or rejects as soon as one of those promises
  16469. * resolves or rejects, with the value or reason from that promise.
  16470. *
  16471. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  16472. * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
  16473. * resolves or rejects, with the value or reason from that promise.
  16474. */
  16475. function race(promises) {
  16476. var deferred = defer();
  16477. forEach(promises, function(promise) {
  16478. when(promise).then(deferred.resolve, deferred.reject);
  16479. });
  16480. return deferred.promise;
  16481. }
  16482. function $Q(resolver) {
  16483. if (!isFunction(resolver)) {
  16484. throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
  16485. }
  16486. var promise = new Promise();
  16487. function resolveFn(value) {
  16488. resolvePromise(promise, value);
  16489. }
  16490. function rejectFn(reason) {
  16491. rejectPromise(promise, reason);
  16492. }
  16493. resolver(resolveFn, rejectFn);
  16494. return promise;
  16495. }
  16496. // Let's make the instanceof operator work for promises, so that
  16497. // `new $q(fn) instanceof $q` would evaluate to true.
  16498. $Q.prototype = Promise.prototype;
  16499. $Q.defer = defer;
  16500. $Q.reject = reject;
  16501. $Q.when = when;
  16502. $Q.resolve = resolve;
  16503. $Q.all = all;
  16504. $Q.race = race;
  16505. return $Q;
  16506. }
  16507. function isStateExceptionHandled(state) {
  16508. return !!state.pur;
  16509. }
  16510. function markQStateExceptionHandled(state) {
  16511. state.pur = true;
  16512. }
  16513. function markQExceptionHandled(q) {
  16514. markQStateExceptionHandled(q.$$state);
  16515. }
  16516. /** @this */
  16517. function $$RAFProvider() { //rAF
  16518. this.$get = ['$window', '$timeout', function($window, $timeout) {
  16519. var requestAnimationFrame = $window.requestAnimationFrame ||
  16520. $window.webkitRequestAnimationFrame;
  16521. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  16522. $window.webkitCancelAnimationFrame ||
  16523. $window.webkitCancelRequestAnimationFrame;
  16524. var rafSupported = !!requestAnimationFrame;
  16525. var raf = rafSupported
  16526. ? function(fn) {
  16527. var id = requestAnimationFrame(fn);
  16528. return function() {
  16529. cancelAnimationFrame(id);
  16530. };
  16531. }
  16532. : function(fn) {
  16533. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  16534. return function() {
  16535. $timeout.cancel(timer);
  16536. };
  16537. };
  16538. raf.supported = rafSupported;
  16539. return raf;
  16540. }];
  16541. }
  16542. /**
  16543. * DESIGN NOTES
  16544. *
  16545. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  16546. *
  16547. * The typical use of scope is to watch the expressions, which most of the time return the same
  16548. * value as last time so we optimize the operation.
  16549. *
  16550. * Closures construction is expensive in terms of speed as well as memory:
  16551. * - No closures, instead use prototypical inheritance for API
  16552. * - Internal state needs to be stored on scope directly, which means that private state is
  16553. * exposed as $$____ properties
  16554. *
  16555. * Loop operations are optimized by using while(count--) { ... }
  16556. * - This means that in order to keep the same order of execution as addition we have to add
  16557. * items to the array at the beginning (unshift) instead of at the end (push)
  16558. *
  16559. * Child scopes are created and removed often
  16560. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  16561. *
  16562. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  16563. * in the same way as watch. Watch requires return of the initialization function which is expensive
  16564. * to construct.
  16565. */
  16566. /**
  16567. * @ngdoc provider
  16568. * @name $rootScopeProvider
  16569. * @description
  16570. *
  16571. * Provider for the $rootScope service.
  16572. */
  16573. /**
  16574. * @ngdoc method
  16575. * @name $rootScopeProvider#digestTtl
  16576. * @description
  16577. *
  16578. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  16579. * assuming that the model is unstable.
  16580. *
  16581. * The current default is 10 iterations.
  16582. *
  16583. * In complex applications it's possible that the dependencies between `$watch`s will result in
  16584. * several digest iterations. However if an application needs more than the default 10 digest
  16585. * iterations for its model to stabilize then you should investigate what is causing the model to
  16586. * continuously change during the digest.
  16587. *
  16588. * Increasing the TTL could have performance implications, so you should not change it without
  16589. * proper justification.
  16590. *
  16591. * @param {number} limit The number of digest iterations.
  16592. */
  16593. /**
  16594. * @ngdoc service
  16595. * @name $rootScope
  16596. * @this
  16597. *
  16598. * @description
  16599. *
  16600. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  16601. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  16602. * between the model and the view, via a mechanism for watching the model for changes.
  16603. * They also provide event emission/broadcast and subscription facility. See the
  16604. * {@link guide/scope developer guide on scopes}.
  16605. */
  16606. function $RootScopeProvider() {
  16607. var TTL = 10;
  16608. var $rootScopeMinErr = minErr('$rootScope');
  16609. var lastDirtyWatch = null;
  16610. var applyAsyncId = null;
  16611. this.digestTtl = function(value) {
  16612. if (arguments.length) {
  16613. TTL = value;
  16614. }
  16615. return TTL;
  16616. };
  16617. function createChildScopeClass(parent) {
  16618. function ChildScope() {
  16619. this.$$watchers = this.$$nextSibling =
  16620. this.$$childHead = this.$$childTail = null;
  16621. this.$$listeners = {};
  16622. this.$$listenerCount = {};
  16623. this.$$watchersCount = 0;
  16624. this.$id = nextUid();
  16625. this.$$ChildScope = null;
  16626. this.$$suspended = false;
  16627. }
  16628. ChildScope.prototype = parent;
  16629. return ChildScope;
  16630. }
  16631. this.$get = ['$exceptionHandler', '$parse', '$browser',
  16632. function($exceptionHandler, $parse, $browser) {
  16633. function destroyChildScope($event) {
  16634. $event.currentScope.$$destroyed = true;
  16635. }
  16636. function cleanUpScope($scope) {
  16637. // Support: IE 9 only
  16638. if (msie === 9) {
  16639. // There is a memory leak in IE9 if all child scopes are not disconnected
  16640. // completely when a scope is destroyed. So this code will recurse up through
  16641. // all this scopes children
  16642. //
  16643. // See issue https://github.com/angular/angular.js/issues/10706
  16644. if ($scope.$$childHead) {
  16645. cleanUpScope($scope.$$childHead);
  16646. }
  16647. if ($scope.$$nextSibling) {
  16648. cleanUpScope($scope.$$nextSibling);
  16649. }
  16650. }
  16651. // The code below works around IE9 and V8's memory leaks
  16652. //
  16653. // See:
  16654. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  16655. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  16656. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  16657. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  16658. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  16659. }
  16660. /**
  16661. * @ngdoc type
  16662. * @name $rootScope.Scope
  16663. *
  16664. * @description
  16665. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  16666. * {@link auto.$injector $injector}. Child scopes are created using the
  16667. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  16668. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  16669. * an in-depth introduction and usage examples.
  16670. *
  16671. *
  16672. * ## Inheritance
  16673. * A scope can inherit from a parent scope, as in this example:
  16674. * ```js
  16675. var parent = $rootScope;
  16676. var child = parent.$new();
  16677. parent.salutation = "Hello";
  16678. expect(child.salutation).toEqual('Hello');
  16679. child.salutation = "Welcome";
  16680. expect(child.salutation).toEqual('Welcome');
  16681. expect(parent.salutation).toEqual('Hello');
  16682. * ```
  16683. *
  16684. * When interacting with `Scope` in tests, additional helper methods are available on the
  16685. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  16686. * details.
  16687. *
  16688. *
  16689. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  16690. * provided for the current scope. Defaults to {@link ng}.
  16691. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  16692. * append/override services provided by `providers`. This is handy
  16693. * when unit-testing and having the need to override a default
  16694. * service.
  16695. * @returns {Object} Newly created scope.
  16696. *
  16697. */
  16698. function Scope() {
  16699. this.$id = nextUid();
  16700. this.$$phase = this.$parent = this.$$watchers =
  16701. this.$$nextSibling = this.$$prevSibling =
  16702. this.$$childHead = this.$$childTail = null;
  16703. this.$root = this;
  16704. this.$$destroyed = false;
  16705. this.$$suspended = false;
  16706. this.$$listeners = {};
  16707. this.$$listenerCount = {};
  16708. this.$$watchersCount = 0;
  16709. this.$$isolateBindings = null;
  16710. }
  16711. /**
  16712. * @ngdoc property
  16713. * @name $rootScope.Scope#$id
  16714. *
  16715. * @description
  16716. * Unique scope ID (monotonically increasing) useful for debugging.
  16717. */
  16718. /**
  16719. * @ngdoc property
  16720. * @name $rootScope.Scope#$parent
  16721. *
  16722. * @description
  16723. * Reference to the parent scope.
  16724. */
  16725. /**
  16726. * @ngdoc property
  16727. * @name $rootScope.Scope#$root
  16728. *
  16729. * @description
  16730. * Reference to the root scope.
  16731. */
  16732. Scope.prototype = {
  16733. constructor: Scope,
  16734. /**
  16735. * @ngdoc method
  16736. * @name $rootScope.Scope#$new
  16737. * @kind function
  16738. *
  16739. * @description
  16740. * Creates a new child {@link ng.$rootScope.Scope scope}.
  16741. *
  16742. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  16743. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  16744. *
  16745. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  16746. * desired for the scope and its child scopes to be permanently detached from the parent and
  16747. * thus stop participating in model change detection and listener notification by invoking.
  16748. *
  16749. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  16750. * parent scope. The scope is isolated, as it can not see parent scope properties.
  16751. * When creating widgets, it is useful for the widget to not accidentally read parent
  16752. * state.
  16753. *
  16754. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  16755. * of the newly created scope. Defaults to `this` scope if not provided.
  16756. * This is used when creating a transclude scope to correctly place it
  16757. * in the scope hierarchy while maintaining the correct prototypical
  16758. * inheritance.
  16759. *
  16760. * @returns {Object} The newly created child scope.
  16761. *
  16762. */
  16763. $new: function(isolate, parent) {
  16764. var child;
  16765. parent = parent || this;
  16766. if (isolate) {
  16767. child = new Scope();
  16768. child.$root = this.$root;
  16769. } else {
  16770. // Only create a child scope class if somebody asks for one,
  16771. // but cache it to allow the VM to optimize lookups.
  16772. if (!this.$$ChildScope) {
  16773. this.$$ChildScope = createChildScopeClass(this);
  16774. }
  16775. child = new this.$$ChildScope();
  16776. }
  16777. child.$parent = parent;
  16778. child.$$prevSibling = parent.$$childTail;
  16779. if (parent.$$childHead) {
  16780. parent.$$childTail.$$nextSibling = child;
  16781. parent.$$childTail = child;
  16782. } else {
  16783. parent.$$childHead = parent.$$childTail = child;
  16784. }
  16785. // When the new scope is not isolated or we inherit from `this`, and
  16786. // the parent scope is destroyed, the property `$$destroyed` is inherited
  16787. // prototypically. In all other cases, this property needs to be set
  16788. // when the parent scope is destroyed.
  16789. // The listener needs to be added after the parent is set
  16790. if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
  16791. return child;
  16792. },
  16793. /**
  16794. * @ngdoc method
  16795. * @name $rootScope.Scope#$watch
  16796. * @kind function
  16797. *
  16798. * @description
  16799. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  16800. *
  16801. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  16802. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  16803. * its value when executed multiple times with the same input because it may be executed multiple
  16804. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  16805. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
  16806. * - The `listener` is called only when the value from the current `watchExpression` and the
  16807. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  16808. * see below). Inequality is determined according to reference inequality,
  16809. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  16810. * via the `!==` Javascript operator, unless `objectEquality == true`
  16811. * (see next point)
  16812. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  16813. * according to the {@link angular.equals} function. To save the value of the object for
  16814. * later comparison, the {@link angular.copy} function is used. This therefore means that
  16815. * watching complex objects will have adverse memory and performance implications.
  16816. * - This should not be used to watch for changes in objects that are (or contain)
  16817. * [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.
  16818. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  16819. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  16820. * iteration limit is 10 to prevent an infinite loop deadlock.
  16821. *
  16822. *
  16823. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  16824. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  16825. * multiple calls to your `watchExpression` because it will execute multiple times in a
  16826. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  16827. *
  16828. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  16829. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  16830. * watcher. In rare cases, this is undesirable because the listener is called when the result
  16831. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  16832. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  16833. * listener was called due to initialization.
  16834. *
  16835. *
  16836. *
  16837. * @example
  16838. * ```js
  16839. // let's assume that scope was dependency injected as the $rootScope
  16840. var scope = $rootScope;
  16841. scope.name = 'misko';
  16842. scope.counter = 0;
  16843. expect(scope.counter).toEqual(0);
  16844. scope.$watch('name', function(newValue, oldValue) {
  16845. scope.counter = scope.counter + 1;
  16846. });
  16847. expect(scope.counter).toEqual(0);
  16848. scope.$digest();
  16849. // the listener is always called during the first $digest loop after it was registered
  16850. expect(scope.counter).toEqual(1);
  16851. scope.$digest();
  16852. // but now it will not be called unless the value changes
  16853. expect(scope.counter).toEqual(1);
  16854. scope.name = 'adam';
  16855. scope.$digest();
  16856. expect(scope.counter).toEqual(2);
  16857. // Using a function as a watchExpression
  16858. var food;
  16859. scope.foodCounter = 0;
  16860. expect(scope.foodCounter).toEqual(0);
  16861. scope.$watch(
  16862. // This function returns the value being watched. It is called for each turn of the $digest loop
  16863. function() { return food; },
  16864. // This is the change listener, called when the value returned from the above function changes
  16865. function(newValue, oldValue) {
  16866. if ( newValue !== oldValue ) {
  16867. // Only increment the counter if the value changed
  16868. scope.foodCounter = scope.foodCounter + 1;
  16869. }
  16870. }
  16871. );
  16872. // No digest has been run so the counter will be zero
  16873. expect(scope.foodCounter).toEqual(0);
  16874. // Run the digest but since food has not changed count will still be zero
  16875. scope.$digest();
  16876. expect(scope.foodCounter).toEqual(0);
  16877. // Update food and run digest. Now the counter will increment
  16878. food = 'cheeseburger';
  16879. scope.$digest();
  16880. expect(scope.foodCounter).toEqual(1);
  16881. * ```
  16882. *
  16883. *
  16884. *
  16885. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  16886. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  16887. * a call to the `listener`.
  16888. *
  16889. * - `string`: Evaluated as {@link guide/expression expression}
  16890. * - `function(scope)`: called with current `scope` as a parameter.
  16891. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  16892. * of `watchExpression` changes.
  16893. *
  16894. * - `newVal` contains the current value of the `watchExpression`
  16895. * - `oldVal` contains the previous value of the `watchExpression`
  16896. * - `scope` refers to the current scope
  16897. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  16898. * comparing for reference equality.
  16899. * @returns {function()} Returns a deregistration function for this listener.
  16900. */
  16901. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  16902. var get = $parse(watchExp);
  16903. var fn = isFunction(listener) ? listener : noop;
  16904. if (get.$$watchDelegate) {
  16905. return get.$$watchDelegate(this, fn, objectEquality, get, watchExp);
  16906. }
  16907. var scope = this,
  16908. array = scope.$$watchers,
  16909. watcher = {
  16910. fn: fn,
  16911. last: initWatchVal,
  16912. get: get,
  16913. exp: prettyPrintExpression || watchExp,
  16914. eq: !!objectEquality
  16915. };
  16916. lastDirtyWatch = null;
  16917. if (!array) {
  16918. array = scope.$$watchers = [];
  16919. array.$$digestWatchIndex = -1;
  16920. }
  16921. // we use unshift since we use a while loop in $digest for speed.
  16922. // the while loop reads in reverse order.
  16923. array.unshift(watcher);
  16924. array.$$digestWatchIndex++;
  16925. incrementWatchersCount(this, 1);
  16926. return function deregisterWatch() {
  16927. var index = arrayRemove(array, watcher);
  16928. if (index >= 0) {
  16929. incrementWatchersCount(scope, -1);
  16930. if (index < array.$$digestWatchIndex) {
  16931. array.$$digestWatchIndex--;
  16932. }
  16933. }
  16934. lastDirtyWatch = null;
  16935. };
  16936. },
  16937. /**
  16938. * @ngdoc method
  16939. * @name $rootScope.Scope#$watchGroup
  16940. * @kind function
  16941. *
  16942. * @description
  16943. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  16944. * If any one expression in the collection changes the `listener` is executed.
  16945. *
  16946. * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return
  16947. * values are examined for changes on every call to `$digest`.
  16948. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  16949. *
  16950. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  16951. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  16952. *
  16953. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  16954. * expression in `watchExpressions` changes
  16955. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  16956. * those of `watchExpression`
  16957. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  16958. * those of `watchExpression`
  16959. * The `scope` refers to the current scope.
  16960. * @returns {function()} Returns a de-registration function for all listeners.
  16961. */
  16962. $watchGroup: function(watchExpressions, listener) {
  16963. var oldValues = new Array(watchExpressions.length);
  16964. var newValues = new Array(watchExpressions.length);
  16965. var deregisterFns = [];
  16966. var self = this;
  16967. var changeReactionScheduled = false;
  16968. var firstRun = true;
  16969. if (!watchExpressions.length) {
  16970. // No expressions means we call the listener ASAP
  16971. var shouldCall = true;
  16972. self.$evalAsync(function() {
  16973. if (shouldCall) listener(newValues, newValues, self);
  16974. });
  16975. return function deregisterWatchGroup() {
  16976. shouldCall = false;
  16977. };
  16978. }
  16979. if (watchExpressions.length === 1) {
  16980. // Special case size of one
  16981. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  16982. newValues[0] = value;
  16983. oldValues[0] = oldValue;
  16984. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  16985. });
  16986. }
  16987. forEach(watchExpressions, function(expr, i) {
  16988. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value) {
  16989. newValues[i] = value;
  16990. if (!changeReactionScheduled) {
  16991. changeReactionScheduled = true;
  16992. self.$evalAsync(watchGroupAction);
  16993. }
  16994. });
  16995. deregisterFns.push(unwatchFn);
  16996. });
  16997. function watchGroupAction() {
  16998. changeReactionScheduled = false;
  16999. try {
  17000. if (firstRun) {
  17001. firstRun = false;
  17002. listener(newValues, newValues, self);
  17003. } else {
  17004. listener(newValues, oldValues, self);
  17005. }
  17006. } finally {
  17007. for (var i = 0; i < watchExpressions.length; i++) {
  17008. oldValues[i] = newValues[i];
  17009. }
  17010. }
  17011. }
  17012. return function deregisterWatchGroup() {
  17013. while (deregisterFns.length) {
  17014. deregisterFns.shift()();
  17015. }
  17016. };
  17017. },
  17018. /**
  17019. * @ngdoc method
  17020. * @name $rootScope.Scope#$watchCollection
  17021. * @kind function
  17022. *
  17023. * @description
  17024. * Shallow watches the properties of an object and fires whenever any of the properties change
  17025. * (for arrays, this implies watching the array items; for object maps, this implies watching
  17026. * the properties). If a change is detected, the `listener` callback is fired.
  17027. *
  17028. * - The `obj` collection is observed via standard $watch operation and is examined on every
  17029. * call to $digest() to see if any items have been added, removed, or moved.
  17030. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  17031. * adding, removing, and moving items belonging to an object or array.
  17032. *
  17033. *
  17034. * @example
  17035. * ```js
  17036. $scope.names = ['igor', 'matias', 'misko', 'james'];
  17037. $scope.dataCount = 4;
  17038. $scope.$watchCollection('names', function(newNames, oldNames) {
  17039. $scope.dataCount = newNames.length;
  17040. });
  17041. expect($scope.dataCount).toEqual(4);
  17042. $scope.$digest();
  17043. //still at 4 ... no changes
  17044. expect($scope.dataCount).toEqual(4);
  17045. $scope.names.pop();
  17046. $scope.$digest();
  17047. //now there's been a change
  17048. expect($scope.dataCount).toEqual(3);
  17049. * ```
  17050. *
  17051. *
  17052. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  17053. * expression value should evaluate to an object or an array which is observed on each
  17054. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  17055. * collection will trigger a call to the `listener`.
  17056. *
  17057. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  17058. * when a change is detected.
  17059. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  17060. * - The `oldCollection` object is a copy of the former collection data.
  17061. * Due to performance considerations, the`oldCollection` value is computed only if the
  17062. * `listener` function declares two or more arguments.
  17063. * - The `scope` argument refers to the current scope.
  17064. *
  17065. * @returns {function()} Returns a de-registration function for this listener. When the
  17066. * de-registration function is executed, the internal watch operation is terminated.
  17067. */
  17068. $watchCollection: function(obj, listener) {
  17069. // Mark the interceptor as
  17070. // ... $$pure when literal since the instance will change when any input changes
  17071. $watchCollectionInterceptor.$$pure = $parse(obj).literal;
  17072. // ... $stateful when non-literal since we must read the state of the collection
  17073. $watchCollectionInterceptor.$stateful = !$watchCollectionInterceptor.$$pure;
  17074. var self = this;
  17075. // the current value, updated on each dirty-check run
  17076. var newValue;
  17077. // a shallow copy of the newValue from the last dirty-check run,
  17078. // updated to match newValue during dirty-check run
  17079. var oldValue;
  17080. // a shallow copy of the newValue from when the last change happened
  17081. var veryOldValue;
  17082. // only track veryOldValue if the listener is asking for it
  17083. var trackVeryOldValue = (listener.length > 1);
  17084. var changeDetected = 0;
  17085. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  17086. var internalArray = [];
  17087. var internalObject = {};
  17088. var initRun = true;
  17089. var oldLength = 0;
  17090. function $watchCollectionInterceptor(_value) {
  17091. newValue = _value;
  17092. var newLength, key, bothNaN, newItem, oldItem;
  17093. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  17094. if (isUndefined(newValue)) return;
  17095. if (!isObject(newValue)) { // if primitive
  17096. if (oldValue !== newValue) {
  17097. oldValue = newValue;
  17098. changeDetected++;
  17099. }
  17100. } else if (isArrayLike(newValue)) {
  17101. if (oldValue !== internalArray) {
  17102. // we are transitioning from something which was not an array into array.
  17103. oldValue = internalArray;
  17104. oldLength = oldValue.length = 0;
  17105. changeDetected++;
  17106. }
  17107. newLength = newValue.length;
  17108. if (oldLength !== newLength) {
  17109. // if lengths do not match we need to trigger change notification
  17110. changeDetected++;
  17111. oldValue.length = oldLength = newLength;
  17112. }
  17113. // copy the items to oldValue and look for changes.
  17114. for (var i = 0; i < newLength; i++) {
  17115. oldItem = oldValue[i];
  17116. newItem = newValue[i];
  17117. // eslint-disable-next-line no-self-compare
  17118. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  17119. if (!bothNaN && (oldItem !== newItem)) {
  17120. changeDetected++;
  17121. oldValue[i] = newItem;
  17122. }
  17123. }
  17124. } else {
  17125. if (oldValue !== internalObject) {
  17126. // we are transitioning from something which was not an object into object.
  17127. oldValue = internalObject = {};
  17128. oldLength = 0;
  17129. changeDetected++;
  17130. }
  17131. // copy the items to oldValue and look for changes.
  17132. newLength = 0;
  17133. for (key in newValue) {
  17134. if (hasOwnProperty.call(newValue, key)) {
  17135. newLength++;
  17136. newItem = newValue[key];
  17137. oldItem = oldValue[key];
  17138. if (key in oldValue) {
  17139. // eslint-disable-next-line no-self-compare
  17140. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  17141. if (!bothNaN && (oldItem !== newItem)) {
  17142. changeDetected++;
  17143. oldValue[key] = newItem;
  17144. }
  17145. } else {
  17146. oldLength++;
  17147. oldValue[key] = newItem;
  17148. changeDetected++;
  17149. }
  17150. }
  17151. }
  17152. if (oldLength > newLength) {
  17153. // we used to have more keys, need to find them and destroy them.
  17154. changeDetected++;
  17155. for (key in oldValue) {
  17156. if (!hasOwnProperty.call(newValue, key)) {
  17157. oldLength--;
  17158. delete oldValue[key];
  17159. }
  17160. }
  17161. }
  17162. }
  17163. return changeDetected;
  17164. }
  17165. function $watchCollectionAction() {
  17166. if (initRun) {
  17167. initRun = false;
  17168. listener(newValue, newValue, self);
  17169. } else {
  17170. listener(newValue, veryOldValue, self);
  17171. }
  17172. // make a copy for the next time a collection is changed
  17173. if (trackVeryOldValue) {
  17174. if (!isObject(newValue)) {
  17175. //primitive
  17176. veryOldValue = newValue;
  17177. } else if (isArrayLike(newValue)) {
  17178. veryOldValue = new Array(newValue.length);
  17179. for (var i = 0; i < newValue.length; i++) {
  17180. veryOldValue[i] = newValue[i];
  17181. }
  17182. } else { // if object
  17183. veryOldValue = {};
  17184. for (var key in newValue) {
  17185. if (hasOwnProperty.call(newValue, key)) {
  17186. veryOldValue[key] = newValue[key];
  17187. }
  17188. }
  17189. }
  17190. }
  17191. }
  17192. return this.$watch(changeDetector, $watchCollectionAction);
  17193. },
  17194. /**
  17195. * @ngdoc method
  17196. * @name $rootScope.Scope#$digest
  17197. * @kind function
  17198. *
  17199. * @description
  17200. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  17201. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  17202. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  17203. * until no more listeners are firing. This means that it is possible to get into an infinite
  17204. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  17205. * iterations exceeds 10.
  17206. *
  17207. * Usually, you don't call `$digest()` directly in
  17208. * {@link ng.directive:ngController controllers} or in
  17209. * {@link ng.$compileProvider#directive directives}.
  17210. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  17211. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  17212. *
  17213. * If you want to be notified whenever `$digest()` is called,
  17214. * you can register a `watchExpression` function with
  17215. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  17216. *
  17217. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  17218. *
  17219. * @example
  17220. * ```js
  17221. var scope = ...;
  17222. scope.name = 'misko';
  17223. scope.counter = 0;
  17224. expect(scope.counter).toEqual(0);
  17225. scope.$watch('name', function(newValue, oldValue) {
  17226. scope.counter = scope.counter + 1;
  17227. });
  17228. expect(scope.counter).toEqual(0);
  17229. scope.$digest();
  17230. // the listener is always called during the first $digest loop after it was registered
  17231. expect(scope.counter).toEqual(1);
  17232. scope.$digest();
  17233. // but now it will not be called unless the value changes
  17234. expect(scope.counter).toEqual(1);
  17235. scope.name = 'adam';
  17236. scope.$digest();
  17237. expect(scope.counter).toEqual(2);
  17238. * ```
  17239. *
  17240. */
  17241. $digest: function() {
  17242. var watch, value, last, fn, get,
  17243. watchers,
  17244. dirty, ttl = TTL,
  17245. next, current, target = asyncQueue.length ? $rootScope : this,
  17246. watchLog = [],
  17247. logIdx, asyncTask;
  17248. beginPhase('$digest');
  17249. // Check for changes to browser url that happened in sync before the call to $digest
  17250. $browser.$$checkUrlChange();
  17251. if (this === $rootScope && applyAsyncId !== null) {
  17252. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  17253. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  17254. $browser.defer.cancel(applyAsyncId);
  17255. flushApplyAsync();
  17256. }
  17257. lastDirtyWatch = null;
  17258. do { // "while dirty" loop
  17259. dirty = false;
  17260. current = target;
  17261. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  17262. // be reentered recursively. Calling $digest from a function passed to $evalAsync would
  17263. // lead to a '$digest already in progress' error.
  17264. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  17265. try {
  17266. asyncTask = asyncQueue[asyncQueuePosition];
  17267. fn = asyncTask.fn;
  17268. fn(asyncTask.scope, asyncTask.locals);
  17269. } catch (e) {
  17270. $exceptionHandler(e);
  17271. }
  17272. lastDirtyWatch = null;
  17273. }
  17274. asyncQueue.length = 0;
  17275. traverseScopesLoop:
  17276. do { // "traverse the scopes" loop
  17277. if ((watchers = !current.$$suspended && current.$$watchers)) {
  17278. // process our watches
  17279. watchers.$$digestWatchIndex = watchers.length;
  17280. while (watchers.$$digestWatchIndex--) {
  17281. try {
  17282. watch = watchers[watchers.$$digestWatchIndex];
  17283. // Most common watches are on primitives, in which case we can short
  17284. // circuit it with === operator, only when === fails do we use .equals
  17285. if (watch) {
  17286. get = watch.get;
  17287. if ((value = get(current)) !== (last = watch.last) &&
  17288. !(watch.eq
  17289. ? equals(value, last)
  17290. : (isNumberNaN(value) && isNumberNaN(last)))) {
  17291. dirty = true;
  17292. lastDirtyWatch = watch;
  17293. watch.last = watch.eq ? copy(value, null) : value;
  17294. fn = watch.fn;
  17295. fn(value, ((last === initWatchVal) ? value : last), current);
  17296. if (ttl < 5) {
  17297. logIdx = 4 - ttl;
  17298. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  17299. watchLog[logIdx].push({
  17300. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  17301. newVal: value,
  17302. oldVal: last
  17303. });
  17304. }
  17305. } else if (watch === lastDirtyWatch) {
  17306. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  17307. // have already been tested.
  17308. dirty = false;
  17309. break traverseScopesLoop;
  17310. }
  17311. }
  17312. } catch (e) {
  17313. $exceptionHandler(e);
  17314. }
  17315. }
  17316. }
  17317. // Insanity Warning: scope depth-first traversal
  17318. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  17319. // this piece should be kept in sync with the traversal in $broadcast
  17320. // (though it differs due to having the extra check for $$suspended and does not
  17321. // check $$listenerCount)
  17322. if (!(next = ((!current.$$suspended && current.$$watchersCount && current.$$childHead) ||
  17323. (current !== target && current.$$nextSibling)))) {
  17324. while (current !== target && !(next = current.$$nextSibling)) {
  17325. current = current.$parent;
  17326. }
  17327. }
  17328. } while ((current = next));
  17329. // `break traverseScopesLoop;` takes us to here
  17330. if ((dirty || asyncQueue.length) && !(ttl--)) {
  17331. clearPhase();
  17332. throw $rootScopeMinErr('infdig',
  17333. '{0} $digest() iterations reached. Aborting!\n' +
  17334. 'Watchers fired in the last 5 iterations: {1}',
  17335. TTL, watchLog);
  17336. }
  17337. } while (dirty || asyncQueue.length);
  17338. clearPhase();
  17339. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  17340. while (postDigestQueuePosition < postDigestQueue.length) {
  17341. try {
  17342. postDigestQueue[postDigestQueuePosition++]();
  17343. } catch (e) {
  17344. $exceptionHandler(e);
  17345. }
  17346. }
  17347. postDigestQueue.length = postDigestQueuePosition = 0;
  17348. // Check for changes to browser url that happened during the $digest
  17349. // (for which no event is fired; e.g. via `history.pushState()`)
  17350. $browser.$$checkUrlChange();
  17351. },
  17352. /**
  17353. * @ngdoc method
  17354. * @name $rootScope.Scope#$suspend
  17355. * @kind function
  17356. *
  17357. * @description
  17358. * Suspend watchers of this scope subtree so that they will not be invoked during digest.
  17359. *
  17360. * This can be used to optimize your application when you know that running those watchers
  17361. * is redundant.
  17362. *
  17363. * **Warning**
  17364. *
  17365. * Suspending scopes from the digest cycle can have unwanted and difficult to debug results.
  17366. * Only use this approach if you are confident that you know what you are doing and have
  17367. * ample tests to ensure that bindings get updated as you expect.
  17368. *
  17369. * Some of the things to consider are:
  17370. *
  17371. * * Any external event on a directive/component will not trigger a digest while the hosting
  17372. * scope is suspended - even if the event handler calls `$apply()` or `$rootScope.$digest()`.
  17373. * * Transcluded content exists on a scope that inherits from outside a directive but exists
  17374. * as a child of the directive's containing scope. If the containing scope is suspended the
  17375. * transcluded scope will also be suspended, even if the scope from which the transcluded
  17376. * scope inherits is not suspended.
  17377. * * Multiple directives trying to manage the suspended status of a scope can confuse each other:
  17378. * * A call to `$suspend()` on an already suspended scope is a no-op.
  17379. * * A call to `$resume()` on a non-suspended scope is a no-op.
  17380. * * If two directives suspend a scope, then one of them resumes the scope, the scope will no
  17381. * longer be suspended. This could result in the other directive believing a scope to be
  17382. * suspended when it is not.
  17383. * * If a parent scope is suspended then all its descendants will be also excluded from future
  17384. * digests whether or not they have been suspended themselves. Note that this also applies to
  17385. * isolate child scopes.
  17386. * * Calling `$digest()` directly on a descendant of a suspended scope will still run the watchers
  17387. * for that scope and its descendants. When digesting we only check whether the current scope is
  17388. * locally suspended, rather than checking whether it has a suspended ancestor.
  17389. * * Calling `$resume()` on a scope that has a suspended ancestor will not cause the scope to be
  17390. * included in future digests until all its ancestors have been resumed.
  17391. * * Resolved promises, e.g. from explicit `$q` deferreds and `$http` calls, trigger `$apply()`
  17392. * against the `$rootScope` and so will still trigger a global digest even if the promise was
  17393. * initiated by a component that lives on a suspended scope.
  17394. */
  17395. $suspend: function() {
  17396. this.$$suspended = true;
  17397. },
  17398. /**
  17399. * @ngdoc method
  17400. * @name $rootScope.Scope#$isSuspended
  17401. * @kind function
  17402. *
  17403. * @description
  17404. * Call this method to determine if this scope has been explicitly suspended. It will not
  17405. * tell you whether an ancestor has been suspended.
  17406. * To determine if this scope will be excluded from a digest triggered at the $rootScope,
  17407. * for example, you must check all its ancestors:
  17408. *
  17409. * ```
  17410. * function isExcludedFromDigest(scope) {
  17411. * while(scope) {
  17412. * if (scope.$isSuspended()) return true;
  17413. * scope = scope.$parent;
  17414. * }
  17415. * return false;
  17416. * ```
  17417. *
  17418. * Be aware that a scope may not be included in digests if it has a suspended ancestor,
  17419. * even if `$isSuspended()` returns false.
  17420. *
  17421. * @returns true if the current scope has been suspended.
  17422. */
  17423. $isSuspended: function() {
  17424. return this.$$suspended;
  17425. },
  17426. /**
  17427. * @ngdoc method
  17428. * @name $rootScope.Scope#$resume
  17429. * @kind function
  17430. *
  17431. * @description
  17432. * Resume watchers of this scope subtree in case it was suspended.
  17433. *
  17434. * See {@link $rootScope.Scope#$suspend} for information about the dangers of using this approach.
  17435. */
  17436. $resume: function() {
  17437. this.$$suspended = false;
  17438. },
  17439. /**
  17440. * @ngdoc event
  17441. * @name $rootScope.Scope#$destroy
  17442. * @eventType broadcast on scope being destroyed
  17443. *
  17444. * @description
  17445. * Broadcasted when a scope and its children are being destroyed.
  17446. *
  17447. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  17448. * clean up DOM bindings before an element is removed from the DOM.
  17449. */
  17450. /**
  17451. * @ngdoc method
  17452. * @name $rootScope.Scope#$destroy
  17453. * @kind function
  17454. *
  17455. * @description
  17456. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  17457. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  17458. * propagate to the current scope and its children. Removal also implies that the current
  17459. * scope is eligible for garbage collection.
  17460. *
  17461. * The `$destroy()` is usually used by directives such as
  17462. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  17463. * unrolling of the loop.
  17464. *
  17465. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  17466. * Application code can register a `$destroy` event handler that will give it a chance to
  17467. * perform any necessary cleanup.
  17468. *
  17469. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  17470. * clean up DOM bindings before an element is removed from the DOM.
  17471. */
  17472. $destroy: function() {
  17473. // We can't destroy a scope that has been already destroyed.
  17474. if (this.$$destroyed) return;
  17475. var parent = this.$parent;
  17476. this.$broadcast('$destroy');
  17477. this.$$destroyed = true;
  17478. if (this === $rootScope) {
  17479. //Remove handlers attached to window when $rootScope is removed
  17480. $browser.$$applicationDestroyed();
  17481. }
  17482. incrementWatchersCount(this, -this.$$watchersCount);
  17483. for (var eventName in this.$$listenerCount) {
  17484. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  17485. }
  17486. // sever all the references to parent scopes (after this cleanup, the current scope should
  17487. // not be retained by any of our references and should be eligible for garbage collection)
  17488. if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
  17489. if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
  17490. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  17491. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  17492. // Disable listeners, watchers and apply/digest methods
  17493. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  17494. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  17495. this.$$listeners = {};
  17496. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  17497. this.$$nextSibling = null;
  17498. cleanUpScope(this);
  17499. },
  17500. /**
  17501. * @ngdoc method
  17502. * @name $rootScope.Scope#$eval
  17503. * @kind function
  17504. *
  17505. * @description
  17506. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  17507. * the expression are propagated (uncaught). This is useful when evaluating AngularJS
  17508. * expressions.
  17509. *
  17510. * @example
  17511. * ```js
  17512. var scope = ng.$rootScope.Scope();
  17513. scope.a = 1;
  17514. scope.b = 2;
  17515. expect(scope.$eval('a+b')).toEqual(3);
  17516. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  17517. * ```
  17518. *
  17519. * @param {(string|function())=} expression An AngularJS expression to be executed.
  17520. *
  17521. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  17522. * - `function(scope)`: execute the function with the current `scope` parameter.
  17523. *
  17524. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  17525. * @returns {*} The result of evaluating the expression.
  17526. */
  17527. $eval: function(expr, locals) {
  17528. return $parse(expr)(this, locals);
  17529. },
  17530. /**
  17531. * @ngdoc method
  17532. * @name $rootScope.Scope#$evalAsync
  17533. * @kind function
  17534. *
  17535. * @description
  17536. * Executes the expression on the current scope at a later point in time.
  17537. *
  17538. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  17539. * that:
  17540. *
  17541. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  17542. * rendering).
  17543. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  17544. * `expression` execution.
  17545. *
  17546. * Any exceptions from the execution of the expression are forwarded to the
  17547. * {@link ng.$exceptionHandler $exceptionHandler} service.
  17548. *
  17549. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  17550. * will be scheduled. However, it is encouraged to always call code that changes the model
  17551. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  17552. *
  17553. * @param {(string|function())=} expression An AngularJS expression to be executed.
  17554. *
  17555. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  17556. * - `function(scope)`: execute the function with the current `scope` parameter.
  17557. *
  17558. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  17559. */
  17560. $evalAsync: function(expr, locals) {
  17561. // if we are outside of an $digest loop and this is the first time we are scheduling async
  17562. // task also schedule async auto-flush
  17563. if (!$rootScope.$$phase && !asyncQueue.length) {
  17564. $browser.defer(function() {
  17565. if (asyncQueue.length) {
  17566. $rootScope.$digest();
  17567. }
  17568. }, null, '$evalAsync');
  17569. }
  17570. asyncQueue.push({scope: this, fn: $parse(expr), locals: locals});
  17571. },
  17572. $$postDigest: function(fn) {
  17573. postDigestQueue.push(fn);
  17574. },
  17575. /**
  17576. * @ngdoc method
  17577. * @name $rootScope.Scope#$apply
  17578. * @kind function
  17579. *
  17580. * @description
  17581. * `$apply()` is used to execute an expression in AngularJS from outside of the AngularJS
  17582. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  17583. * Because we are calling into the AngularJS framework we need to perform proper scope life
  17584. * cycle of {@link ng.$exceptionHandler exception handling},
  17585. * {@link ng.$rootScope.Scope#$digest executing watches}.
  17586. *
  17587. * **Life cycle: Pseudo-Code of `$apply()`**
  17588. *
  17589. * ```js
  17590. function $apply(expr) {
  17591. try {
  17592. return $eval(expr);
  17593. } catch (e) {
  17594. $exceptionHandler(e);
  17595. } finally {
  17596. $root.$digest();
  17597. }
  17598. }
  17599. * ```
  17600. *
  17601. *
  17602. * Scope's `$apply()` method transitions through the following stages:
  17603. *
  17604. * 1. The {@link guide/expression expression} is executed using the
  17605. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  17606. * 2. Any exceptions from the execution of the expression are forwarded to the
  17607. * {@link ng.$exceptionHandler $exceptionHandler} service.
  17608. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  17609. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  17610. *
  17611. *
  17612. * @param {(string|function())=} exp An AngularJS expression to be executed.
  17613. *
  17614. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  17615. * - `function(scope)`: execute the function with current `scope` parameter.
  17616. *
  17617. * @returns {*} The result of evaluating the expression.
  17618. */
  17619. $apply: function(expr) {
  17620. try {
  17621. beginPhase('$apply');
  17622. try {
  17623. return this.$eval(expr);
  17624. } finally {
  17625. clearPhase();
  17626. }
  17627. } catch (e) {
  17628. $exceptionHandler(e);
  17629. } finally {
  17630. try {
  17631. $rootScope.$digest();
  17632. } catch (e) {
  17633. $exceptionHandler(e);
  17634. // eslint-disable-next-line no-unsafe-finally
  17635. throw e;
  17636. }
  17637. }
  17638. },
  17639. /**
  17640. * @ngdoc method
  17641. * @name $rootScope.Scope#$applyAsync
  17642. * @kind function
  17643. *
  17644. * @description
  17645. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  17646. * varies across browsers, but is typically around ~10 milliseconds.
  17647. *
  17648. * This can be used to queue up multiple expressions which need to be evaluated in the same
  17649. * digest.
  17650. *
  17651. * @param {(string|function())=} exp An AngularJS expression to be executed.
  17652. *
  17653. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  17654. * - `function(scope)`: execute the function with current `scope` parameter.
  17655. */
  17656. $applyAsync: function(expr) {
  17657. var scope = this;
  17658. if (expr) {
  17659. applyAsyncQueue.push($applyAsyncExpression);
  17660. }
  17661. expr = $parse(expr);
  17662. scheduleApplyAsync();
  17663. function $applyAsyncExpression() {
  17664. scope.$eval(expr);
  17665. }
  17666. },
  17667. /**
  17668. * @ngdoc method
  17669. * @name $rootScope.Scope#$on
  17670. * @kind function
  17671. *
  17672. * @description
  17673. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  17674. * discussion of event life cycle.
  17675. *
  17676. * The event listener function format is: `function(event, args...)`. The `event` object
  17677. * passed into the listener has the following attributes:
  17678. *
  17679. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  17680. * `$broadcast`-ed.
  17681. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  17682. * event propagates through the scope hierarchy, this property is set to null.
  17683. * - `name` - `{string}`: name of the event.
  17684. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  17685. * further event propagation (available only for events that were `$emit`-ed).
  17686. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  17687. * to true.
  17688. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  17689. *
  17690. * @param {string} name Event name to listen on.
  17691. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  17692. * @returns {function()} Returns a deregistration function for this listener.
  17693. */
  17694. $on: function(name, listener) {
  17695. var namedListeners = this.$$listeners[name];
  17696. if (!namedListeners) {
  17697. this.$$listeners[name] = namedListeners = [];
  17698. }
  17699. namedListeners.push(listener);
  17700. var current = this;
  17701. do {
  17702. if (!current.$$listenerCount[name]) {
  17703. current.$$listenerCount[name] = 0;
  17704. }
  17705. current.$$listenerCount[name]++;
  17706. } while ((current = current.$parent));
  17707. var self = this;
  17708. return function() {
  17709. var indexOfListener = namedListeners.indexOf(listener);
  17710. if (indexOfListener !== -1) {
  17711. // Use delete in the hope of the browser deallocating the memory for the array entry,
  17712. // while not shifting the array indexes of other listeners.
  17713. // See issue https://github.com/angular/angular.js/issues/16135
  17714. delete namedListeners[indexOfListener];
  17715. decrementListenerCount(self, 1, name);
  17716. }
  17717. };
  17718. },
  17719. /**
  17720. * @ngdoc method
  17721. * @name $rootScope.Scope#$emit
  17722. * @kind function
  17723. *
  17724. * @description
  17725. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  17726. * registered {@link ng.$rootScope.Scope#$on} listeners.
  17727. *
  17728. * The event life cycle starts at the scope on which `$emit` was called. All
  17729. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  17730. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  17731. * registered listeners along the way. The event will stop propagating if one of the listeners
  17732. * cancels it.
  17733. *
  17734. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  17735. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  17736. *
  17737. * @param {string} name Event name to emit.
  17738. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  17739. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  17740. */
  17741. $emit: function(name, args) {
  17742. var empty = [],
  17743. namedListeners,
  17744. scope = this,
  17745. stopPropagation = false,
  17746. event = {
  17747. name: name,
  17748. targetScope: scope,
  17749. stopPropagation: function() {stopPropagation = true;},
  17750. preventDefault: function() {
  17751. event.defaultPrevented = true;
  17752. },
  17753. defaultPrevented: false
  17754. },
  17755. listenerArgs = concat([event], arguments, 1),
  17756. i, length;
  17757. do {
  17758. namedListeners = scope.$$listeners[name] || empty;
  17759. event.currentScope = scope;
  17760. for (i = 0, length = namedListeners.length; i < length; i++) {
  17761. // if listeners were deregistered, defragment the array
  17762. if (!namedListeners[i]) {
  17763. namedListeners.splice(i, 1);
  17764. i--;
  17765. length--;
  17766. continue;
  17767. }
  17768. try {
  17769. //allow all listeners attached to the current scope to run
  17770. namedListeners[i].apply(null, listenerArgs);
  17771. } catch (e) {
  17772. $exceptionHandler(e);
  17773. }
  17774. }
  17775. //if any listener on the current scope stops propagation, prevent bubbling
  17776. if (stopPropagation) {
  17777. break;
  17778. }
  17779. //traverse upwards
  17780. scope = scope.$parent;
  17781. } while (scope);
  17782. event.currentScope = null;
  17783. return event;
  17784. },
  17785. /**
  17786. * @ngdoc method
  17787. * @name $rootScope.Scope#$broadcast
  17788. * @kind function
  17789. *
  17790. * @description
  17791. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  17792. * registered {@link ng.$rootScope.Scope#$on} listeners.
  17793. *
  17794. * The event life cycle starts at the scope on which `$broadcast` was called. All
  17795. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  17796. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  17797. * scope and calls all registered listeners along the way. The event cannot be canceled.
  17798. *
  17799. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  17800. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  17801. *
  17802. * @param {string} name Event name to broadcast.
  17803. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  17804. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  17805. */
  17806. $broadcast: function(name, args) {
  17807. var target = this,
  17808. current = target,
  17809. next = target,
  17810. event = {
  17811. name: name,
  17812. targetScope: target,
  17813. preventDefault: function() {
  17814. event.defaultPrevented = true;
  17815. },
  17816. defaultPrevented: false
  17817. };
  17818. if (!target.$$listenerCount[name]) return event;
  17819. var listenerArgs = concat([event], arguments, 1),
  17820. listeners, i, length;
  17821. //down while you can, then up and next sibling or up and next sibling until back at root
  17822. while ((current = next)) {
  17823. event.currentScope = current;
  17824. listeners = current.$$listeners[name] || [];
  17825. for (i = 0, length = listeners.length; i < length; i++) {
  17826. // if listeners were deregistered, defragment the array
  17827. if (!listeners[i]) {
  17828. listeners.splice(i, 1);
  17829. i--;
  17830. length--;
  17831. continue;
  17832. }
  17833. try {
  17834. listeners[i].apply(null, listenerArgs);
  17835. } catch (e) {
  17836. $exceptionHandler(e);
  17837. }
  17838. }
  17839. // Insanity Warning: scope depth-first traversal
  17840. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  17841. // this piece should be kept in sync with the traversal in $digest
  17842. // (though it differs due to having the extra check for $$listenerCount and
  17843. // does not check $$suspended)
  17844. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  17845. (current !== target && current.$$nextSibling)))) {
  17846. while (current !== target && !(next = current.$$nextSibling)) {
  17847. current = current.$parent;
  17848. }
  17849. }
  17850. }
  17851. event.currentScope = null;
  17852. return event;
  17853. }
  17854. };
  17855. var $rootScope = new Scope();
  17856. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  17857. var asyncQueue = $rootScope.$$asyncQueue = [];
  17858. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  17859. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  17860. var postDigestQueuePosition = 0;
  17861. return $rootScope;
  17862. function beginPhase(phase) {
  17863. if ($rootScope.$$phase) {
  17864. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  17865. }
  17866. $rootScope.$$phase = phase;
  17867. }
  17868. function clearPhase() {
  17869. $rootScope.$$phase = null;
  17870. }
  17871. function incrementWatchersCount(current, count) {
  17872. do {
  17873. current.$$watchersCount += count;
  17874. } while ((current = current.$parent));
  17875. }
  17876. function decrementListenerCount(current, count, name) {
  17877. do {
  17878. current.$$listenerCount[name] -= count;
  17879. if (current.$$listenerCount[name] === 0) {
  17880. delete current.$$listenerCount[name];
  17881. }
  17882. } while ((current = current.$parent));
  17883. }
  17884. /**
  17885. * function used as an initial value for watchers.
  17886. * because it's unique we can easily tell it apart from other values
  17887. */
  17888. function initWatchVal() {}
  17889. function flushApplyAsync() {
  17890. while (applyAsyncQueue.length) {
  17891. try {
  17892. applyAsyncQueue.shift()();
  17893. } catch (e) {
  17894. $exceptionHandler(e);
  17895. }
  17896. }
  17897. applyAsyncId = null;
  17898. }
  17899. function scheduleApplyAsync() {
  17900. if (applyAsyncId === null) {
  17901. applyAsyncId = $browser.defer(function() {
  17902. $rootScope.$apply(flushApplyAsync);
  17903. }, null, '$applyAsync');
  17904. }
  17905. }
  17906. }];
  17907. }
  17908. /**
  17909. * @ngdoc service
  17910. * @name $rootElement
  17911. *
  17912. * @description
  17913. * The root element of AngularJS application. This is either the element where {@link
  17914. * ng.directive:ngApp ngApp} was declared or the element passed into
  17915. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  17916. * location where the application's {@link auto.$injector $injector} service gets
  17917. * published, and can be retrieved using `$rootElement.injector()`.
  17918. */
  17919. // the implementation is in angular.bootstrap
  17920. /**
  17921. * @this
  17922. * @description
  17923. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  17924. */
  17925. function $$SanitizeUriProvider() {
  17926. var aHrefSanitizationWhitelist = /^\s*(https?|s?ftp|mailto|tel|file):/,
  17927. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  17928. /**
  17929. * @description
  17930. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  17931. * urls during a[href] sanitization.
  17932. *
  17933. * The sanitization is a security measure aimed at prevent XSS attacks via HTML anchor links.
  17934. *
  17935. * Any url due to be assigned to an `a[href]` attribute via interpolation is marked as requiring
  17936. * the $sce.URL security context. When interpolation occurs a call is made to `$sce.trustAsUrl(url)`
  17937. * which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize the potentially malicious URL.
  17938. *
  17939. * If the URL matches the `aHrefSanitizationWhitelist` regular expression, it is returned unchanged.
  17940. *
  17941. * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written
  17942. * to the DOM it is inactive and potentially malicious code will not be executed.
  17943. *
  17944. * @param {RegExp=} regexp New regexp to whitelist urls with.
  17945. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  17946. * chaining otherwise.
  17947. */
  17948. this.aHrefSanitizationWhitelist = function(regexp) {
  17949. if (isDefined(regexp)) {
  17950. aHrefSanitizationWhitelist = regexp;
  17951. return this;
  17952. }
  17953. return aHrefSanitizationWhitelist;
  17954. };
  17955. /**
  17956. * @description
  17957. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  17958. * urls during img[src] sanitization.
  17959. *
  17960. * The sanitization is a security measure aimed at prevent XSS attacks via HTML image src links.
  17961. *
  17962. * Any URL due to be assigned to an `img[src]` attribute via interpolation is marked as requiring
  17963. * the $sce.MEDIA_URL security context. When interpolation occurs a call is made to
  17964. * `$sce.trustAsMediaUrl(url)` which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize
  17965. * the potentially malicious URL.
  17966. *
  17967. * If the URL matches the `aImgSanitizationWhitelist` regular expression, it is returned unchanged.
  17968. *
  17969. * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written
  17970. * to the DOM it is inactive and potentially malicious code will not be executed.
  17971. *
  17972. * @param {RegExp=} regexp New regexp to whitelist urls with.
  17973. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  17974. * chaining otherwise.
  17975. */
  17976. this.imgSrcSanitizationWhitelist = function(regexp) {
  17977. if (isDefined(regexp)) {
  17978. imgSrcSanitizationWhitelist = regexp;
  17979. return this;
  17980. }
  17981. return imgSrcSanitizationWhitelist;
  17982. };
  17983. this.$get = function() {
  17984. return function sanitizeUri(uri, isMediaUrl) {
  17985. // if (!uri) return uri;
  17986. var regex = isMediaUrl ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  17987. var normalizedVal = urlResolve(uri && uri.trim()).href;
  17988. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  17989. return 'unsafe:' + normalizedVal;
  17990. }
  17991. return uri;
  17992. };
  17993. };
  17994. }
  17995. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  17996. * Any commits to this file should be reviewed with security in mind. *
  17997. * Changes to this file can potentially create security vulnerabilities. *
  17998. * An approval from 2 Core members with history of modifying *
  17999. * this file is required. *
  18000. * *
  18001. * Does the change somehow allow for arbitrary javascript to be executed? *
  18002. * Or allows for someone to change the prototype of built-in objects? *
  18003. * Or gives undesired access to variables likes document or window? *
  18004. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  18005. /* exported $SceProvider, $SceDelegateProvider */
  18006. var $sceMinErr = minErr('$sce');
  18007. var SCE_CONTEXTS = {
  18008. // HTML is used when there's HTML rendered (e.g. ng-bind-html, iframe srcdoc binding).
  18009. HTML: 'html',
  18010. // Style statements or stylesheets. Currently unused in AngularJS.
  18011. CSS: 'css',
  18012. // An URL used in a context where it refers to the source of media, which are not expected to be run
  18013. // as scripts, such as an image, audio, video, etc.
  18014. MEDIA_URL: 'mediaUrl',
  18015. // An URL used in a context where it does not refer to a resource that loads code.
  18016. // A value that can be trusted as a URL can also trusted as a MEDIA_URL.
  18017. URL: 'url',
  18018. // RESOURCE_URL is a subtype of URL used where the referred-to resource could be interpreted as
  18019. // code. (e.g. ng-include, script src binding, templateUrl)
  18020. // A value that can be trusted as a RESOURCE_URL, can also trusted as a URL and a MEDIA_URL.
  18021. RESOURCE_URL: 'resourceUrl',
  18022. // Script. Currently unused in AngularJS.
  18023. JS: 'js'
  18024. };
  18025. // Helper functions follow.
  18026. var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;
  18027. function snakeToCamel(name) {
  18028. return name
  18029. .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);
  18030. }
  18031. function adjustMatcher(matcher) {
  18032. if (matcher === 'self') {
  18033. return matcher;
  18034. } else if (isString(matcher)) {
  18035. // Strings match exactly except for 2 wildcards - '*' and '**'.
  18036. // '*' matches any character except those from the set ':/.?&'.
  18037. // '**' matches any character (like .* in a RegExp).
  18038. // More than 2 *'s raises an error as it's ill defined.
  18039. if (matcher.indexOf('***') > -1) {
  18040. throw $sceMinErr('iwcard',
  18041. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  18042. }
  18043. matcher = escapeForRegexp(matcher).
  18044. replace(/\\\*\\\*/g, '.*').
  18045. replace(/\\\*/g, '[^:/.?&;]*');
  18046. return new RegExp('^' + matcher + '$');
  18047. } else if (isRegExp(matcher)) {
  18048. // The only other type of matcher allowed is a Regexp.
  18049. // Match entire URL / disallow partial matches.
  18050. // Flags are reset (i.e. no global, ignoreCase or multiline)
  18051. return new RegExp('^' + matcher.source + '$');
  18052. } else {
  18053. throw $sceMinErr('imatcher',
  18054. 'Matchers may only be "self", string patterns or RegExp objects');
  18055. }
  18056. }
  18057. function adjustMatchers(matchers) {
  18058. var adjustedMatchers = [];
  18059. if (isDefined(matchers)) {
  18060. forEach(matchers, function(matcher) {
  18061. adjustedMatchers.push(adjustMatcher(matcher));
  18062. });
  18063. }
  18064. return adjustedMatchers;
  18065. }
  18066. /**
  18067. * @ngdoc service
  18068. * @name $sceDelegate
  18069. * @kind function
  18070. *
  18071. * @description
  18072. *
  18073. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  18074. * Contextual Escaping (SCE)} services to AngularJS.
  18075. *
  18076. * For an overview of this service and the functionnality it provides in AngularJS, see the main
  18077. * page for {@link ng.$sce SCE}. The current page is targeted for developers who need to alter how
  18078. * SCE works in their application, which shouldn't be needed in most cases.
  18079. *
  18080. * <div class="alert alert-danger">
  18081. * AngularJS strongly relies on contextual escaping for the security of bindings: disabling or
  18082. * modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners,
  18083. * changes to this service will also influence users, so be extra careful and document your changes.
  18084. * </div>
  18085. *
  18086. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  18087. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  18088. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  18089. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  18090. * work because `$sce` delegates to `$sceDelegate` for these operations.
  18091. *
  18092. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  18093. *
  18094. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  18095. * can override it completely to change the behavior of `$sce`, the common case would
  18096. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  18097. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  18098. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  18099. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  18100. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  18101. */
  18102. /**
  18103. * @ngdoc provider
  18104. * @name $sceDelegateProvider
  18105. * @this
  18106. *
  18107. * @description
  18108. *
  18109. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  18110. * $sceDelegate service}, used as a delegate for {@link ng.$sce Strict Contextual Escaping (SCE)}.
  18111. *
  18112. * The `$sceDelegateProvider` allows one to get/set the whitelists and blacklists used to ensure
  18113. * that the URLs used for sourcing AngularJS templates and other script-running URLs are safe (all
  18114. * places that use the `$sce.RESOURCE_URL` context). See
  18115. * {@link ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist}
  18116. * and
  18117. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist},
  18118. *
  18119. * For the general details about this service in AngularJS, read the main page for {@link ng.$sce
  18120. * Strict Contextual Escaping (SCE)}.
  18121. *
  18122. * **Example**: Consider the following case. <a name="example"></a>
  18123. *
  18124. * - your app is hosted at url `http://myapp.example.com/`
  18125. * - but some of your templates are hosted on other domains you control such as
  18126. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  18127. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  18128. *
  18129. * Here is what a secure configuration for this scenario might look like:
  18130. *
  18131. * ```
  18132. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  18133. * $sceDelegateProvider.resourceUrlWhitelist([
  18134. * // Allow same origin resource loads.
  18135. * 'self',
  18136. * // Allow loading from our assets domain. Notice the difference between * and **.
  18137. * 'http://srv*.assets.example.com/**'
  18138. * ]);
  18139. *
  18140. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  18141. * $sceDelegateProvider.resourceUrlBlacklist([
  18142. * 'http://myapp.example.com/clickThru**'
  18143. * ]);
  18144. * });
  18145. * ```
  18146. * Note that an empty whitelist will block every resource URL from being loaded, and will require
  18147. * you to manually mark each one as trusted with `$sce.trustAsResourceUrl`. However, templates
  18148. * requested by {@link ng.$templateRequest $templateRequest} that are present in
  18149. * {@link ng.$templateCache $templateCache} will not go through this check. If you have a mechanism
  18150. * to populate your templates in that cache at config time, then it is a good idea to remove 'self'
  18151. * from that whitelist. This helps to mitigate the security impact of certain types of issues, like
  18152. * for instance attacker-controlled `ng-includes`.
  18153. */
  18154. function $SceDelegateProvider() {
  18155. this.SCE_CONTEXTS = SCE_CONTEXTS;
  18156. // Resource URLs can also be trusted by policy.
  18157. var resourceUrlWhitelist = ['self'],
  18158. resourceUrlBlacklist = [];
  18159. /**
  18160. * @ngdoc method
  18161. * @name $sceDelegateProvider#resourceUrlWhitelist
  18162. * @kind function
  18163. *
  18164. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  18165. * provided. This must be an array or null. A snapshot of this array is used so further
  18166. * changes to the array are ignored.
  18167. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  18168. * allowed in this array.
  18169. *
  18170. * @return {Array} The currently set whitelist array.
  18171. *
  18172. * @description
  18173. * Sets/Gets the whitelist of trusted resource URLs.
  18174. *
  18175. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  18176. * same origin resource requests.
  18177. *
  18178. * <div class="alert alert-warning">
  18179. * **Note:** the default whitelist of 'self' is not recommended if your app shares its origin
  18180. * with other apps! It is a good idea to limit it to only your application's directory.
  18181. * </div>
  18182. */
  18183. this.resourceUrlWhitelist = function(value) {
  18184. if (arguments.length) {
  18185. resourceUrlWhitelist = adjustMatchers(value);
  18186. }
  18187. return resourceUrlWhitelist;
  18188. };
  18189. /**
  18190. * @ngdoc method
  18191. * @name $sceDelegateProvider#resourceUrlBlacklist
  18192. * @kind function
  18193. *
  18194. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  18195. * provided. This must be an array or null. A snapshot of this array is used so further
  18196. * changes to the array are ignored.</p><p>
  18197. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  18198. * allowed in this array.</p><p>
  18199. * The typical usage for the blacklist is to **block
  18200. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  18201. * these would otherwise be trusted but actually return content from the redirected domain.
  18202. * </p><p>
  18203. * Finally, **the blacklist overrides the whitelist** and has the final say.
  18204. *
  18205. * @return {Array} The currently set blacklist array.
  18206. *
  18207. * @description
  18208. * Sets/Gets the blacklist of trusted resource URLs.
  18209. *
  18210. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  18211. * is no blacklist.)
  18212. */
  18213. this.resourceUrlBlacklist = function(value) {
  18214. if (arguments.length) {
  18215. resourceUrlBlacklist = adjustMatchers(value);
  18216. }
  18217. return resourceUrlBlacklist;
  18218. };
  18219. this.$get = ['$injector', '$$sanitizeUri', function($injector, $$sanitizeUri) {
  18220. var htmlSanitizer = function htmlSanitizer(html) {
  18221. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  18222. };
  18223. if ($injector.has('$sanitize')) {
  18224. htmlSanitizer = $injector.get('$sanitize');
  18225. }
  18226. function matchUrl(matcher, parsedUrl) {
  18227. if (matcher === 'self') {
  18228. return urlIsSameOrigin(parsedUrl) || urlIsSameOriginAsBaseUrl(parsedUrl);
  18229. } else {
  18230. // definitely a regex. See adjustMatchers()
  18231. return !!matcher.exec(parsedUrl.href);
  18232. }
  18233. }
  18234. function isResourceUrlAllowedByPolicy(url) {
  18235. var parsedUrl = urlResolve(url.toString());
  18236. var i, n, allowed = false;
  18237. // Ensure that at least one item from the whitelist allows this url.
  18238. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  18239. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  18240. allowed = true;
  18241. break;
  18242. }
  18243. }
  18244. if (allowed) {
  18245. // Ensure that no item from the blacklist blocked this url.
  18246. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  18247. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  18248. allowed = false;
  18249. break;
  18250. }
  18251. }
  18252. }
  18253. return allowed;
  18254. }
  18255. function generateHolderType(Base) {
  18256. var holderType = function TrustedValueHolderType(trustedValue) {
  18257. this.$$unwrapTrustedValue = function() {
  18258. return trustedValue;
  18259. };
  18260. };
  18261. if (Base) {
  18262. holderType.prototype = new Base();
  18263. }
  18264. holderType.prototype.valueOf = function sceValueOf() {
  18265. return this.$$unwrapTrustedValue();
  18266. };
  18267. holderType.prototype.toString = function sceToString() {
  18268. return this.$$unwrapTrustedValue().toString();
  18269. };
  18270. return holderType;
  18271. }
  18272. var trustedValueHolderBase = generateHolderType(),
  18273. byType = {};
  18274. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  18275. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  18276. byType[SCE_CONTEXTS.MEDIA_URL] = generateHolderType(trustedValueHolderBase);
  18277. byType[SCE_CONTEXTS.URL] = generateHolderType(byType[SCE_CONTEXTS.MEDIA_URL]);
  18278. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  18279. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  18280. /**
  18281. * @ngdoc method
  18282. * @name $sceDelegate#trustAs
  18283. *
  18284. * @description
  18285. * Returns a trusted representation of the parameter for the specified context. This trusted
  18286. * object will later on be used as-is, without any security check, by bindings or directives
  18287. * that require this security context.
  18288. * For instance, marking a string as trusted for the `$sce.HTML` context will entirely bypass
  18289. * the potential `$sanitize` call in corresponding `$sce.HTML` bindings or directives, such as
  18290. * `ng-bind-html`. Note that in most cases you won't need to call this function: if you have the
  18291. * sanitizer loaded, passing the value itself will render all the HTML that does not pose a
  18292. * security risk.
  18293. *
  18294. * See {@link ng.$sceDelegate#getTrusted getTrusted} for the function that will consume those
  18295. * trusted values, and {@link ng.$sce $sce} for general documentation about strict contextual
  18296. * escaping.
  18297. *
  18298. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  18299. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  18300. *
  18301. * @param {*} value The value that should be considered trusted.
  18302. * @return {*} A trusted representation of value, that can be used in the given context.
  18303. */
  18304. function trustAs(type, trustedValue) {
  18305. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  18306. if (!Constructor) {
  18307. throw $sceMinErr('icontext',
  18308. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  18309. type, trustedValue);
  18310. }
  18311. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  18312. return trustedValue;
  18313. }
  18314. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  18315. // mutable objects, we ensure here that the value passed in is actually a string.
  18316. if (typeof trustedValue !== 'string') {
  18317. throw $sceMinErr('itype',
  18318. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  18319. type);
  18320. }
  18321. return new Constructor(trustedValue);
  18322. }
  18323. /**
  18324. * @ngdoc method
  18325. * @name $sceDelegate#valueOf
  18326. *
  18327. * @description
  18328. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  18329. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  18330. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  18331. *
  18332. * If the passed parameter is not a value that had been returned by {@link
  18333. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, it must be returned as-is.
  18334. *
  18335. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  18336. * call or anything else.
  18337. * @return {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  18338. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  18339. * `value` unchanged.
  18340. */
  18341. function valueOf(maybeTrusted) {
  18342. if (maybeTrusted instanceof trustedValueHolderBase) {
  18343. return maybeTrusted.$$unwrapTrustedValue();
  18344. } else {
  18345. return maybeTrusted;
  18346. }
  18347. }
  18348. /**
  18349. * @ngdoc method
  18350. * @name $sceDelegate#getTrusted
  18351. *
  18352. * @description
  18353. * Given an object and a security context in which to assign it, returns a value that's safe to
  18354. * use in this context, which was represented by the parameter. To do so, this function either
  18355. * unwraps the safe type it has been given (for instance, a {@link ng.$sceDelegate#trustAs
  18356. * `$sceDelegate.trustAs`} result), or it might try to sanitize the value given, depending on
  18357. * the context and sanitizer availablility.
  18358. *
  18359. * The contexts that can be sanitized are $sce.MEDIA_URL, $sce.URL and $sce.HTML. The first two are available
  18360. * by default, and the third one relies on the `$sanitize` service (which may be loaded through
  18361. * the `ngSanitize` module). Furthermore, for $sce.RESOURCE_URL context, a plain string may be
  18362. * accepted if the resource url policy defined by {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  18363. * `$sceDelegateProvider.resourceUrlWhitelist`} and {@link ng.$sceDelegateProvider#resourceUrlBlacklist
  18364. * `$sceDelegateProvider.resourceUrlBlacklist`} accepts that resource.
  18365. *
  18366. * This function will throw if the safe type isn't appropriate for this context, or if the
  18367. * value given cannot be accepted in the context (which might be caused by sanitization not
  18368. * being available, or the value not being recognized as safe).
  18369. *
  18370. * <div class="alert alert-danger">
  18371. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  18372. * (XSS) vulnerability in your application.
  18373. * </div>
  18374. *
  18375. * @param {string} type The context in which this value is to be used (such as `$sce.HTML`).
  18376. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  18377. * `$sceDelegate.trustAs`} call, or anything else (which will not be considered trusted.)
  18378. * @return {*} A version of the value that's safe to use in the given context, or throws an
  18379. * exception if this is impossible.
  18380. */
  18381. function getTrusted(type, maybeTrusted) {
  18382. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  18383. return maybeTrusted;
  18384. }
  18385. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  18386. // If maybeTrusted is a trusted class instance or subclass instance, then unwrap and return
  18387. // as-is.
  18388. if (constructor && maybeTrusted instanceof constructor) {
  18389. return maybeTrusted.$$unwrapTrustedValue();
  18390. }
  18391. // If maybeTrusted is a trusted class instance but not of the correct trusted type
  18392. // then unwrap it and allow it to pass through to the rest of the checks
  18393. if (isFunction(maybeTrusted.$$unwrapTrustedValue)) {
  18394. maybeTrusted = maybeTrusted.$$unwrapTrustedValue();
  18395. }
  18396. // If we get here, then we will either sanitize the value or throw an exception.
  18397. if (type === SCE_CONTEXTS.MEDIA_URL || type === SCE_CONTEXTS.URL) {
  18398. // we attempt to sanitize non-resource URLs
  18399. return $$sanitizeUri(maybeTrusted.toString(), type === SCE_CONTEXTS.MEDIA_URL);
  18400. } else if (type === SCE_CONTEXTS.RESOURCE_URL) {
  18401. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  18402. return maybeTrusted;
  18403. } else {
  18404. throw $sceMinErr('insecurl',
  18405. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  18406. maybeTrusted.toString());
  18407. }
  18408. } else if (type === SCE_CONTEXTS.HTML) {
  18409. // htmlSanitizer throws its own error when no sanitizer is available.
  18410. return htmlSanitizer(maybeTrusted);
  18411. }
  18412. // Default error when the $sce service has no way to make the input safe.
  18413. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  18414. }
  18415. return { trustAs: trustAs,
  18416. getTrusted: getTrusted,
  18417. valueOf: valueOf };
  18418. }];
  18419. }
  18420. /**
  18421. * @ngdoc provider
  18422. * @name $sceProvider
  18423. * @this
  18424. *
  18425. * @description
  18426. *
  18427. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  18428. * - enable/disable Strict Contextual Escaping (SCE) in a module
  18429. * - override the default implementation with a custom delegate
  18430. *
  18431. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  18432. */
  18433. /**
  18434. * @ngdoc service
  18435. * @name $sce
  18436. * @kind function
  18437. *
  18438. * @description
  18439. *
  18440. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  18441. *
  18442. * ## Strict Contextual Escaping
  18443. *
  18444. * Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render
  18445. * trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and
  18446. * (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  18447. *
  18448. * ### Overview
  18449. *
  18450. * To systematically block XSS security bugs, AngularJS treats all values as untrusted by default in
  18451. * HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically
  18452. * run security checks on them (sanitizations, whitelists, depending on context), or throw when it
  18453. * cannot guarantee the security of the result. That behavior depends strongly on contexts: HTML
  18454. * can be sanitized, but template URLs cannot, for instance.
  18455. *
  18456. * To illustrate this, consider the `ng-bind-html` directive. It renders its value directly as HTML:
  18457. * we call that the *context*. When given an untrusted input, AngularJS will attempt to sanitize it
  18458. * before rendering if a sanitizer is available, and throw otherwise. To bypass sanitization and
  18459. * render the input as-is, you will need to mark it as trusted for that context before attempting
  18460. * to bind it.
  18461. *
  18462. * As of version 1.2, AngularJS ships with SCE enabled by default.
  18463. *
  18464. * ### In practice
  18465. *
  18466. * Here's an example of a binding in a privileged context:
  18467. *
  18468. * ```
  18469. * <input ng-model="userHtml" aria-label="User input">
  18470. * <div ng-bind-html="userHtml"></div>
  18471. * ```
  18472. *
  18473. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  18474. * disabled, this application allows the user to render arbitrary HTML into the DIV, which would
  18475. * be an XSS security bug. In a more realistic example, one may be rendering user comments, blog
  18476. * articles, etc. via bindings. (HTML is just one example of a context where rendering user
  18477. * controlled input creates security vulnerabilities.)
  18478. *
  18479. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  18480. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  18481. *
  18482. * How would you ensure that every place that used these types of bindings was bound to a value that
  18483. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  18484. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  18485. * properties/fields and forgot to update the binding to the sanitized value?
  18486. *
  18487. * To be secure by default, AngularJS makes sure bindings go through that sanitization, or
  18488. * any similar validation process, unless there's a good reason to trust the given value in this
  18489. * context. That trust is formalized with a function call. This means that as a developer, you
  18490. * can assume all untrusted bindings are safe. Then, to audit your code for binding security issues,
  18491. * you just need to ensure the values you mark as trusted indeed are safe - because they were
  18492. * received from your server, sanitized by your library, etc. You can organize your codebase to
  18493. * help with this - perhaps allowing only the files in a specific directory to do this.
  18494. * Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then
  18495. * becomes a more manageable task.
  18496. *
  18497. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  18498. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  18499. * build the trusted versions of your values.
  18500. *
  18501. * ### How does it work?
  18502. *
  18503. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  18504. * $sce.getTrusted(context, value)} rather than to the value directly. Think of this function as
  18505. * a way to enforce the required security context in your data sink. Directives use {@link
  18506. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs
  18507. * the {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. Also,
  18508. * when binding without directives, AngularJS will understand the context of your bindings
  18509. * automatically.
  18510. *
  18511. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  18512. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  18513. * simplified):
  18514. *
  18515. * ```
  18516. * var ngBindHtmlDirective = ['$sce', function($sce) {
  18517. * return function(scope, element, attr) {
  18518. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  18519. * element.html(value || '');
  18520. * });
  18521. * };
  18522. * }];
  18523. * ```
  18524. *
  18525. * ### Impact on loading templates
  18526. *
  18527. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  18528. * `templateUrl`'s specified by {@link guide/directive directives}.
  18529. *
  18530. * By default, AngularJS only loads templates from the same domain and protocol as the application
  18531. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  18532. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  18533. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  18534. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  18535. *
  18536. * *Please note*:
  18537. * The browser's
  18538. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  18539. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  18540. * policy apply in addition to this and may further restrict whether the template is successfully
  18541. * loaded. This means that without the right CORS policy, loading templates from a different domain
  18542. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  18543. * browsers.
  18544. *
  18545. * ### This feels like too much overhead
  18546. *
  18547. * It's important to remember that SCE only applies to interpolation expressions.
  18548. *
  18549. * If your expressions are constant literals, they're automatically trusted and you don't need to
  18550. * call `$sce.trustAs` on them (e.g.
  18551. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works (remember to include the
  18552. * `ngSanitize` module). The `$sceDelegate` will also use the `$sanitize` service if it is available
  18553. * when binding untrusted values to `$sce.HTML` context.
  18554. * AngularJS provides an implementation in `angular-sanitize.js`, and if you
  18555. * wish to use it, you will also need to depend on the {@link ngSanitize `ngSanitize`} module in
  18556. * your application.
  18557. *
  18558. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  18559. * templates in `ng-include` from your application's domain without having to even know about SCE.
  18560. * It blocks loading templates from other domains or loading templates over http from an https
  18561. * served document. You can change these by setting your own custom {@link
  18562. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  18563. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  18564. *
  18565. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  18566. * application that's secure and can be audited to verify that with much more ease than bolting
  18567. * security onto an application later.
  18568. *
  18569. * <a name="contexts"></a>
  18570. * ### What trusted context types are supported?
  18571. *
  18572. * | Context | Notes |
  18573. * |---------------------|----------------|
  18574. * | `$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. |
  18575. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  18576. * | `$sce.MEDIA_URL` | For URLs that are safe to render as media. Is automatically converted from string by sanitizing when needed. |
  18577. * | `$sce.URL` | For URLs that are safe to follow as links. Is automatically converted from string by sanitizing when needed. Note that `$sce.URL` makes a stronger statement about the URL than `$sce.MEDIA_URL` does and therefore contexts requiring values trusted for `$sce.URL` can be used anywhere that values trusted for `$sce.MEDIA_URL` are required.|
  18578. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` or `$sce.MEDIA_URL` do and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` or `$sce.MEDIA_URL` are required. <br><br> The {@link $sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider#resourceUrlWhitelist()} and {@link $sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider#resourceUrlBlacklist()} can be used to restrict trusted origins for `RESOURCE_URL` |
  18579. * | `$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. |
  18580. *
  18581. *
  18582. * <div class="alert alert-warning">
  18583. * Be aware that, before AngularJS 1.7.0, `a[href]` and `img[src]` used to sanitize their
  18584. * interpolated values directly rather than rely upon {@link ng.$sce#getTrusted `$sce.getTrusted`}.
  18585. *
  18586. * **As of 1.7.0, this is no longer the case.**
  18587. *
  18588. * Now such interpolations are marked as requiring `$sce.URL` (for `a[href]`) or `$sce.MEDIA_URL`
  18589. * (for `img[src]`), so that the sanitization happens (via `$sce.getTrusted...`) when the `$interpolate`
  18590. * service evaluates the expressions.
  18591. * </div>
  18592. *
  18593. * There are no CSS or JS context bindings in AngularJS currently, so their corresponding `$sce.trustAs`
  18594. * functions aren't useful yet. This might evolve.
  18595. *
  18596. * ### Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  18597. *
  18598. * Each element in these arrays must be one of the following:
  18599. *
  18600. * - **'self'**
  18601. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  18602. * domain** as the application document using the **same protocol**.
  18603. * - **String** (except the special value `'self'`)
  18604. * - The string is matched against the full *normalized / absolute URL* of the resource
  18605. * being tested (substring matches are not good enough.)
  18606. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  18607. * match themselves.
  18608. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  18609. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  18610. * in a whitelist.
  18611. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  18612. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  18613. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  18614. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  18615. * http://foo.example.com/templates/**).
  18616. * - **RegExp** (*see caveat below*)
  18617. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  18618. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  18619. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  18620. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  18621. * small number of cases. A `.` character in the regex used when matching the scheme or a
  18622. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  18623. * is highly recommended to use the string patterns and only fall back to regular expressions
  18624. * as a last resort.
  18625. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  18626. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  18627. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  18628. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  18629. * - If you are generating your JavaScript from some other templating engine (not
  18630. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  18631. * remember to escape your regular expression (and be aware that you might need more than
  18632. * one level of escaping depending on your templating engine and the way you interpolated
  18633. * the value.) Do make use of your platform's escaping mechanism as it might be good
  18634. * enough before coding your own. E.g. Ruby has
  18635. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  18636. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  18637. * Javascript lacks a similar built in function for escaping. Take a look at Google
  18638. * Closure library's [goog.string.regExpEscape(s)](
  18639. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  18640. *
  18641. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  18642. *
  18643. * ### Show me an example using SCE.
  18644. *
  18645. * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
  18646. * <file name="index.html">
  18647. * <div ng-controller="AppController as myCtrl">
  18648. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  18649. * <b>User comments</b><br>
  18650. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  18651. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  18652. * exploit.
  18653. * <div class="well">
  18654. * <div ng-repeat="userComment in myCtrl.userComments">
  18655. * <b>{{userComment.name}}</b>:
  18656. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  18657. * <br>
  18658. * </div>
  18659. * </div>
  18660. * </div>
  18661. * </file>
  18662. *
  18663. * <file name="script.js">
  18664. * angular.module('mySceApp', ['ngSanitize'])
  18665. * .controller('AppController', ['$http', '$templateCache', '$sce',
  18666. * function AppController($http, $templateCache, $sce) {
  18667. * var self = this;
  18668. * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {
  18669. * self.userComments = response.data;
  18670. * });
  18671. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  18672. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  18673. * 'sanitization.&quot;">Hover over this text.</span>');
  18674. * }]);
  18675. * </file>
  18676. *
  18677. * <file name="test_data.json">
  18678. * [
  18679. * { "name": "Alice",
  18680. * "htmlComment":
  18681. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  18682. * },
  18683. * { "name": "Bob",
  18684. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  18685. * }
  18686. * ]
  18687. * </file>
  18688. *
  18689. * <file name="protractor.js" type="protractor">
  18690. * describe('SCE doc demo', function() {
  18691. * it('should sanitize untrusted values', function() {
  18692. * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
  18693. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  18694. * });
  18695. *
  18696. * it('should NOT sanitize explicitly trusted values', function() {
  18697. * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
  18698. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  18699. * 'sanitization.&quot;">Hover over this text.</span>');
  18700. * });
  18701. * });
  18702. * </file>
  18703. * </example>
  18704. *
  18705. *
  18706. *
  18707. * ## Can I disable SCE completely?
  18708. *
  18709. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  18710. * for little coding overhead. It will be much harder to take an SCE disabled application and
  18711. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  18712. * for cases where you have a lot of existing code that was written before SCE was introduced and
  18713. * you're migrating them a module at a time. Also do note that this is an app-wide setting, so if
  18714. * you are writing a library, you will cause security bugs applications using it.
  18715. *
  18716. * That said, here's how you can completely disable SCE:
  18717. *
  18718. * ```
  18719. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  18720. * // Completely disable SCE. For demonstration purposes only!
  18721. * // Do not use in new projects or libraries.
  18722. * $sceProvider.enabled(false);
  18723. * });
  18724. * ```
  18725. *
  18726. */
  18727. function $SceProvider() {
  18728. var enabled = true;
  18729. /**
  18730. * @ngdoc method
  18731. * @name $sceProvider#enabled
  18732. * @kind function
  18733. *
  18734. * @param {boolean=} value If provided, then enables/disables SCE application-wide.
  18735. * @return {boolean} True if SCE is enabled, false otherwise.
  18736. *
  18737. * @description
  18738. * Enables/disables SCE and returns the current value.
  18739. */
  18740. this.enabled = function(value) {
  18741. if (arguments.length) {
  18742. enabled = !!value;
  18743. }
  18744. return enabled;
  18745. };
  18746. /* Design notes on the default implementation for SCE.
  18747. *
  18748. * The API contract for the SCE delegate
  18749. * -------------------------------------
  18750. * The SCE delegate object must provide the following 3 methods:
  18751. *
  18752. * - trustAs(contextEnum, value)
  18753. * This method is used to tell the SCE service that the provided value is OK to use in the
  18754. * contexts specified by contextEnum. It must return an object that will be accepted by
  18755. * getTrusted() for a compatible contextEnum and return this value.
  18756. *
  18757. * - valueOf(value)
  18758. * For values that were not produced by trustAs(), return them as is. For values that were
  18759. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  18760. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  18761. * such a value.
  18762. *
  18763. * - getTrusted(contextEnum, value)
  18764. * This function should return the value that is safe to use in the context specified by
  18765. * contextEnum or throw and exception otherwise.
  18766. *
  18767. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  18768. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  18769. * instance, an implementation could maintain a registry of all trusted objects by context. In
  18770. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  18771. * return the same object passed in if it was found in the registry under a compatible context or
  18772. * throw an exception otherwise. An implementation might only wrap values some of the time based
  18773. * on some criteria. getTrusted() might return a value and not throw an exception for special
  18774. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  18775. *
  18776. *
  18777. * A note on the inheritance model for SCE contexts
  18778. * ------------------------------------------------
  18779. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  18780. * is purely an implementation details.
  18781. *
  18782. * The contract is simply this:
  18783. *
  18784. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  18785. * will also succeed.
  18786. *
  18787. * Inheritance happens to capture this in a natural way. In some future, we may not use
  18788. * inheritance anymore. That is OK because no code outside of sce.js and sceSpecs.js would need to
  18789. * be aware of this detail.
  18790. */
  18791. this.$get = ['$parse', '$sceDelegate', function(
  18792. $parse, $sceDelegate) {
  18793. // Support: IE 9-11 only
  18794. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  18795. // the "expression(javascript expression)" syntax which is insecure.
  18796. if (enabled && msie < 8) {
  18797. throw $sceMinErr('iequirks',
  18798. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  18799. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  18800. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  18801. }
  18802. var sce = shallowCopy(SCE_CONTEXTS);
  18803. /**
  18804. * @ngdoc method
  18805. * @name $sce#isEnabled
  18806. * @kind function
  18807. *
  18808. * @return {Boolean} True if SCE is enabled, false otherwise. If you want to set the value, you
  18809. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  18810. *
  18811. * @description
  18812. * Returns a boolean indicating if SCE is enabled.
  18813. */
  18814. sce.isEnabled = function() {
  18815. return enabled;
  18816. };
  18817. sce.trustAs = $sceDelegate.trustAs;
  18818. sce.getTrusted = $sceDelegate.getTrusted;
  18819. sce.valueOf = $sceDelegate.valueOf;
  18820. if (!enabled) {
  18821. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  18822. sce.valueOf = identity;
  18823. }
  18824. /**
  18825. * @ngdoc method
  18826. * @name $sce#parseAs
  18827. *
  18828. * @description
  18829. * Converts AngularJS {@link guide/expression expression} into a function. This is like {@link
  18830. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  18831. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  18832. * *result*)}
  18833. *
  18834. * @param {string} type The SCE context in which this result will be used.
  18835. * @param {string} expression String expression to compile.
  18836. * @return {function(context, locals)} A function which represents the compiled expression:
  18837. *
  18838. * * `context` – `{object}` – an object against which any expressions embedded in the
  18839. * strings are evaluated against (typically a scope object).
  18840. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18841. * in `context`.
  18842. */
  18843. sce.parseAs = function sceParseAs(type, expr) {
  18844. var parsed = $parse(expr);
  18845. if (parsed.literal && parsed.constant) {
  18846. return parsed;
  18847. } else {
  18848. return $parse(expr, function(value) {
  18849. return sce.getTrusted(type, value);
  18850. });
  18851. }
  18852. };
  18853. /**
  18854. * @ngdoc method
  18855. * @name $sce#trustAs
  18856. *
  18857. * @description
  18858. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns a
  18859. * wrapped object that represents your value, and the trust you have in its safety for the given
  18860. * context. AngularJS can then use that value as-is in bindings of the specified secure context.
  18861. * This is used in bindings for `ng-bind-html`, `ng-include`, and most `src` attribute
  18862. * interpolations. See {@link ng.$sce $sce} for strict contextual escaping.
  18863. *
  18864. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  18865. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  18866. *
  18867. * @param {*} value The value that that should be considered trusted.
  18868. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18869. * in the context you specified.
  18870. */
  18871. /**
  18872. * @ngdoc method
  18873. * @name $sce#trustAsHtml
  18874. *
  18875. * @description
  18876. * Shorthand method. `$sce.trustAsHtml(value)` →
  18877. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  18878. *
  18879. * @param {*} value The value to mark as trusted for `$sce.HTML` context.
  18880. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18881. * in `$sce.HTML` context (like `ng-bind-html`).
  18882. */
  18883. /**
  18884. * @ngdoc method
  18885. * @name $sce#trustAsCss
  18886. *
  18887. * @description
  18888. * Shorthand method. `$sce.trustAsCss(value)` →
  18889. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.CSS, value)`}
  18890. *
  18891. * @param {*} value The value to mark as trusted for `$sce.CSS` context.
  18892. * @return {*} A wrapped version of value that can be used as a trusted variant
  18893. * of your `value` in `$sce.CSS` context. This context is currently unused, so there are
  18894. * almost no reasons to use this function so far.
  18895. */
  18896. /**
  18897. * @ngdoc method
  18898. * @name $sce#trustAsUrl
  18899. *
  18900. * @description
  18901. * Shorthand method. `$sce.trustAsUrl(value)` →
  18902. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  18903. *
  18904. * @param {*} value The value to mark as trusted for `$sce.URL` context.
  18905. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18906. * in `$sce.URL` context. That context is currently unused, so there are almost no reasons
  18907. * to use this function so far.
  18908. */
  18909. /**
  18910. * @ngdoc method
  18911. * @name $sce#trustAsResourceUrl
  18912. *
  18913. * @description
  18914. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  18915. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  18916. *
  18917. * @param {*} value The value to mark as trusted for `$sce.RESOURCE_URL` context.
  18918. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18919. * in `$sce.RESOURCE_URL` context (template URLs in `ng-include`, most `src` attribute
  18920. * bindings, ...)
  18921. */
  18922. /**
  18923. * @ngdoc method
  18924. * @name $sce#trustAsJs
  18925. *
  18926. * @description
  18927. * Shorthand method. `$sce.trustAsJs(value)` →
  18928. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  18929. *
  18930. * @param {*} value The value to mark as trusted for `$sce.JS` context.
  18931. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18932. * in `$sce.JS` context. That context is currently unused, so there are almost no reasons to
  18933. * use this function so far.
  18934. */
  18935. /**
  18936. * @ngdoc method
  18937. * @name $sce#getTrusted
  18938. *
  18939. * @description
  18940. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  18941. * takes any input, and either returns a value that's safe to use in the specified context,
  18942. * or throws an exception. This function is aware of trusted values created by the `trustAs`
  18943. * function and its shorthands, and when contexts are appropriate, returns the unwrapped value
  18944. * as-is. Finally, this function can also throw when there is no way to turn `maybeTrusted` in a
  18945. * safe value (e.g., no sanitization is available or possible.)
  18946. *
  18947. * @param {string} type The context in which this value is to be used.
  18948. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs
  18949. * `$sce.trustAs`} call, or anything else (which will not be considered trusted.)
  18950. * @return {*} A version of the value that's safe to use in the given context, or throws an
  18951. * exception if this is impossible.
  18952. */
  18953. /**
  18954. * @ngdoc method
  18955. * @name $sce#getTrustedHtml
  18956. *
  18957. * @description
  18958. * Shorthand method. `$sce.getTrustedHtml(value)` →
  18959. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  18960. *
  18961. * @param {*} value The value to pass to `$sce.getTrusted`.
  18962. * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  18963. */
  18964. /**
  18965. * @ngdoc method
  18966. * @name $sce#getTrustedCss
  18967. *
  18968. * @description
  18969. * Shorthand method. `$sce.getTrustedCss(value)` →
  18970. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  18971. *
  18972. * @param {*} value The value to pass to `$sce.getTrusted`.
  18973. * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  18974. */
  18975. /**
  18976. * @ngdoc method
  18977. * @name $sce#getTrustedUrl
  18978. *
  18979. * @description
  18980. * Shorthand method. `$sce.getTrustedUrl(value)` →
  18981. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  18982. *
  18983. * @param {*} value The value to pass to `$sce.getTrusted`.
  18984. * @return {*} The return value of `$sce.getTrusted($sce.URL, value)`
  18985. */
  18986. /**
  18987. * @ngdoc method
  18988. * @name $sce#getTrustedResourceUrl
  18989. *
  18990. * @description
  18991. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  18992. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  18993. *
  18994. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  18995. * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  18996. */
  18997. /**
  18998. * @ngdoc method
  18999. * @name $sce#getTrustedJs
  19000. *
  19001. * @description
  19002. * Shorthand method. `$sce.getTrustedJs(value)` →
  19003. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  19004. *
  19005. * @param {*} value The value to pass to `$sce.getTrusted`.
  19006. * @return {*} The return value of `$sce.getTrusted($sce.JS, value)`
  19007. */
  19008. /**
  19009. * @ngdoc method
  19010. * @name $sce#parseAsHtml
  19011. *
  19012. * @description
  19013. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  19014. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  19015. *
  19016. * @param {string} expression String expression to compile.
  19017. * @return {function(context, locals)} A function which represents the compiled expression:
  19018. *
  19019. * * `context` – `{object}` – an object against which any expressions embedded in the
  19020. * strings are evaluated against (typically a scope object).
  19021. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  19022. * in `context`.
  19023. */
  19024. /**
  19025. * @ngdoc method
  19026. * @name $sce#parseAsCss
  19027. *
  19028. * @description
  19029. * Shorthand method. `$sce.parseAsCss(value)` →
  19030. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  19031. *
  19032. * @param {string} expression String expression to compile.
  19033. * @return {function(context, locals)} A function which represents the compiled expression:
  19034. *
  19035. * * `context` – `{object}` – an object against which any expressions embedded in the
  19036. * strings are evaluated against (typically a scope object).
  19037. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  19038. * in `context`.
  19039. */
  19040. /**
  19041. * @ngdoc method
  19042. * @name $sce#parseAsUrl
  19043. *
  19044. * @description
  19045. * Shorthand method. `$sce.parseAsUrl(value)` →
  19046. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  19047. *
  19048. * @param {string} expression String expression to compile.
  19049. * @return {function(context, locals)} A function which represents the compiled expression:
  19050. *
  19051. * * `context` – `{object}` – an object against which any expressions embedded in the
  19052. * strings are evaluated against (typically a scope object).
  19053. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  19054. * in `context`.
  19055. */
  19056. /**
  19057. * @ngdoc method
  19058. * @name $sce#parseAsResourceUrl
  19059. *
  19060. * @description
  19061. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  19062. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  19063. *
  19064. * @param {string} expression String expression to compile.
  19065. * @return {function(context, locals)} A function which represents the compiled expression:
  19066. *
  19067. * * `context` – `{object}` – an object against which any expressions embedded in the
  19068. * strings are evaluated against (typically a scope object).
  19069. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  19070. * in `context`.
  19071. */
  19072. /**
  19073. * @ngdoc method
  19074. * @name $sce#parseAsJs
  19075. *
  19076. * @description
  19077. * Shorthand method. `$sce.parseAsJs(value)` →
  19078. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  19079. *
  19080. * @param {string} expression String expression to compile.
  19081. * @return {function(context, locals)} A function which represents the compiled expression:
  19082. *
  19083. * * `context` – `{object}` – an object against which any expressions embedded in the
  19084. * strings are evaluated against (typically a scope object).
  19085. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  19086. * in `context`.
  19087. */
  19088. // Shorthand delegations.
  19089. var parse = sce.parseAs,
  19090. getTrusted = sce.getTrusted,
  19091. trustAs = sce.trustAs;
  19092. forEach(SCE_CONTEXTS, function(enumValue, name) {
  19093. var lName = lowercase(name);
  19094. sce[snakeToCamel('parse_as_' + lName)] = function(expr) {
  19095. return parse(enumValue, expr);
  19096. };
  19097. sce[snakeToCamel('get_trusted_' + lName)] = function(value) {
  19098. return getTrusted(enumValue, value);
  19099. };
  19100. sce[snakeToCamel('trust_as_' + lName)] = function(value) {
  19101. return trustAs(enumValue, value);
  19102. };
  19103. });
  19104. return sce;
  19105. }];
  19106. }
  19107. /* exported $SnifferProvider */
  19108. /**
  19109. * !!! This is an undocumented "private" service !!!
  19110. *
  19111. * @name $sniffer
  19112. * @requires $window
  19113. * @requires $document
  19114. * @this
  19115. *
  19116. * @property {boolean} history Does the browser support html5 history api ?
  19117. * @property {boolean} transitions Does the browser support CSS transition events ?
  19118. * @property {boolean} animations Does the browser support CSS animation events ?
  19119. *
  19120. * @description
  19121. * This is very simple implementation of testing browser's features.
  19122. */
  19123. function $SnifferProvider() {
  19124. this.$get = ['$window', '$document', function($window, $document) {
  19125. var eventSupport = {},
  19126. // Chrome Packaged Apps are not allowed to access `history.pushState`.
  19127. // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
  19128. // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
  19129. // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
  19130. // (see https://developer.chrome.com/apps/manifest/sandbox).
  19131. // (NW.js apps have access to Chrome APIs, but do support `history`.)
  19132. isNw = $window.nw && $window.nw.process,
  19133. isChromePackagedApp =
  19134. !isNw &&
  19135. $window.chrome &&
  19136. ($window.chrome.app && $window.chrome.app.runtime ||
  19137. !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
  19138. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  19139. android =
  19140. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  19141. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  19142. document = $document[0] || {},
  19143. bodyStyle = document.body && document.body.style,
  19144. transitions = false,
  19145. animations = false;
  19146. if (bodyStyle) {
  19147. // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x
  19148. // Mentioned browsers need a -webkit- prefix for transitions & animations.
  19149. transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);
  19150. animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);
  19151. }
  19152. return {
  19153. // Android has history.pushState, but it does not update location correctly
  19154. // so let's not use the history API at all.
  19155. // http://code.google.com/p/android/issues/detail?id=17471
  19156. // https://github.com/angular/angular.js/issues/904
  19157. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  19158. // so let's not use the history API also
  19159. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  19160. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  19161. hasEvent: function(event) {
  19162. // Support: IE 9-11 only
  19163. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  19164. // it. In particular the event is not fired when backspace or delete key are pressed or
  19165. // when cut operation is performed.
  19166. // IE10+ implements 'input' event but it erroneously fires under various situations,
  19167. // e.g. when placeholder changes, or a form is focused.
  19168. if (event === 'input' && msie) return false;
  19169. if (isUndefined(eventSupport[event])) {
  19170. var divElm = document.createElement('div');
  19171. eventSupport[event] = 'on' + event in divElm;
  19172. }
  19173. return eventSupport[event];
  19174. },
  19175. csp: csp(),
  19176. transitions: transitions,
  19177. animations: animations,
  19178. android: android
  19179. };
  19180. }];
  19181. }
  19182. /**
  19183. * ! This is a private undocumented service !
  19184. *
  19185. * @name $$taskTrackerFactory
  19186. * @description
  19187. * A function to create `TaskTracker` instances.
  19188. *
  19189. * A `TaskTracker` can keep track of pending tasks (grouped by type) and can notify interested
  19190. * parties when all pending tasks (or tasks of a specific type) have been completed.
  19191. *
  19192. * @param {$log} log - A logger instance (such as `$log`). Used to log error during callback
  19193. * execution.
  19194. *
  19195. * @this
  19196. */
  19197. function $$TaskTrackerFactoryProvider() {
  19198. this.$get = valueFn(function(log) { return new TaskTracker(log); });
  19199. }
  19200. function TaskTracker(log) {
  19201. var self = this;
  19202. var taskCounts = {};
  19203. var taskCallbacks = [];
  19204. var ALL_TASKS_TYPE = self.ALL_TASKS_TYPE = '$$all$$';
  19205. var DEFAULT_TASK_TYPE = self.DEFAULT_TASK_TYPE = '$$default$$';
  19206. /**
  19207. * Execute the specified function and decrement the appropriate `taskCounts` counter.
  19208. * If the counter reaches 0, all corresponding `taskCallbacks` are executed.
  19209. *
  19210. * @param {Function} fn - The function to execute.
  19211. * @param {string=} [taskType=DEFAULT_TASK_TYPE] - The type of task that is being completed.
  19212. */
  19213. self.completeTask = completeTask;
  19214. /**
  19215. * Increase the task count for the specified task type (or the default task type if non is
  19216. * specified).
  19217. *
  19218. * @param {string=} [taskType=DEFAULT_TASK_TYPE] - The type of task whose count will be increased.
  19219. */
  19220. self.incTaskCount = incTaskCount;
  19221. /**
  19222. * Execute the specified callback when all pending tasks have been completed.
  19223. *
  19224. * If there are no pending tasks, the callback is executed immediately. You can optionally limit
  19225. * the tasks that will be waited for to a specific type, by passing a `taskType`.
  19226. *
  19227. * @param {function} callback - The function to call when there are no pending tasks.
  19228. * @param {string=} [taskType=ALL_TASKS_TYPE] - The type of tasks that will be waited for.
  19229. */
  19230. self.notifyWhenNoPendingTasks = notifyWhenNoPendingTasks;
  19231. function completeTask(fn, taskType) {
  19232. taskType = taskType || DEFAULT_TASK_TYPE;
  19233. try {
  19234. fn();
  19235. } finally {
  19236. decTaskCount(taskType);
  19237. var countForType = taskCounts[taskType];
  19238. var countForAll = taskCounts[ALL_TASKS_TYPE];
  19239. // If at least one of the queues (`ALL_TASKS_TYPE` or `taskType`) is empty, run callbacks.
  19240. if (!countForAll || !countForType) {
  19241. var getNextCallback = !countForAll ? getLastCallback : getLastCallbackForType;
  19242. var nextCb;
  19243. while ((nextCb = getNextCallback(taskType))) {
  19244. try {
  19245. nextCb();
  19246. } catch (e) {
  19247. log.error(e);
  19248. }
  19249. }
  19250. }
  19251. }
  19252. }
  19253. function decTaskCount(taskType) {
  19254. taskType = taskType || DEFAULT_TASK_TYPE;
  19255. if (taskCounts[taskType]) {
  19256. taskCounts[taskType]--;
  19257. taskCounts[ALL_TASKS_TYPE]--;
  19258. }
  19259. }
  19260. function getLastCallback() {
  19261. var cbInfo = taskCallbacks.pop();
  19262. return cbInfo && cbInfo.cb;
  19263. }
  19264. function getLastCallbackForType(taskType) {
  19265. for (var i = taskCallbacks.length - 1; i >= 0; --i) {
  19266. var cbInfo = taskCallbacks[i];
  19267. if (cbInfo.type === taskType) {
  19268. taskCallbacks.splice(i, 1);
  19269. return cbInfo.cb;
  19270. }
  19271. }
  19272. }
  19273. function incTaskCount(taskType) {
  19274. taskType = taskType || DEFAULT_TASK_TYPE;
  19275. taskCounts[taskType] = (taskCounts[taskType] || 0) + 1;
  19276. taskCounts[ALL_TASKS_TYPE] = (taskCounts[ALL_TASKS_TYPE] || 0) + 1;
  19277. }
  19278. function notifyWhenNoPendingTasks(callback, taskType) {
  19279. taskType = taskType || ALL_TASKS_TYPE;
  19280. if (!taskCounts[taskType]) {
  19281. callback();
  19282. } else {
  19283. taskCallbacks.push({type: taskType, cb: callback});
  19284. }
  19285. }
  19286. }
  19287. var $templateRequestMinErr = minErr('$templateRequest');
  19288. /**
  19289. * @ngdoc provider
  19290. * @name $templateRequestProvider
  19291. * @this
  19292. *
  19293. * @description
  19294. * Used to configure the options passed to the {@link $http} service when making a template request.
  19295. *
  19296. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  19297. * requesting a template.
  19298. */
  19299. function $TemplateRequestProvider() {
  19300. var httpOptions;
  19301. /**
  19302. * @ngdoc method
  19303. * @name $templateRequestProvider#httpOptions
  19304. * @description
  19305. * The options to be passed to the {@link $http} service when making the request.
  19306. * You can use this to override options such as the "Accept" header for template requests.
  19307. *
  19308. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  19309. * options if not overridden here.
  19310. *
  19311. * @param {string=} value new value for the {@link $http} options.
  19312. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  19313. */
  19314. this.httpOptions = function(val) {
  19315. if (val) {
  19316. httpOptions = val;
  19317. return this;
  19318. }
  19319. return httpOptions;
  19320. };
  19321. /**
  19322. * @ngdoc service
  19323. * @name $templateRequest
  19324. *
  19325. * @description
  19326. * The `$templateRequest` service runs security checks then downloads the provided template using
  19327. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  19328. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  19329. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  19330. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  19331. * when `tpl` is of type string and `$templateCache` has the matching entry.
  19332. *
  19333. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  19334. * can configure this via {@link $templateRequestProvider#httpOptions}.
  19335. *
  19336. * `$templateRequest` is used internally by {@link $compile}, {@link ngRoute.$route}, and directives such
  19337. * as {@link ngInclude} to download and cache templates.
  19338. *
  19339. * 3rd party modules should use `$templateRequest` if their services or directives are loading
  19340. * templates.
  19341. *
  19342. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  19343. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  19344. *
  19345. * @return {Promise} a promise for the HTTP response data of the given URL.
  19346. *
  19347. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  19348. */
  19349. this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',
  19350. function($exceptionHandler, $templateCache, $http, $q, $sce) {
  19351. function handleRequestFn(tpl, ignoreRequestError) {
  19352. handleRequestFn.totalPendingRequests++;
  19353. // We consider the template cache holds only trusted templates, so
  19354. // there's no need to go through whitelisting again for keys that already
  19355. // are included in there. This also makes AngularJS accept any script
  19356. // directive, no matter its name. However, we still need to unwrap trusted
  19357. // types.
  19358. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  19359. tpl = $sce.getTrustedResourceUrl(tpl);
  19360. }
  19361. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  19362. if (isArray(transformResponse)) {
  19363. transformResponse = transformResponse.filter(function(transformer) {
  19364. return transformer !== defaultHttpResponseTransform;
  19365. });
  19366. } else if (transformResponse === defaultHttpResponseTransform) {
  19367. transformResponse = null;
  19368. }
  19369. return $http.get(tpl, extend({
  19370. cache: $templateCache,
  19371. transformResponse: transformResponse
  19372. }, httpOptions))
  19373. .finally(function() {
  19374. handleRequestFn.totalPendingRequests--;
  19375. })
  19376. .then(function(response) {
  19377. return $templateCache.put(tpl, response.data);
  19378. }, handleError);
  19379. function handleError(resp) {
  19380. if (!ignoreRequestError) {
  19381. resp = $templateRequestMinErr('tpload',
  19382. 'Failed to load template: {0} (HTTP status: {1} {2})',
  19383. tpl, resp.status, resp.statusText);
  19384. $exceptionHandler(resp);
  19385. }
  19386. return $q.reject(resp);
  19387. }
  19388. }
  19389. handleRequestFn.totalPendingRequests = 0;
  19390. return handleRequestFn;
  19391. }
  19392. ];
  19393. }
  19394. /** @this */
  19395. function $$TestabilityProvider() {
  19396. this.$get = ['$rootScope', '$browser', '$location',
  19397. function($rootScope, $browser, $location) {
  19398. /**
  19399. * @name $testability
  19400. *
  19401. * @description
  19402. * The private $$testability service provides a collection of methods for use when debugging
  19403. * or by automated test and debugging tools.
  19404. */
  19405. var testability = {};
  19406. /**
  19407. * @name $$testability#findBindings
  19408. *
  19409. * @description
  19410. * Returns an array of elements that are bound (via ng-bind or {{}})
  19411. * to expressions matching the input.
  19412. *
  19413. * @param {Element} element The element root to search from.
  19414. * @param {string} expression The binding expression to match.
  19415. * @param {boolean} opt_exactMatch If true, only returns exact matches
  19416. * for the expression. Filters and whitespace are ignored.
  19417. */
  19418. testability.findBindings = function(element, expression, opt_exactMatch) {
  19419. var bindings = element.getElementsByClassName('ng-binding');
  19420. var matches = [];
  19421. forEach(bindings, function(binding) {
  19422. var dataBinding = angular.element(binding).data('$binding');
  19423. if (dataBinding) {
  19424. forEach(dataBinding, function(bindingName) {
  19425. if (opt_exactMatch) {
  19426. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  19427. if (matcher.test(bindingName)) {
  19428. matches.push(binding);
  19429. }
  19430. } else {
  19431. if (bindingName.indexOf(expression) !== -1) {
  19432. matches.push(binding);
  19433. }
  19434. }
  19435. });
  19436. }
  19437. });
  19438. return matches;
  19439. };
  19440. /**
  19441. * @name $$testability#findModels
  19442. *
  19443. * @description
  19444. * Returns an array of elements that are two-way found via ng-model to
  19445. * expressions matching the input.
  19446. *
  19447. * @param {Element} element The element root to search from.
  19448. * @param {string} expression The model expression to match.
  19449. * @param {boolean} opt_exactMatch If true, only returns exact matches
  19450. * for the expression.
  19451. */
  19452. testability.findModels = function(element, expression, opt_exactMatch) {
  19453. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  19454. for (var p = 0; p < prefixes.length; ++p) {
  19455. var attributeEquals = opt_exactMatch ? '=' : '*=';
  19456. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  19457. var elements = element.querySelectorAll(selector);
  19458. if (elements.length) {
  19459. return elements;
  19460. }
  19461. }
  19462. };
  19463. /**
  19464. * @name $$testability#getLocation
  19465. *
  19466. * @description
  19467. * Shortcut for getting the location in a browser agnostic way. Returns
  19468. * the path, search, and hash. (e.g. /path?a=b#hash)
  19469. */
  19470. testability.getLocation = function() {
  19471. return $location.url();
  19472. };
  19473. /**
  19474. * @name $$testability#setLocation
  19475. *
  19476. * @description
  19477. * Shortcut for navigating to a location without doing a full page reload.
  19478. *
  19479. * @param {string} url The location url (path, search and hash,
  19480. * e.g. /path?a=b#hash) to go to.
  19481. */
  19482. testability.setLocation = function(url) {
  19483. if (url !== $location.url()) {
  19484. $location.url(url);
  19485. $rootScope.$digest();
  19486. }
  19487. };
  19488. /**
  19489. * @name $$testability#whenStable
  19490. *
  19491. * @description
  19492. * Calls the callback when all pending tasks are completed.
  19493. *
  19494. * Types of tasks waited for include:
  19495. * - Pending timeouts (via {@link $timeout}).
  19496. * - Pending HTTP requests (via {@link $http}).
  19497. * - In-progress route transitions (via {@link $route}).
  19498. * - Pending tasks scheduled via {@link $rootScope#$applyAsync}.
  19499. * - Pending tasks scheduled via {@link $rootScope#$evalAsync}.
  19500. * These include tasks scheduled via `$evalAsync()` indirectly (such as {@link $q} promises).
  19501. *
  19502. * @param {function} callback
  19503. */
  19504. testability.whenStable = function(callback) {
  19505. $browser.notifyWhenNoOutstandingRequests(callback);
  19506. };
  19507. return testability;
  19508. }];
  19509. }
  19510. var $timeoutMinErr = minErr('$timeout');
  19511. /** @this */
  19512. function $TimeoutProvider() {
  19513. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  19514. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  19515. var deferreds = {};
  19516. /**
  19517. * @ngdoc service
  19518. * @name $timeout
  19519. *
  19520. * @description
  19521. * AngularJS's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  19522. * block and delegates any exceptions to
  19523. * {@link ng.$exceptionHandler $exceptionHandler} service.
  19524. *
  19525. * The return value of calling `$timeout` is a promise, which will be resolved when
  19526. * the delay has passed and the timeout function, if provided, is executed.
  19527. *
  19528. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  19529. *
  19530. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  19531. * synchronously flush the queue of deferred functions.
  19532. *
  19533. * If you only want a promise that will be resolved after some specified delay
  19534. * then you can call `$timeout` without the `fn` function.
  19535. *
  19536. * @param {function()=} fn A function, whose execution should be delayed.
  19537. * @param {number=} [delay=0] Delay in milliseconds.
  19538. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  19539. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  19540. * @param {...*=} Pass additional parameters to the executed function.
  19541. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  19542. * will be resolved with the return value of the `fn` function.
  19543. *
  19544. */
  19545. function timeout(fn, delay, invokeApply) {
  19546. if (!isFunction(fn)) {
  19547. invokeApply = delay;
  19548. delay = fn;
  19549. fn = noop;
  19550. }
  19551. var args = sliceArgs(arguments, 3),
  19552. skipApply = (isDefined(invokeApply) && !invokeApply),
  19553. deferred = (skipApply ? $$q : $q).defer(),
  19554. promise = deferred.promise,
  19555. timeoutId;
  19556. timeoutId = $browser.defer(function() {
  19557. try {
  19558. deferred.resolve(fn.apply(null, args));
  19559. } catch (e) {
  19560. deferred.reject(e);
  19561. $exceptionHandler(e);
  19562. } finally {
  19563. delete deferreds[promise.$$timeoutId];
  19564. }
  19565. if (!skipApply) $rootScope.$apply();
  19566. }, delay, '$timeout');
  19567. promise.$$timeoutId = timeoutId;
  19568. deferreds[timeoutId] = deferred;
  19569. return promise;
  19570. }
  19571. /**
  19572. * @ngdoc method
  19573. * @name $timeout#cancel
  19574. *
  19575. * @description
  19576. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  19577. * resolved with a rejection.
  19578. *
  19579. * @param {Promise=} promise Promise returned by the `$timeout` function.
  19580. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  19581. * canceled.
  19582. */
  19583. timeout.cancel = function(promise) {
  19584. if (!promise) return false;
  19585. if (!promise.hasOwnProperty('$$timeoutId')) {
  19586. throw $timeoutMinErr('badprom',
  19587. '`$timeout.cancel()` called with a promise that was not generated by `$timeout()`.');
  19588. }
  19589. if (!deferreds.hasOwnProperty(promise.$$timeoutId)) return false;
  19590. var id = promise.$$timeoutId;
  19591. var deferred = deferreds[id];
  19592. // Timeout cancels should not report an unhandled promise.
  19593. markQExceptionHandled(deferred.promise);
  19594. deferred.reject('canceled');
  19595. delete deferreds[id];
  19596. return $browser.defer.cancel(id);
  19597. };
  19598. return timeout;
  19599. }];
  19600. }
  19601. // NOTE: The usage of window and document instead of $window and $document here is
  19602. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  19603. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  19604. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  19605. // doesn't know about mocked locations and resolves URLs to the real document - which is
  19606. // exactly the behavior needed here. There is little value is mocking these out for this
  19607. // service.
  19608. var urlParsingNode = window.document.createElement('a');
  19609. var originUrl = urlResolve(window.location.href);
  19610. var baseUrlParsingNode;
  19611. /**
  19612. *
  19613. * Implementation Notes for non-IE browsers
  19614. * ----------------------------------------
  19615. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  19616. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  19617. * URL will be resolved into an absolute URL in the context of the application document.
  19618. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  19619. * properties are all populated to reflect the normalized URL. This approach has wide
  19620. * compatibility - Safari 1+, Mozilla 1+ etc. See
  19621. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  19622. *
  19623. * Implementation Notes for IE
  19624. * ---------------------------
  19625. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  19626. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  19627. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  19628. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  19629. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  19630. * properties such as protocol, hostname, port, etc.
  19631. *
  19632. * References:
  19633. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  19634. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  19635. * http://url.spec.whatwg.org/#urlutils
  19636. * https://github.com/angular/angular.js/pull/2902
  19637. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  19638. *
  19639. * @kind function
  19640. * @param {string|object} url The URL to be parsed. If `url` is not a string, it will be returned
  19641. * unchanged.
  19642. * @description Normalizes and parses a URL.
  19643. * @returns {object} Returns the normalized URL as a dictionary.
  19644. *
  19645. * | member name | Description |
  19646. * |---------------|------------------------------------------------------------------------|
  19647. * | href | A normalized version of the provided URL if it was not an absolute URL |
  19648. * | protocol | The protocol without the trailing colon |
  19649. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  19650. * | search | The search params, minus the question mark |
  19651. * | hash | The hash string, minus the hash symbol |
  19652. * | hostname | The hostname |
  19653. * | port | The port, without ":" |
  19654. * | pathname | The pathname, beginning with "/" |
  19655. *
  19656. */
  19657. function urlResolve(url) {
  19658. if (!isString(url)) return url;
  19659. var href = url;
  19660. // Support: IE 9-11 only
  19661. if (msie) {
  19662. // Normalize before parse. Refer Implementation Notes on why this is
  19663. // done in two steps on IE.
  19664. urlParsingNode.setAttribute('href', href);
  19665. href = urlParsingNode.href;
  19666. }
  19667. urlParsingNode.setAttribute('href', href);
  19668. return {
  19669. href: urlParsingNode.href,
  19670. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  19671. host: urlParsingNode.host,
  19672. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  19673. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  19674. hostname: urlParsingNode.hostname,
  19675. port: urlParsingNode.port,
  19676. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  19677. ? urlParsingNode.pathname
  19678. : '/' + urlParsingNode.pathname
  19679. };
  19680. }
  19681. /**
  19682. * Parse a request URL and determine whether this is a same-origin request as the application
  19683. * document.
  19684. *
  19685. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  19686. * or a parsed URL object.
  19687. * @returns {boolean} Whether the request is for the same origin as the application document.
  19688. */
  19689. function urlIsSameOrigin(requestUrl) {
  19690. return urlsAreSameOrigin(requestUrl, originUrl);
  19691. }
  19692. /**
  19693. * Parse a request URL and determine whether it is same-origin as the current document base URL.
  19694. *
  19695. * Note: The base URL is usually the same as the document location (`location.href`) but can
  19696. * be overriden by using the `<base>` tag.
  19697. *
  19698. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  19699. * or a parsed URL object.
  19700. * @returns {boolean} Whether the URL is same-origin as the document base URL.
  19701. */
  19702. function urlIsSameOriginAsBaseUrl(requestUrl) {
  19703. return urlsAreSameOrigin(requestUrl, getBaseUrl());
  19704. }
  19705. /**
  19706. * Create a function that can check a URL's origin against a list of allowed/whitelisted origins.
  19707. * The current location's origin is implicitly trusted.
  19708. *
  19709. * @param {string[]} whitelistedOriginUrls - A list of URLs (strings), whose origins are trusted.
  19710. *
  19711. * @returns {Function} - A function that receives a URL (string or parsed URL object) and returns
  19712. * whether it is of an allowed origin.
  19713. */
  19714. function urlIsAllowedOriginFactory(whitelistedOriginUrls) {
  19715. var parsedAllowedOriginUrls = [originUrl].concat(whitelistedOriginUrls.map(urlResolve));
  19716. /**
  19717. * Check whether the specified URL (string or parsed URL object) has an origin that is allowed
  19718. * based on a list of whitelisted-origin URLs. The current location's origin is implicitly
  19719. * trusted.
  19720. *
  19721. * @param {string|Object} requestUrl - The URL to be checked (provided as a string that will be
  19722. * resolved or a parsed URL object).
  19723. *
  19724. * @returns {boolean} - Whether the specified URL is of an allowed origin.
  19725. */
  19726. return function urlIsAllowedOrigin(requestUrl) {
  19727. var parsedUrl = urlResolve(requestUrl);
  19728. return parsedAllowedOriginUrls.some(urlsAreSameOrigin.bind(null, parsedUrl));
  19729. };
  19730. }
  19731. /**
  19732. * Determine if two URLs share the same origin.
  19733. *
  19734. * @param {string|Object} url1 - First URL to compare as a string or a normalized URL in the form of
  19735. * a dictionary object returned by `urlResolve()`.
  19736. * @param {string|object} url2 - Second URL to compare as a string or a normalized URL in the form
  19737. * of a dictionary object returned by `urlResolve()`.
  19738. *
  19739. * @returns {boolean} - True if both URLs have the same origin, and false otherwise.
  19740. */
  19741. function urlsAreSameOrigin(url1, url2) {
  19742. url1 = urlResolve(url1);
  19743. url2 = urlResolve(url2);
  19744. return (url1.protocol === url2.protocol &&
  19745. url1.host === url2.host);
  19746. }
  19747. /**
  19748. * Returns the current document base URL.
  19749. * @returns {string}
  19750. */
  19751. function getBaseUrl() {
  19752. if (window.document.baseURI) {
  19753. return window.document.baseURI;
  19754. }
  19755. // `document.baseURI` is available everywhere except IE
  19756. if (!baseUrlParsingNode) {
  19757. baseUrlParsingNode = window.document.createElement('a');
  19758. baseUrlParsingNode.href = '.';
  19759. // Work-around for IE bug described in Implementation Notes. The fix in `urlResolve()` is not
  19760. // suitable here because we need to track changes to the base URL.
  19761. baseUrlParsingNode = baseUrlParsingNode.cloneNode(false);
  19762. }
  19763. return baseUrlParsingNode.href;
  19764. }
  19765. /**
  19766. * @ngdoc service
  19767. * @name $window
  19768. * @this
  19769. *
  19770. * @description
  19771. * A reference to the browser's `window` object. While `window`
  19772. * is globally available in JavaScript, it causes testability problems, because
  19773. * it is a global variable. In AngularJS we always refer to it through the
  19774. * `$window` service, so it may be overridden, removed or mocked for testing.
  19775. *
  19776. * Expressions, like the one defined for the `ngClick` directive in the example
  19777. * below, are evaluated with respect to the current scope. Therefore, there is
  19778. * no risk of inadvertently coding in a dependency on a global value in such an
  19779. * expression.
  19780. *
  19781. * @example
  19782. <example module="windowExample" name="window-service">
  19783. <file name="index.html">
  19784. <script>
  19785. angular.module('windowExample', [])
  19786. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  19787. $scope.greeting = 'Hello, World!';
  19788. $scope.doGreeting = function(greeting) {
  19789. $window.alert(greeting);
  19790. };
  19791. }]);
  19792. </script>
  19793. <div ng-controller="ExampleController">
  19794. <input type="text" ng-model="greeting" aria-label="greeting" />
  19795. <button ng-click="doGreeting(greeting)">ALERT</button>
  19796. </div>
  19797. </file>
  19798. <file name="protractor.js" type="protractor">
  19799. it('should display the greeting in the input box', function() {
  19800. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  19801. // If we click the button it will block the test runner
  19802. // element(':button').click();
  19803. });
  19804. </file>
  19805. </example>
  19806. */
  19807. function $WindowProvider() {
  19808. this.$get = valueFn(window);
  19809. }
  19810. /**
  19811. * @name $$cookieReader
  19812. * @requires $document
  19813. *
  19814. * @description
  19815. * This is a private service for reading cookies used by $http and ngCookies
  19816. *
  19817. * @return {Object} a key/value map of the current cookies
  19818. */
  19819. function $$CookieReader($document) {
  19820. var rawDocument = $document[0] || {};
  19821. var lastCookies = {};
  19822. var lastCookieString = '';
  19823. function safeGetCookie(rawDocument) {
  19824. try {
  19825. return rawDocument.cookie || '';
  19826. } catch (e) {
  19827. return '';
  19828. }
  19829. }
  19830. function safeDecodeURIComponent(str) {
  19831. try {
  19832. return decodeURIComponent(str);
  19833. } catch (e) {
  19834. return str;
  19835. }
  19836. }
  19837. return function() {
  19838. var cookieArray, cookie, i, index, name;
  19839. var currentCookieString = safeGetCookie(rawDocument);
  19840. if (currentCookieString !== lastCookieString) {
  19841. lastCookieString = currentCookieString;
  19842. cookieArray = lastCookieString.split('; ');
  19843. lastCookies = {};
  19844. for (i = 0; i < cookieArray.length; i++) {
  19845. cookie = cookieArray[i];
  19846. index = cookie.indexOf('=');
  19847. if (index > 0) { //ignore nameless cookies
  19848. name = safeDecodeURIComponent(cookie.substring(0, index));
  19849. // the first value that is seen for a cookie is the most
  19850. // specific one. values for the same cookie name that
  19851. // follow are for less specific paths.
  19852. if (isUndefined(lastCookies[name])) {
  19853. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  19854. }
  19855. }
  19856. }
  19857. }
  19858. return lastCookies;
  19859. };
  19860. }
  19861. $$CookieReader.$inject = ['$document'];
  19862. /** @this */
  19863. function $$CookieReaderProvider() {
  19864. this.$get = $$CookieReader;
  19865. }
  19866. /* global currencyFilter: true,
  19867. dateFilter: true,
  19868. filterFilter: true,
  19869. jsonFilter: true,
  19870. limitToFilter: true,
  19871. lowercaseFilter: true,
  19872. numberFilter: true,
  19873. orderByFilter: true,
  19874. uppercaseFilter: true,
  19875. */
  19876. /**
  19877. * @ngdoc provider
  19878. * @name $filterProvider
  19879. * @description
  19880. *
  19881. * Filters are just functions which transform input to an output. However filters need to be
  19882. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  19883. * annotated with dependencies and is responsible for creating a filter function.
  19884. *
  19885. * <div class="alert alert-warning">
  19886. * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.
  19887. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  19888. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  19889. * (`myapp_subsection_filterx`).
  19890. * </div>
  19891. *
  19892. * ```js
  19893. * // Filter registration
  19894. * function MyModule($provide, $filterProvider) {
  19895. * // create a service to demonstrate injection (not always needed)
  19896. * $provide.value('greet', function(name){
  19897. * return 'Hello ' + name + '!';
  19898. * });
  19899. *
  19900. * // register a filter factory which uses the
  19901. * // greet service to demonstrate DI.
  19902. * $filterProvider.register('greet', function(greet){
  19903. * // return the filter function which uses the greet service
  19904. * // to generate salutation
  19905. * return function(text) {
  19906. * // filters need to be forgiving so check input validity
  19907. * return text && greet(text) || text;
  19908. * };
  19909. * });
  19910. * }
  19911. * ```
  19912. *
  19913. * The filter function is registered with the `$injector` under the filter name suffix with
  19914. * `Filter`.
  19915. *
  19916. * ```js
  19917. * it('should be the same instance', inject(
  19918. * function($filterProvider) {
  19919. * $filterProvider.register('reverse', function(){
  19920. * return ...;
  19921. * });
  19922. * },
  19923. * function($filter, reverseFilter) {
  19924. * expect($filter('reverse')).toBe(reverseFilter);
  19925. * });
  19926. * ```
  19927. *
  19928. *
  19929. * For more information about how AngularJS filters work, and how to create your own filters, see
  19930. * {@link guide/filter Filters} in the AngularJS Developer Guide.
  19931. */
  19932. /**
  19933. * @ngdoc service
  19934. * @name $filter
  19935. * @kind function
  19936. * @description
  19937. * Filters are used for formatting data displayed to the user.
  19938. *
  19939. * They can be used in view templates, controllers or services. AngularJS comes
  19940. * with a collection of [built-in filters](api/ng/filter), but it is easy to
  19941. * define your own as well.
  19942. *
  19943. * The general syntax in templates is as follows:
  19944. *
  19945. * ```html
  19946. * {{ expression [| filter_name[:parameter_value] ... ] }}
  19947. * ```
  19948. *
  19949. * @param {String} name Name of the filter function to retrieve
  19950. * @return {Function} the filter function
  19951. * @example
  19952. <example name="$filter" module="filterExample">
  19953. <file name="index.html">
  19954. <div ng-controller="MainCtrl">
  19955. <h3>{{ originalText }}</h3>
  19956. <h3>{{ filteredText }}</h3>
  19957. </div>
  19958. </file>
  19959. <file name="script.js">
  19960. angular.module('filterExample', [])
  19961. .controller('MainCtrl', function($scope, $filter) {
  19962. $scope.originalText = 'hello';
  19963. $scope.filteredText = $filter('uppercase')($scope.originalText);
  19964. });
  19965. </file>
  19966. </example>
  19967. */
  19968. $FilterProvider.$inject = ['$provide'];
  19969. /** @this */
  19970. function $FilterProvider($provide) {
  19971. var suffix = 'Filter';
  19972. /**
  19973. * @ngdoc method
  19974. * @name $filterProvider#register
  19975. * @param {string|Object} name Name of the filter function, or an object map of filters where
  19976. * the keys are the filter names and the values are the filter factories.
  19977. *
  19978. * <div class="alert alert-warning">
  19979. * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.
  19980. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  19981. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  19982. * (`myapp_subsection_filterx`).
  19983. * </div>
  19984. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  19985. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  19986. * of the registered filter instances.
  19987. */
  19988. function register(name, factory) {
  19989. if (isObject(name)) {
  19990. var filters = {};
  19991. forEach(name, function(filter, key) {
  19992. filters[key] = register(key, filter);
  19993. });
  19994. return filters;
  19995. } else {
  19996. return $provide.factory(name + suffix, factory);
  19997. }
  19998. }
  19999. this.register = register;
  20000. this.$get = ['$injector', function($injector) {
  20001. return function(name) {
  20002. return $injector.get(name + suffix);
  20003. };
  20004. }];
  20005. ////////////////////////////////////////
  20006. /* global
  20007. currencyFilter: false,
  20008. dateFilter: false,
  20009. filterFilter: false,
  20010. jsonFilter: false,
  20011. limitToFilter: false,
  20012. lowercaseFilter: false,
  20013. numberFilter: false,
  20014. orderByFilter: false,
  20015. uppercaseFilter: false
  20016. */
  20017. register('currency', currencyFilter);
  20018. register('date', dateFilter);
  20019. register('filter', filterFilter);
  20020. register('json', jsonFilter);
  20021. register('limitTo', limitToFilter);
  20022. register('lowercase', lowercaseFilter);
  20023. register('number', numberFilter);
  20024. register('orderBy', orderByFilter);
  20025. register('uppercase', uppercaseFilter);
  20026. }
  20027. /**
  20028. * @ngdoc filter
  20029. * @name filter
  20030. * @kind function
  20031. *
  20032. * @description
  20033. * Selects a subset of items from `array` and returns it as a new array.
  20034. *
  20035. * @param {Array} array The source array.
  20036. * <div class="alert alert-info">
  20037. * **Note**: If the array contains objects that reference themselves, filtering is not possible.
  20038. * </div>
  20039. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  20040. * `array`.
  20041. *
  20042. * Can be one of:
  20043. *
  20044. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  20045. * objects with string properties in `array` that match this string will be returned. This also
  20046. * applies to nested object properties.
  20047. * The predicate can be negated by prefixing the string with `!`.
  20048. *
  20049. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  20050. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  20051. * which have property `name` containing "M" and property `phone` containing "1". A special
  20052. * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
  20053. * against any property of the object or its nested object properties. That's equivalent to the
  20054. * simple substring match with a `string` as described above. The special property name can be
  20055. * overwritten, using the `anyPropertyKey` parameter.
  20056. * The predicate can be negated by prefixing the string with `!`.
  20057. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  20058. * not containing "M".
  20059. *
  20060. * Note that a named property will match properties on the same level only, while the special
  20061. * `$` property will match properties on the same level or deeper. E.g. an array item like
  20062. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  20063. * **will** be matched by `{$: 'John'}`.
  20064. *
  20065. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  20066. * The function is called for each element of the array, with the element, its index, and
  20067. * the entire array itself as arguments.
  20068. *
  20069. * The final result is an array of those elements that the predicate returned true for.
  20070. *
  20071. * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in
  20072. * determining if values retrieved using `expression` (when it is not a function) should be
  20073. * considered a match based on the expected value (from the filter expression) and actual
  20074. * value (from the object in the array).
  20075. *
  20076. * Can be one of:
  20077. *
  20078. * - `function(actual, expected)`:
  20079. * The function will be given the object value and the predicate value to compare and
  20080. * should return true if both values should be considered equal.
  20081. *
  20082. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  20083. * This is essentially strict comparison of expected and actual.
  20084. *
  20085. * - `false`: A short hand for a function which will look for a substring match in a case
  20086. * insensitive way. Primitive values are converted to strings. Objects are not compared against
  20087. * primitives, unless they have a custom `toString` method (e.g. `Date` objects).
  20088. *
  20089. *
  20090. * Defaults to `false`.
  20091. *
  20092. * @param {string} [anyPropertyKey] The special property name that matches against any property.
  20093. * By default `$`.
  20094. *
  20095. * @example
  20096. <example name="filter-filter">
  20097. <file name="index.html">
  20098. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  20099. {name:'Mary', phone:'800-BIG-MARY'},
  20100. {name:'Mike', phone:'555-4321'},
  20101. {name:'Adam', phone:'555-5678'},
  20102. {name:'Julie', phone:'555-8765'},
  20103. {name:'Juliette', phone:'555-5678'}]"></div>
  20104. <label>Search: <input ng-model="searchText"></label>
  20105. <table id="searchTextResults">
  20106. <tr><th>Name</th><th>Phone</th></tr>
  20107. <tr ng-repeat="friend in friends | filter:searchText">
  20108. <td>{{friend.name}}</td>
  20109. <td>{{friend.phone}}</td>
  20110. </tr>
  20111. </table>
  20112. <hr>
  20113. <label>Any: <input ng-model="search.$"></label> <br>
  20114. <label>Name only <input ng-model="search.name"></label><br>
  20115. <label>Phone only <input ng-model="search.phone"></label><br>
  20116. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  20117. <table id="searchObjResults">
  20118. <tr><th>Name</th><th>Phone</th></tr>
  20119. <tr ng-repeat="friendObj in friends | filter:search:strict">
  20120. <td>{{friendObj.name}}</td>
  20121. <td>{{friendObj.phone}}</td>
  20122. </tr>
  20123. </table>
  20124. </file>
  20125. <file name="protractor.js" type="protractor">
  20126. var expectFriendNames = function(expectedNames, key) {
  20127. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  20128. arr.forEach(function(wd, i) {
  20129. expect(wd.getText()).toMatch(expectedNames[i]);
  20130. });
  20131. });
  20132. };
  20133. it('should search across all fields when filtering with a string', function() {
  20134. var searchText = element(by.model('searchText'));
  20135. searchText.clear();
  20136. searchText.sendKeys('m');
  20137. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  20138. searchText.clear();
  20139. searchText.sendKeys('76');
  20140. expectFriendNames(['John', 'Julie'], 'friend');
  20141. });
  20142. it('should search in specific fields when filtering with a predicate object', function() {
  20143. var searchAny = element(by.model('search.$'));
  20144. searchAny.clear();
  20145. searchAny.sendKeys('i');
  20146. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  20147. });
  20148. it('should use a equal comparison when comparator is true', function() {
  20149. var searchName = element(by.model('search.name'));
  20150. var strict = element(by.model('strict'));
  20151. searchName.clear();
  20152. searchName.sendKeys('Julie');
  20153. strict.click();
  20154. expectFriendNames(['Julie'], 'friendObj');
  20155. });
  20156. </file>
  20157. </example>
  20158. */
  20159. function filterFilter() {
  20160. return function(array, expression, comparator, anyPropertyKey) {
  20161. if (!isArrayLike(array)) {
  20162. if (array == null) {
  20163. return array;
  20164. } else {
  20165. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  20166. }
  20167. }
  20168. anyPropertyKey = anyPropertyKey || '$';
  20169. var expressionType = getTypeForFilter(expression);
  20170. var predicateFn;
  20171. var matchAgainstAnyProp;
  20172. switch (expressionType) {
  20173. case 'function':
  20174. predicateFn = expression;
  20175. break;
  20176. case 'boolean':
  20177. case 'null':
  20178. case 'number':
  20179. case 'string':
  20180. matchAgainstAnyProp = true;
  20181. // falls through
  20182. case 'object':
  20183. predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  20184. break;
  20185. default:
  20186. return array;
  20187. }
  20188. return Array.prototype.filter.call(array, predicateFn);
  20189. };
  20190. }
  20191. // Helper functions for `filterFilter`
  20192. function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
  20193. var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
  20194. var predicateFn;
  20195. if (comparator === true) {
  20196. comparator = equals;
  20197. } else if (!isFunction(comparator)) {
  20198. comparator = function(actual, expected) {
  20199. if (isUndefined(actual)) {
  20200. // No substring matching against `undefined`
  20201. return false;
  20202. }
  20203. if ((actual === null) || (expected === null)) {
  20204. // No substring matching against `null`; only match against `null`
  20205. return actual === expected;
  20206. }
  20207. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  20208. // Should not compare primitives against objects, unless they have custom `toString` method
  20209. return false;
  20210. }
  20211. actual = lowercase('' + actual);
  20212. expected = lowercase('' + expected);
  20213. return actual.indexOf(expected) !== -1;
  20214. };
  20215. }
  20216. predicateFn = function(item) {
  20217. if (shouldMatchPrimitives && !isObject(item)) {
  20218. return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
  20219. }
  20220. return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  20221. };
  20222. return predicateFn;
  20223. }
  20224. function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
  20225. var actualType = getTypeForFilter(actual);
  20226. var expectedType = getTypeForFilter(expected);
  20227. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  20228. return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
  20229. } else if (isArray(actual)) {
  20230. // In case `actual` is an array, consider it a match
  20231. // if ANY of it's items matches `expected`
  20232. return actual.some(function(item) {
  20233. return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
  20234. });
  20235. }
  20236. switch (actualType) {
  20237. case 'object':
  20238. var key;
  20239. if (matchAgainstAnyProp) {
  20240. for (key in actual) {
  20241. // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined
  20242. // See: https://github.com/angular/angular.js/issues/15644
  20243. if (key.charAt && (key.charAt(0) !== '$') &&
  20244. deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
  20245. return true;
  20246. }
  20247. }
  20248. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
  20249. } else if (expectedType === 'object') {
  20250. for (key in expected) {
  20251. var expectedVal = expected[key];
  20252. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  20253. continue;
  20254. }
  20255. var matchAnyProperty = key === anyPropertyKey;
  20256. var actualVal = matchAnyProperty ? actual : actual[key];
  20257. if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
  20258. return false;
  20259. }
  20260. }
  20261. return true;
  20262. } else {
  20263. return comparator(actual, expected);
  20264. }
  20265. case 'function':
  20266. return false;
  20267. default:
  20268. return comparator(actual, expected);
  20269. }
  20270. }
  20271. // Used for easily differentiating between `null` and actual `object`
  20272. function getTypeForFilter(val) {
  20273. return (val === null) ? 'null' : typeof val;
  20274. }
  20275. var MAX_DIGITS = 22;
  20276. var DECIMAL_SEP = '.';
  20277. var ZERO_CHAR = '0';
  20278. /**
  20279. * @ngdoc filter
  20280. * @name currency
  20281. * @kind function
  20282. *
  20283. * @description
  20284. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  20285. * symbol for current locale is used.
  20286. *
  20287. * @param {number} amount Input to filter.
  20288. * @param {string=} symbol Currency symbol or identifier to be displayed.
  20289. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  20290. * @returns {string} Formatted number.
  20291. *
  20292. *
  20293. * @example
  20294. <example module="currencyExample" name="currency-filter">
  20295. <file name="index.html">
  20296. <script>
  20297. angular.module('currencyExample', [])
  20298. .controller('ExampleController', ['$scope', function($scope) {
  20299. $scope.amount = 1234.56;
  20300. }]);
  20301. </script>
  20302. <div ng-controller="ExampleController">
  20303. <input type="number" ng-model="amount" aria-label="amount"> <br>
  20304. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  20305. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
  20306. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  20307. </div>
  20308. </file>
  20309. <file name="protractor.js" type="protractor">
  20310. it('should init with 1234.56', function() {
  20311. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  20312. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  20313. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  20314. });
  20315. it('should update', function() {
  20316. if (browser.params.browser === 'safari') {
  20317. // Safari does not understand the minus key. See
  20318. // https://github.com/angular/protractor/issues/481
  20319. return;
  20320. }
  20321. element(by.model('amount')).clear();
  20322. element(by.model('amount')).sendKeys('-1234');
  20323. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  20324. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  20325. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  20326. });
  20327. </file>
  20328. </example>
  20329. */
  20330. currencyFilter.$inject = ['$locale'];
  20331. function currencyFilter($locale) {
  20332. var formats = $locale.NUMBER_FORMATS;
  20333. return function(amount, currencySymbol, fractionSize) {
  20334. if (isUndefined(currencySymbol)) {
  20335. currencySymbol = formats.CURRENCY_SYM;
  20336. }
  20337. if (isUndefined(fractionSize)) {
  20338. fractionSize = formats.PATTERNS[1].maxFrac;
  20339. }
  20340. // If the currency symbol is empty, trim whitespace around the symbol
  20341. var currencySymbolRe = !currencySymbol ? /\s*\u00A4\s*/g : /\u00A4/g;
  20342. // if null or undefined pass it through
  20343. return (amount == null)
  20344. ? amount
  20345. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  20346. replace(currencySymbolRe, currencySymbol);
  20347. };
  20348. }
  20349. /**
  20350. * @ngdoc filter
  20351. * @name number
  20352. * @kind function
  20353. *
  20354. * @description
  20355. * Formats a number as text.
  20356. *
  20357. * If the input is null or undefined, it will just be returned.
  20358. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  20359. * If the input is not a number an empty string is returned.
  20360. *
  20361. *
  20362. * @param {number|string} number Number to format.
  20363. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  20364. * If this is not provided then the fraction size is computed from the current locale's number
  20365. * formatting pattern. In the case of the default locale, it will be 3.
  20366. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  20367. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  20368. * include "," group separators after each third digit).
  20369. *
  20370. * @example
  20371. <example module="numberFilterExample" name="number-filter">
  20372. <file name="index.html">
  20373. <script>
  20374. angular.module('numberFilterExample', [])
  20375. .controller('ExampleController', ['$scope', function($scope) {
  20376. $scope.val = 1234.56789;
  20377. }]);
  20378. </script>
  20379. <div ng-controller="ExampleController">
  20380. <label>Enter number: <input ng-model='val'></label><br>
  20381. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  20382. No fractions: <span>{{val | number:0}}</span><br>
  20383. Negative number: <span>{{-val | number:4}}</span>
  20384. </div>
  20385. </file>
  20386. <file name="protractor.js" type="protractor">
  20387. it('should format numbers', function() {
  20388. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  20389. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  20390. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  20391. });
  20392. it('should update', function() {
  20393. element(by.model('val')).clear();
  20394. element(by.model('val')).sendKeys('3374.333');
  20395. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  20396. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  20397. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  20398. });
  20399. </file>
  20400. </example>
  20401. */
  20402. numberFilter.$inject = ['$locale'];
  20403. function numberFilter($locale) {
  20404. var formats = $locale.NUMBER_FORMATS;
  20405. return function(number, fractionSize) {
  20406. // if null or undefined pass it through
  20407. return (number == null)
  20408. ? number
  20409. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  20410. fractionSize);
  20411. };
  20412. }
  20413. /**
  20414. * Parse a number (as a string) into three components that can be used
  20415. * for formatting the number.
  20416. *
  20417. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  20418. *
  20419. * @param {string} numStr The number to parse
  20420. * @return {object} An object describing this number, containing the following keys:
  20421. * - d : an array of digits containing leading zeros as necessary
  20422. * - i : the number of the digits in `d` that are to the left of the decimal point
  20423. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  20424. *
  20425. */
  20426. function parse(numStr) {
  20427. var exponent = 0, digits, numberOfIntegerDigits;
  20428. var i, j, zeros;
  20429. // Decimal point?
  20430. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  20431. numStr = numStr.replace(DECIMAL_SEP, '');
  20432. }
  20433. // Exponential form?
  20434. if ((i = numStr.search(/e/i)) > 0) {
  20435. // Work out the exponent.
  20436. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  20437. numberOfIntegerDigits += +numStr.slice(i + 1);
  20438. numStr = numStr.substring(0, i);
  20439. } else if (numberOfIntegerDigits < 0) {
  20440. // There was no decimal point or exponent so it is an integer.
  20441. numberOfIntegerDigits = numStr.length;
  20442. }
  20443. // Count the number of leading zeros.
  20444. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
  20445. if (i === (zeros = numStr.length)) {
  20446. // The digits are all zero.
  20447. digits = [0];
  20448. numberOfIntegerDigits = 1;
  20449. } else {
  20450. // Count the number of trailing zeros
  20451. zeros--;
  20452. while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
  20453. // Trailing zeros are insignificant so ignore them
  20454. numberOfIntegerDigits -= i;
  20455. digits = [];
  20456. // Convert string to array of digits without leading/trailing zeros.
  20457. for (j = 0; i <= zeros; i++, j++) {
  20458. digits[j] = +numStr.charAt(i);
  20459. }
  20460. }
  20461. // If the number overflows the maximum allowed digits then use an exponent.
  20462. if (numberOfIntegerDigits > MAX_DIGITS) {
  20463. digits = digits.splice(0, MAX_DIGITS - 1);
  20464. exponent = numberOfIntegerDigits - 1;
  20465. numberOfIntegerDigits = 1;
  20466. }
  20467. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  20468. }
  20469. /**
  20470. * Round the parsed number to the specified number of decimal places
  20471. * This function changed the parsedNumber in-place
  20472. */
  20473. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  20474. var digits = parsedNumber.d;
  20475. var fractionLen = digits.length - parsedNumber.i;
  20476. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  20477. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  20478. // The index of the digit to where rounding is to occur
  20479. var roundAt = fractionSize + parsedNumber.i;
  20480. var digit = digits[roundAt];
  20481. if (roundAt > 0) {
  20482. // Drop fractional digits beyond `roundAt`
  20483. digits.splice(Math.max(parsedNumber.i, roundAt));
  20484. // Set non-fractional digits beyond `roundAt` to 0
  20485. for (var j = roundAt; j < digits.length; j++) {
  20486. digits[j] = 0;
  20487. }
  20488. } else {
  20489. // We rounded to zero so reset the parsedNumber
  20490. fractionLen = Math.max(0, fractionLen);
  20491. parsedNumber.i = 1;
  20492. digits.length = Math.max(1, roundAt = fractionSize + 1);
  20493. digits[0] = 0;
  20494. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  20495. }
  20496. if (digit >= 5) {
  20497. if (roundAt - 1 < 0) {
  20498. for (var k = 0; k > roundAt; k--) {
  20499. digits.unshift(0);
  20500. parsedNumber.i++;
  20501. }
  20502. digits.unshift(1);
  20503. parsedNumber.i++;
  20504. } else {
  20505. digits[roundAt - 1]++;
  20506. }
  20507. }
  20508. // Pad out with zeros to get the required fraction length
  20509. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  20510. // Do any carrying, e.g. a digit was rounded up to 10
  20511. var carry = digits.reduceRight(function(carry, d, i, digits) {
  20512. d = d + carry;
  20513. digits[i] = d % 10;
  20514. return Math.floor(d / 10);
  20515. }, 0);
  20516. if (carry) {
  20517. digits.unshift(carry);
  20518. parsedNumber.i++;
  20519. }
  20520. }
  20521. /**
  20522. * Format a number into a string
  20523. * @param {number} number The number to format
  20524. * @param {{
  20525. * minFrac, // the minimum number of digits required in the fraction part of the number
  20526. * maxFrac, // the maximum number of digits required in the fraction part of the number
  20527. * gSize, // number of digits in each group of separated digits
  20528. * lgSize, // number of digits in the last group of digits before the decimal separator
  20529. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  20530. * posPre, // the string to go in front of a positive number
  20531. * negSuf, // the string to go after a negative number (e.g. `)`)
  20532. * posSuf // the string to go after a positive number
  20533. * }} pattern
  20534. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  20535. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  20536. * @param {[type]} fractionSize The size of the fractional part of the number
  20537. * @return {string} The number formatted as a string
  20538. */
  20539. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  20540. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  20541. var isInfinity = !isFinite(number);
  20542. var isZero = false;
  20543. var numStr = Math.abs(number) + '',
  20544. formattedText = '',
  20545. parsedNumber;
  20546. if (isInfinity) {
  20547. formattedText = '\u221e';
  20548. } else {
  20549. parsedNumber = parse(numStr);
  20550. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  20551. var digits = parsedNumber.d;
  20552. var integerLen = parsedNumber.i;
  20553. var exponent = parsedNumber.e;
  20554. var decimals = [];
  20555. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  20556. // pad zeros for small numbers
  20557. while (integerLen < 0) {
  20558. digits.unshift(0);
  20559. integerLen++;
  20560. }
  20561. // extract decimals digits
  20562. if (integerLen > 0) {
  20563. decimals = digits.splice(integerLen, digits.length);
  20564. } else {
  20565. decimals = digits;
  20566. digits = [0];
  20567. }
  20568. // format the integer digits with grouping separators
  20569. var groups = [];
  20570. if (digits.length >= pattern.lgSize) {
  20571. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  20572. }
  20573. while (digits.length > pattern.gSize) {
  20574. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  20575. }
  20576. if (digits.length) {
  20577. groups.unshift(digits.join(''));
  20578. }
  20579. formattedText = groups.join(groupSep);
  20580. // append the decimal digits
  20581. if (decimals.length) {
  20582. formattedText += decimalSep + decimals.join('');
  20583. }
  20584. if (exponent) {
  20585. formattedText += 'e+' + exponent;
  20586. }
  20587. }
  20588. if (number < 0 && !isZero) {
  20589. return pattern.negPre + formattedText + pattern.negSuf;
  20590. } else {
  20591. return pattern.posPre + formattedText + pattern.posSuf;
  20592. }
  20593. }
  20594. function padNumber(num, digits, trim, negWrap) {
  20595. var neg = '';
  20596. if (num < 0 || (negWrap && num <= 0)) {
  20597. if (negWrap) {
  20598. num = -num + 1;
  20599. } else {
  20600. num = -num;
  20601. neg = '-';
  20602. }
  20603. }
  20604. num = '' + num;
  20605. while (num.length < digits) num = ZERO_CHAR + num;
  20606. if (trim) {
  20607. num = num.substr(num.length - digits);
  20608. }
  20609. return neg + num;
  20610. }
  20611. function dateGetter(name, size, offset, trim, negWrap) {
  20612. offset = offset || 0;
  20613. return function(date) {
  20614. var value = date['get' + name]();
  20615. if (offset > 0 || value > -offset) {
  20616. value += offset;
  20617. }
  20618. if (value === 0 && offset === -12) value = 12;
  20619. return padNumber(value, size, trim, negWrap);
  20620. };
  20621. }
  20622. function dateStrGetter(name, shortForm, standAlone) {
  20623. return function(date, formats) {
  20624. var value = date['get' + name]();
  20625. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  20626. var get = uppercase(propPrefix + name);
  20627. return formats[get][value];
  20628. };
  20629. }
  20630. function timeZoneGetter(date, formats, offset) {
  20631. var zone = -1 * offset;
  20632. var paddedZone = (zone >= 0) ? '+' : '';
  20633. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  20634. padNumber(Math.abs(zone % 60), 2);
  20635. return paddedZone;
  20636. }
  20637. function getFirstThursdayOfYear(year) {
  20638. // 0 = index of January
  20639. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  20640. // 4 = index of Thursday (+1 to account for 1st = 5)
  20641. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  20642. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  20643. }
  20644. function getThursdayThisWeek(datetime) {
  20645. return new Date(datetime.getFullYear(), datetime.getMonth(),
  20646. // 4 = index of Thursday
  20647. datetime.getDate() + (4 - datetime.getDay()));
  20648. }
  20649. function weekGetter(size) {
  20650. return function(date) {
  20651. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  20652. thisThurs = getThursdayThisWeek(date);
  20653. var diff = +thisThurs - +firstThurs,
  20654. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  20655. return padNumber(result, size);
  20656. };
  20657. }
  20658. function ampmGetter(date, formats) {
  20659. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  20660. }
  20661. function eraGetter(date, formats) {
  20662. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  20663. }
  20664. function longEraGetter(date, formats) {
  20665. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  20666. }
  20667. var DATE_FORMATS = {
  20668. yyyy: dateGetter('FullYear', 4, 0, false, true),
  20669. yy: dateGetter('FullYear', 2, 0, true, true),
  20670. y: dateGetter('FullYear', 1, 0, false, true),
  20671. MMMM: dateStrGetter('Month'),
  20672. MMM: dateStrGetter('Month', true),
  20673. MM: dateGetter('Month', 2, 1),
  20674. M: dateGetter('Month', 1, 1),
  20675. LLLL: dateStrGetter('Month', false, true),
  20676. dd: dateGetter('Date', 2),
  20677. d: dateGetter('Date', 1),
  20678. HH: dateGetter('Hours', 2),
  20679. H: dateGetter('Hours', 1),
  20680. hh: dateGetter('Hours', 2, -12),
  20681. h: dateGetter('Hours', 1, -12),
  20682. mm: dateGetter('Minutes', 2),
  20683. m: dateGetter('Minutes', 1),
  20684. ss: dateGetter('Seconds', 2),
  20685. s: dateGetter('Seconds', 1),
  20686. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  20687. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  20688. sss: dateGetter('Milliseconds', 3),
  20689. EEEE: dateStrGetter('Day'),
  20690. EEE: dateStrGetter('Day', true),
  20691. a: ampmGetter,
  20692. Z: timeZoneGetter,
  20693. ww: weekGetter(2),
  20694. w: weekGetter(1),
  20695. G: eraGetter,
  20696. GG: eraGetter,
  20697. GGG: eraGetter,
  20698. GGGG: longEraGetter
  20699. };
  20700. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\s\S]*)/,
  20701. NUMBER_STRING = /^-?\d+$/;
  20702. /**
  20703. * @ngdoc filter
  20704. * @name date
  20705. * @kind function
  20706. *
  20707. * @description
  20708. * Formats `date` to a string based on the requested `format`.
  20709. *
  20710. * `format` string can be composed of the following elements:
  20711. *
  20712. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  20713. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  20714. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  20715. * * `'MMMM'`: Month in year (January-December)
  20716. * * `'MMM'`: Month in year (Jan-Dec)
  20717. * * `'MM'`: Month in year, padded (01-12)
  20718. * * `'M'`: Month in year (1-12)
  20719. * * `'LLLL'`: Stand-alone month in year (January-December)
  20720. * * `'dd'`: Day in month, padded (01-31)
  20721. * * `'d'`: Day in month (1-31)
  20722. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  20723. * * `'EEE'`: Day in Week, (Sun-Sat)
  20724. * * `'HH'`: Hour in day, padded (00-23)
  20725. * * `'H'`: Hour in day (0-23)
  20726. * * `'hh'`: Hour in AM/PM, padded (01-12)
  20727. * * `'h'`: Hour in AM/PM, (1-12)
  20728. * * `'mm'`: Minute in hour, padded (00-59)
  20729. * * `'m'`: Minute in hour (0-59)
  20730. * * `'ss'`: Second in minute, padded (00-59)
  20731. * * `'s'`: Second in minute (0-59)
  20732. * * `'sss'`: Millisecond in second, padded (000-999)
  20733. * * `'a'`: AM/PM marker
  20734. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  20735. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  20736. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  20737. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  20738. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  20739. *
  20740. * `format` string can also be one of the following predefined
  20741. * {@link guide/i18n localizable formats}:
  20742. *
  20743. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  20744. * (e.g. Sep 3, 2010 12:05:08 PM)
  20745. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  20746. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  20747. * (e.g. Friday, September 3, 2010)
  20748. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  20749. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  20750. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  20751. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  20752. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  20753. *
  20754. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  20755. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  20756. * (e.g. `"h 'o''clock'"`).
  20757. *
  20758. * Any other characters in the `format` string will be output as-is.
  20759. *
  20760. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  20761. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  20762. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  20763. * specified in the string input, the time is considered to be in the local timezone.
  20764. * @param {string=} format Formatting rules (see Description). If not specified,
  20765. * `mediumDate` is used.
  20766. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  20767. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  20768. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  20769. * If not specified, the timezone of the browser will be used.
  20770. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  20771. *
  20772. * @example
  20773. <example name="filter-date">
  20774. <file name="index.html">
  20775. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  20776. <span>{{1288323623006 | date:'medium'}}</span><br>
  20777. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  20778. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  20779. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  20780. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  20781. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  20782. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  20783. </file>
  20784. <file name="protractor.js" type="protractor">
  20785. it('should format date', function() {
  20786. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  20787. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  20788. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  20789. toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
  20790. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  20791. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  20792. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  20793. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  20794. });
  20795. </file>
  20796. </example>
  20797. */
  20798. dateFilter.$inject = ['$locale'];
  20799. function dateFilter($locale) {
  20800. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  20801. // 1 2 3 4 5 6 7 8 9 10 11
  20802. function jsonStringToDate(string) {
  20803. var match;
  20804. if ((match = string.match(R_ISO8601_STR))) {
  20805. var date = new Date(0),
  20806. tzHour = 0,
  20807. tzMin = 0,
  20808. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  20809. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  20810. if (match[9]) {
  20811. tzHour = toInt(match[9] + match[10]);
  20812. tzMin = toInt(match[9] + match[11]);
  20813. }
  20814. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  20815. var h = toInt(match[4] || 0) - tzHour;
  20816. var m = toInt(match[5] || 0) - tzMin;
  20817. var s = toInt(match[6] || 0);
  20818. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  20819. timeSetter.call(date, h, m, s, ms);
  20820. return date;
  20821. }
  20822. return string;
  20823. }
  20824. return function(date, format, timezone) {
  20825. var text = '',
  20826. parts = [],
  20827. fn, match;
  20828. format = format || 'mediumDate';
  20829. format = $locale.DATETIME_FORMATS[format] || format;
  20830. if (isString(date)) {
  20831. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  20832. }
  20833. if (isNumber(date)) {
  20834. date = new Date(date);
  20835. }
  20836. if (!isDate(date) || !isFinite(date.getTime())) {
  20837. return date;
  20838. }
  20839. while (format) {
  20840. match = DATE_FORMATS_SPLIT.exec(format);
  20841. if (match) {
  20842. parts = concat(parts, match, 1);
  20843. format = parts.pop();
  20844. } else {
  20845. parts.push(format);
  20846. format = null;
  20847. }
  20848. }
  20849. var dateTimezoneOffset = date.getTimezoneOffset();
  20850. if (timezone) {
  20851. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  20852. date = convertTimezoneToLocal(date, timezone, true);
  20853. }
  20854. forEach(parts, function(value) {
  20855. fn = DATE_FORMATS[value];
  20856. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  20857. : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
  20858. });
  20859. return text;
  20860. };
  20861. }
  20862. /**
  20863. * @ngdoc filter
  20864. * @name json
  20865. * @kind function
  20866. *
  20867. * @description
  20868. * Allows you to convert a JavaScript object into JSON string.
  20869. *
  20870. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  20871. * the binding is automatically converted to JSON.
  20872. *
  20873. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  20874. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  20875. * @returns {string} JSON string.
  20876. *
  20877. *
  20878. * @example
  20879. <example name="filter-json">
  20880. <file name="index.html">
  20881. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  20882. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  20883. </file>
  20884. <file name="protractor.js" type="protractor">
  20885. it('should jsonify filtered objects', function() {
  20886. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
  20887. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
  20888. });
  20889. </file>
  20890. </example>
  20891. *
  20892. */
  20893. function jsonFilter() {
  20894. return function(object, spacing) {
  20895. if (isUndefined(spacing)) {
  20896. spacing = 2;
  20897. }
  20898. return toJson(object, spacing);
  20899. };
  20900. }
  20901. /**
  20902. * @ngdoc filter
  20903. * @name lowercase
  20904. * @kind function
  20905. * @description
  20906. * Converts string to lowercase.
  20907. *
  20908. * See the {@link ng.uppercase uppercase filter documentation} for a functionally identical example.
  20909. *
  20910. * @see angular.lowercase
  20911. */
  20912. var lowercaseFilter = valueFn(lowercase);
  20913. /**
  20914. * @ngdoc filter
  20915. * @name uppercase
  20916. * @kind function
  20917. * @description
  20918. * Converts string to uppercase.
  20919. * @example
  20920. <example module="uppercaseFilterExample" name="filter-uppercase">
  20921. <file name="index.html">
  20922. <script>
  20923. angular.module('uppercaseFilterExample', [])
  20924. .controller('ExampleController', ['$scope', function($scope) {
  20925. $scope.title = 'This is a title';
  20926. }]);
  20927. </script>
  20928. <div ng-controller="ExampleController">
  20929. <!-- This title should be formatted normally -->
  20930. <h1>{{title}}</h1>
  20931. <!-- This title should be capitalized -->
  20932. <h1>{{title | uppercase}}</h1>
  20933. </div>
  20934. </file>
  20935. </example>
  20936. */
  20937. var uppercaseFilter = valueFn(uppercase);
  20938. /**
  20939. * @ngdoc filter
  20940. * @name limitTo
  20941. * @kind function
  20942. *
  20943. * @description
  20944. * Creates a new array or string containing only a specified number of elements. The elements are
  20945. * taken from either the beginning or the end of the source array, string or number, as specified by
  20946. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  20947. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  20948. * it is converted to a string.
  20949. *
  20950. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  20951. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  20952. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  20953. * If the number is negative, `limit` number of items from the end of the source array/string
  20954. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  20955. * the input will be returned unchanged.
  20956. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  20957. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  20958. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  20959. * less than `limit` elements.
  20960. *
  20961. * @example
  20962. <example module="limitToExample" name="limit-to-filter">
  20963. <file name="index.html">
  20964. <script>
  20965. angular.module('limitToExample', [])
  20966. .controller('ExampleController', ['$scope', function($scope) {
  20967. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  20968. $scope.letters = "abcdefghi";
  20969. $scope.longNumber = 2345432342;
  20970. $scope.numLimit = 3;
  20971. $scope.letterLimit = 3;
  20972. $scope.longNumberLimit = 3;
  20973. }]);
  20974. </script>
  20975. <div ng-controller="ExampleController">
  20976. <label>
  20977. Limit {{numbers}} to:
  20978. <input type="number" step="1" ng-model="numLimit">
  20979. </label>
  20980. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  20981. <label>
  20982. Limit {{letters}} to:
  20983. <input type="number" step="1" ng-model="letterLimit">
  20984. </label>
  20985. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  20986. <label>
  20987. Limit {{longNumber}} to:
  20988. <input type="number" step="1" ng-model="longNumberLimit">
  20989. </label>
  20990. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  20991. </div>
  20992. </file>
  20993. <file name="protractor.js" type="protractor">
  20994. var numLimitInput = element(by.model('numLimit'));
  20995. var letterLimitInput = element(by.model('letterLimit'));
  20996. var longNumberLimitInput = element(by.model('longNumberLimit'));
  20997. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  20998. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  20999. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  21000. it('should limit the number array to first three items', function() {
  21001. expect(numLimitInput.getAttribute('value')).toBe('3');
  21002. expect(letterLimitInput.getAttribute('value')).toBe('3');
  21003. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  21004. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  21005. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  21006. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  21007. });
  21008. // There is a bug in safari and protractor that doesn't like the minus key
  21009. // it('should update the output when -3 is entered', function() {
  21010. // numLimitInput.clear();
  21011. // numLimitInput.sendKeys('-3');
  21012. // letterLimitInput.clear();
  21013. // letterLimitInput.sendKeys('-3');
  21014. // longNumberLimitInput.clear();
  21015. // longNumberLimitInput.sendKeys('-3');
  21016. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  21017. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  21018. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  21019. // });
  21020. it('should not exceed the maximum size of input array', function() {
  21021. numLimitInput.clear();
  21022. numLimitInput.sendKeys('100');
  21023. letterLimitInput.clear();
  21024. letterLimitInput.sendKeys('100');
  21025. longNumberLimitInput.clear();
  21026. longNumberLimitInput.sendKeys('100');
  21027. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  21028. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  21029. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  21030. });
  21031. </file>
  21032. </example>
  21033. */
  21034. function limitToFilter() {
  21035. return function(input, limit, begin) {
  21036. if (Math.abs(Number(limit)) === Infinity) {
  21037. limit = Number(limit);
  21038. } else {
  21039. limit = toInt(limit);
  21040. }
  21041. if (isNumberNaN(limit)) return input;
  21042. if (isNumber(input)) input = input.toString();
  21043. if (!isArrayLike(input)) return input;
  21044. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  21045. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  21046. if (limit >= 0) {
  21047. return sliceFn(input, begin, begin + limit);
  21048. } else {
  21049. if (begin === 0) {
  21050. return sliceFn(input, limit, input.length);
  21051. } else {
  21052. return sliceFn(input, Math.max(0, begin + limit), begin);
  21053. }
  21054. }
  21055. };
  21056. }
  21057. function sliceFn(input, begin, end) {
  21058. if (isString(input)) return input.slice(begin, end);
  21059. return slice.call(input, begin, end);
  21060. }
  21061. /**
  21062. * @ngdoc filter
  21063. * @name orderBy
  21064. * @kind function
  21065. *
  21066. * @description
  21067. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  21068. * function based on the values computed using the `expression` predicate.
  21069. *
  21070. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  21071. * `[{id: 'bar'}, {id: 'foo'}]`.
  21072. *
  21073. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  21074. * String, etc).
  21075. *
  21076. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  21077. * for the preceding one. The `expression` is evaluated against each item and the output is used
  21078. * for comparing with other items.
  21079. *
  21080. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  21081. * ascending order.
  21082. *
  21083. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  21084. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  21085. * strings alphabetically).
  21086. *
  21087. * ### Under the hood
  21088. *
  21089. * Ordering the specified `collection` happens in two phases:
  21090. *
  21091. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  21092. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  21093. * through a predicate that extracts the value of the `label` property, would be transformed to:
  21094. * ```
  21095. * {
  21096. * value: 'foo',
  21097. * type: 'string',
  21098. * index: ...
  21099. * }
  21100. * ```
  21101. * **Note:** `null` values use `'null'` as their type.
  21102. * 2. The comparator function is used to sort the items, based on the derived values, types and
  21103. * indices.
  21104. *
  21105. * If you use a custom comparator, it will be called with pairs of objects of the form
  21106. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  21107. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  21108. * second, or `1` otherwise.
  21109. *
  21110. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  21111. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  21112. * dummy predicate that returns the item's index as `value`.
  21113. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  21114. *
  21115. * If a custom comparator still can't distinguish between two items, then they will be sorted based
  21116. * on their index using the built-in comparator.
  21117. *
  21118. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  21119. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  21120. * it to the comparator. The following rules govern the conversion:
  21121. *
  21122. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  21123. * used instead.<br />
  21124. * (If the object has a `valueOf()` method that returns another object, then the returned object
  21125. * will be used in subsequent steps.)
  21126. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  21127. * returns a primitive, its return value will be used instead.<br />
  21128. * (If the object has a `toString()` method that returns another object, then the returned object
  21129. * will be used in subsequent steps.)
  21130. * 3. No conversion; the object itself is used.
  21131. *
  21132. * ### The default comparator
  21133. *
  21134. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  21135. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  21136. * using their index in the original collection, sorts values of different types by type and puts
  21137. * `undefined` and `null` values at the end of the sorted list.
  21138. *
  21139. * More specifically, it follows these steps to determine the relative order of items:
  21140. *
  21141. * 1. If the compared values are of different types:
  21142. * - If one of the values is undefined, consider it "greater than" the other.
  21143. * - Else if one of the values is null, consider it "greater than" the other.
  21144. * - Else compare the types themselves alphabetically.
  21145. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  21146. * locale-insensitive way.
  21147. * 3. If both values are objects, compare their indices instead.
  21148. * 4. Otherwise, return:
  21149. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  21150. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  21151. * - `1`, otherwise.
  21152. *
  21153. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  21154. * saved as numbers and not strings.
  21155. * **Note:** For the purpose of sorting, `null` and `undefined` are considered "greater than"
  21156. * any other value (with undefined "greater than" null). This effectively means that `null`
  21157. * and `undefined` values end up at the end of a list sorted in ascending order.
  21158. * **Note:** `null` values use `'null'` as their type to be able to distinguish them from objects.
  21159. *
  21160. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  21161. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  21162. * predicates) to be used by the comparator to determine the order of elements.
  21163. *
  21164. * Can be one of:
  21165. *
  21166. * - `Function`: A getter function. This function will be called with each item as argument and
  21167. * the return value will be used for sorting.
  21168. * - `string`: An AngularJS expression. This expression will be evaluated against each item and the
  21169. * result will be used for sorting. For example, use `'label'` to sort by a property called
  21170. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  21171. * property.<br />
  21172. * (The result of a constant expression is interpreted as a property name to be used for
  21173. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  21174. * property called `special name`.)<br />
  21175. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  21176. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  21177. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  21178. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  21179. * relative order of two items, the next predicate is used as a tie-breaker.
  21180. *
  21181. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  21182. *
  21183. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  21184. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  21185. * value pairs. If omitted, the built-in comparator will be used.
  21186. *
  21187. * @returns {Array} - The sorted array.
  21188. *
  21189. *
  21190. * @example
  21191. * ### Ordering a table with `ngRepeat`
  21192. *
  21193. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  21194. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  21195. * it defaults to the built-in comparator.
  21196. *
  21197. <example name="orderBy-static" module="orderByExample1">
  21198. <file name="index.html">
  21199. <div ng-controller="ExampleController">
  21200. <table class="friends">
  21201. <tr>
  21202. <th>Name</th>
  21203. <th>Phone Number</th>
  21204. <th>Age</th>
  21205. </tr>
  21206. <tr ng-repeat="friend in friends | orderBy:'-age'">
  21207. <td>{{friend.name}}</td>
  21208. <td>{{friend.phone}}</td>
  21209. <td>{{friend.age}}</td>
  21210. </tr>
  21211. </table>
  21212. </div>
  21213. </file>
  21214. <file name="script.js">
  21215. angular.module('orderByExample1', [])
  21216. .controller('ExampleController', ['$scope', function($scope) {
  21217. $scope.friends = [
  21218. {name: 'John', phone: '555-1212', age: 10},
  21219. {name: 'Mary', phone: '555-9876', age: 19},
  21220. {name: 'Mike', phone: '555-4321', age: 21},
  21221. {name: 'Adam', phone: '555-5678', age: 35},
  21222. {name: 'Julie', phone: '555-8765', age: 29}
  21223. ];
  21224. }]);
  21225. </file>
  21226. <file name="style.css">
  21227. .friends {
  21228. border-collapse: collapse;
  21229. }
  21230. .friends th {
  21231. border-bottom: 1px solid;
  21232. }
  21233. .friends td, .friends th {
  21234. border-left: 1px solid;
  21235. padding: 5px 10px;
  21236. }
  21237. .friends td:first-child, .friends th:first-child {
  21238. border-left: none;
  21239. }
  21240. </file>
  21241. <file name="protractor.js" type="protractor">
  21242. // Element locators
  21243. var names = element.all(by.repeater('friends').column('friend.name'));
  21244. it('should sort friends by age in reverse order', function() {
  21245. expect(names.get(0).getText()).toBe('Adam');
  21246. expect(names.get(1).getText()).toBe('Julie');
  21247. expect(names.get(2).getText()).toBe('Mike');
  21248. expect(names.get(3).getText()).toBe('Mary');
  21249. expect(names.get(4).getText()).toBe('John');
  21250. });
  21251. </file>
  21252. </example>
  21253. * <hr />
  21254. *
  21255. * @example
  21256. * ### Changing parameters dynamically
  21257. *
  21258. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  21259. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  21260. *
  21261. <example name="orderBy-dynamic" module="orderByExample2">
  21262. <file name="index.html">
  21263. <div ng-controller="ExampleController">
  21264. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  21265. <hr/>
  21266. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  21267. <hr/>
  21268. <table class="friends">
  21269. <tr>
  21270. <th>
  21271. <button ng-click="sortBy('name')">Name</button>
  21272. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  21273. </th>
  21274. <th>
  21275. <button ng-click="sortBy('phone')">Phone Number</button>
  21276. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  21277. </th>
  21278. <th>
  21279. <button ng-click="sortBy('age')">Age</button>
  21280. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  21281. </th>
  21282. </tr>
  21283. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  21284. <td>{{friend.name}}</td>
  21285. <td>{{friend.phone}}</td>
  21286. <td>{{friend.age}}</td>
  21287. </tr>
  21288. </table>
  21289. </div>
  21290. </file>
  21291. <file name="script.js">
  21292. angular.module('orderByExample2', [])
  21293. .controller('ExampleController', ['$scope', function($scope) {
  21294. var friends = [
  21295. {name: 'John', phone: '555-1212', age: 10},
  21296. {name: 'Mary', phone: '555-9876', age: 19},
  21297. {name: 'Mike', phone: '555-4321', age: 21},
  21298. {name: 'Adam', phone: '555-5678', age: 35},
  21299. {name: 'Julie', phone: '555-8765', age: 29}
  21300. ];
  21301. $scope.propertyName = 'age';
  21302. $scope.reverse = true;
  21303. $scope.friends = friends;
  21304. $scope.sortBy = function(propertyName) {
  21305. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  21306. $scope.propertyName = propertyName;
  21307. };
  21308. }]);
  21309. </file>
  21310. <file name="style.css">
  21311. .friends {
  21312. border-collapse: collapse;
  21313. }
  21314. .friends th {
  21315. border-bottom: 1px solid;
  21316. }
  21317. .friends td, .friends th {
  21318. border-left: 1px solid;
  21319. padding: 5px 10px;
  21320. }
  21321. .friends td:first-child, .friends th:first-child {
  21322. border-left: none;
  21323. }
  21324. .sortorder:after {
  21325. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  21326. }
  21327. .sortorder.reverse:after {
  21328. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  21329. }
  21330. </file>
  21331. <file name="protractor.js" type="protractor">
  21332. // Element locators
  21333. var unsortButton = element(by.partialButtonText('unsorted'));
  21334. var nameHeader = element(by.partialButtonText('Name'));
  21335. var phoneHeader = element(by.partialButtonText('Phone'));
  21336. var ageHeader = element(by.partialButtonText('Age'));
  21337. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  21338. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  21339. it('should sort friends by some property, when clicking on the column header', function() {
  21340. expect(firstName.getText()).toBe('Adam');
  21341. expect(lastName.getText()).toBe('John');
  21342. phoneHeader.click();
  21343. expect(firstName.getText()).toBe('John');
  21344. expect(lastName.getText()).toBe('Mary');
  21345. nameHeader.click();
  21346. expect(firstName.getText()).toBe('Adam');
  21347. expect(lastName.getText()).toBe('Mike');
  21348. ageHeader.click();
  21349. expect(firstName.getText()).toBe('John');
  21350. expect(lastName.getText()).toBe('Adam');
  21351. });
  21352. it('should sort friends in reverse order, when clicking on the same column', function() {
  21353. expect(firstName.getText()).toBe('Adam');
  21354. expect(lastName.getText()).toBe('John');
  21355. ageHeader.click();
  21356. expect(firstName.getText()).toBe('John');
  21357. expect(lastName.getText()).toBe('Adam');
  21358. ageHeader.click();
  21359. expect(firstName.getText()).toBe('Adam');
  21360. expect(lastName.getText()).toBe('John');
  21361. });
  21362. it('should restore the original order, when clicking "Set to unsorted"', function() {
  21363. expect(firstName.getText()).toBe('Adam');
  21364. expect(lastName.getText()).toBe('John');
  21365. unsortButton.click();
  21366. expect(firstName.getText()).toBe('John');
  21367. expect(lastName.getText()).toBe('Julie');
  21368. });
  21369. </file>
  21370. </example>
  21371. * <hr />
  21372. *
  21373. * @example
  21374. * ### Using `orderBy` inside a controller
  21375. *
  21376. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  21377. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  21378. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  21379. *
  21380. <example name="orderBy-call-manually" module="orderByExample3">
  21381. <file name="index.html">
  21382. <div ng-controller="ExampleController">
  21383. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  21384. <hr/>
  21385. <button ng-click="sortBy(null)">Set to unsorted</button>
  21386. <hr/>
  21387. <table class="friends">
  21388. <tr>
  21389. <th>
  21390. <button ng-click="sortBy('name')">Name</button>
  21391. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  21392. </th>
  21393. <th>
  21394. <button ng-click="sortBy('phone')">Phone Number</button>
  21395. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  21396. </th>
  21397. <th>
  21398. <button ng-click="sortBy('age')">Age</button>
  21399. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  21400. </th>
  21401. </tr>
  21402. <tr ng-repeat="friend in friends">
  21403. <td>{{friend.name}}</td>
  21404. <td>{{friend.phone}}</td>
  21405. <td>{{friend.age}}</td>
  21406. </tr>
  21407. </table>
  21408. </div>
  21409. </file>
  21410. <file name="script.js">
  21411. angular.module('orderByExample3', [])
  21412. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  21413. var friends = [
  21414. {name: 'John', phone: '555-1212', age: 10},
  21415. {name: 'Mary', phone: '555-9876', age: 19},
  21416. {name: 'Mike', phone: '555-4321', age: 21},
  21417. {name: 'Adam', phone: '555-5678', age: 35},
  21418. {name: 'Julie', phone: '555-8765', age: 29}
  21419. ];
  21420. $scope.propertyName = 'age';
  21421. $scope.reverse = true;
  21422. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  21423. $scope.sortBy = function(propertyName) {
  21424. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  21425. ? !$scope.reverse : false;
  21426. $scope.propertyName = propertyName;
  21427. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  21428. };
  21429. }]);
  21430. </file>
  21431. <file name="style.css">
  21432. .friends {
  21433. border-collapse: collapse;
  21434. }
  21435. .friends th {
  21436. border-bottom: 1px solid;
  21437. }
  21438. .friends td, .friends th {
  21439. border-left: 1px solid;
  21440. padding: 5px 10px;
  21441. }
  21442. .friends td:first-child, .friends th:first-child {
  21443. border-left: none;
  21444. }
  21445. .sortorder:after {
  21446. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  21447. }
  21448. .sortorder.reverse:after {
  21449. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  21450. }
  21451. </file>
  21452. <file name="protractor.js" type="protractor">
  21453. // Element locators
  21454. var unsortButton = element(by.partialButtonText('unsorted'));
  21455. var nameHeader = element(by.partialButtonText('Name'));
  21456. var phoneHeader = element(by.partialButtonText('Phone'));
  21457. var ageHeader = element(by.partialButtonText('Age'));
  21458. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  21459. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  21460. it('should sort friends by some property, when clicking on the column header', function() {
  21461. expect(firstName.getText()).toBe('Adam');
  21462. expect(lastName.getText()).toBe('John');
  21463. phoneHeader.click();
  21464. expect(firstName.getText()).toBe('John');
  21465. expect(lastName.getText()).toBe('Mary');
  21466. nameHeader.click();
  21467. expect(firstName.getText()).toBe('Adam');
  21468. expect(lastName.getText()).toBe('Mike');
  21469. ageHeader.click();
  21470. expect(firstName.getText()).toBe('John');
  21471. expect(lastName.getText()).toBe('Adam');
  21472. });
  21473. it('should sort friends in reverse order, when clicking on the same column', function() {
  21474. expect(firstName.getText()).toBe('Adam');
  21475. expect(lastName.getText()).toBe('John');
  21476. ageHeader.click();
  21477. expect(firstName.getText()).toBe('John');
  21478. expect(lastName.getText()).toBe('Adam');
  21479. ageHeader.click();
  21480. expect(firstName.getText()).toBe('Adam');
  21481. expect(lastName.getText()).toBe('John');
  21482. });
  21483. it('should restore the original order, when clicking "Set to unsorted"', function() {
  21484. expect(firstName.getText()).toBe('Adam');
  21485. expect(lastName.getText()).toBe('John');
  21486. unsortButton.click();
  21487. expect(firstName.getText()).toBe('John');
  21488. expect(lastName.getText()).toBe('Julie');
  21489. });
  21490. </file>
  21491. </example>
  21492. * <hr />
  21493. *
  21494. * @example
  21495. * ### Using a custom comparator
  21496. *
  21497. * If you have very specific requirements about the way items are sorted, you can pass your own
  21498. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  21499. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  21500. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  21501. *
  21502. <example name="orderBy-custom-comparator" module="orderByExample4">
  21503. <file name="index.html">
  21504. <div ng-controller="ExampleController">
  21505. <div class="friends-container custom-comparator">
  21506. <h3>Locale-sensitive Comparator</h3>
  21507. <table class="friends">
  21508. <tr>
  21509. <th>Name</th>
  21510. <th>Favorite Letter</th>
  21511. </tr>
  21512. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  21513. <td>{{friend.name}}</td>
  21514. <td>{{friend.favoriteLetter}}</td>
  21515. </tr>
  21516. </table>
  21517. </div>
  21518. <div class="friends-container default-comparator">
  21519. <h3>Default Comparator</h3>
  21520. <table class="friends">
  21521. <tr>
  21522. <th>Name</th>
  21523. <th>Favorite Letter</th>
  21524. </tr>
  21525. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  21526. <td>{{friend.name}}</td>
  21527. <td>{{friend.favoriteLetter}}</td>
  21528. </tr>
  21529. </table>
  21530. </div>
  21531. </div>
  21532. </file>
  21533. <file name="script.js">
  21534. angular.module('orderByExample4', [])
  21535. .controller('ExampleController', ['$scope', function($scope) {
  21536. $scope.friends = [
  21537. {name: 'John', favoriteLetter: 'Ä'},
  21538. {name: 'Mary', favoriteLetter: 'Ü'},
  21539. {name: 'Mike', favoriteLetter: 'Ö'},
  21540. {name: 'Adam', favoriteLetter: 'H'},
  21541. {name: 'Julie', favoriteLetter: 'Z'}
  21542. ];
  21543. $scope.localeSensitiveComparator = function(v1, v2) {
  21544. // If we don't get strings, just compare by index
  21545. if (v1.type !== 'string' || v2.type !== 'string') {
  21546. return (v1.index < v2.index) ? -1 : 1;
  21547. }
  21548. // Compare strings alphabetically, taking locale into account
  21549. return v1.value.localeCompare(v2.value);
  21550. };
  21551. }]);
  21552. </file>
  21553. <file name="style.css">
  21554. .friends-container {
  21555. display: inline-block;
  21556. margin: 0 30px;
  21557. }
  21558. .friends {
  21559. border-collapse: collapse;
  21560. }
  21561. .friends th {
  21562. border-bottom: 1px solid;
  21563. }
  21564. .friends td, .friends th {
  21565. border-left: 1px solid;
  21566. padding: 5px 10px;
  21567. }
  21568. .friends td:first-child, .friends th:first-child {
  21569. border-left: none;
  21570. }
  21571. </file>
  21572. <file name="protractor.js" type="protractor">
  21573. // Element locators
  21574. var container = element(by.css('.custom-comparator'));
  21575. var names = container.all(by.repeater('friends').column('friend.name'));
  21576. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  21577. expect(names.get(0).getText()).toBe('John');
  21578. expect(names.get(1).getText()).toBe('Adam');
  21579. expect(names.get(2).getText()).toBe('Mike');
  21580. expect(names.get(3).getText()).toBe('Mary');
  21581. expect(names.get(4).getText()).toBe('Julie');
  21582. });
  21583. </file>
  21584. </example>
  21585. *
  21586. */
  21587. orderByFilter.$inject = ['$parse'];
  21588. function orderByFilter($parse) {
  21589. return function(array, sortPredicate, reverseOrder, compareFn) {
  21590. if (array == null) return array;
  21591. if (!isArrayLike(array)) {
  21592. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  21593. }
  21594. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  21595. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  21596. var predicates = processPredicates(sortPredicate);
  21597. var descending = reverseOrder ? -1 : 1;
  21598. // Define the `compare()` function. Use a default comparator if none is specified.
  21599. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  21600. // The next three lines are a version of a Swartzian Transform idiom from Perl
  21601. // (sometimes called the Decorate-Sort-Undecorate idiom)
  21602. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  21603. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  21604. compareValues.sort(doComparison);
  21605. array = compareValues.map(function(item) { return item.value; });
  21606. return array;
  21607. function getComparisonObject(value, index) {
  21608. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  21609. // This will be used to keep the sort stable when none of the input predicates can
  21610. // distinguish between two elements.
  21611. return {
  21612. value: value,
  21613. tieBreaker: {value: index, type: 'number', index: index},
  21614. predicateValues: predicates.map(function(predicate) {
  21615. return getPredicateValue(predicate.get(value), index);
  21616. })
  21617. };
  21618. }
  21619. function doComparison(v1, v2) {
  21620. for (var i = 0, ii = predicates.length; i < ii; i++) {
  21621. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  21622. if (result) {
  21623. return result * predicates[i].descending * descending;
  21624. }
  21625. }
  21626. return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending;
  21627. }
  21628. };
  21629. function processPredicates(sortPredicates) {
  21630. return sortPredicates.map(function(predicate) {
  21631. var descending = 1, get = identity;
  21632. if (isFunction(predicate)) {
  21633. get = predicate;
  21634. } else if (isString(predicate)) {
  21635. if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
  21636. descending = predicate.charAt(0) === '-' ? -1 : 1;
  21637. predicate = predicate.substring(1);
  21638. }
  21639. if (predicate !== '') {
  21640. get = $parse(predicate);
  21641. if (get.constant) {
  21642. var key = get();
  21643. get = function(value) { return value[key]; };
  21644. }
  21645. }
  21646. }
  21647. return {get: get, descending: descending};
  21648. });
  21649. }
  21650. function isPrimitive(value) {
  21651. switch (typeof value) {
  21652. case 'number': /* falls through */
  21653. case 'boolean': /* falls through */
  21654. case 'string':
  21655. return true;
  21656. default:
  21657. return false;
  21658. }
  21659. }
  21660. function objectValue(value) {
  21661. // If `valueOf` is a valid function use that
  21662. if (isFunction(value.valueOf)) {
  21663. value = value.valueOf();
  21664. if (isPrimitive(value)) return value;
  21665. }
  21666. // If `toString` is a valid function and not the one from `Object.prototype` use that
  21667. if (hasCustomToString(value)) {
  21668. value = value.toString();
  21669. if (isPrimitive(value)) return value;
  21670. }
  21671. return value;
  21672. }
  21673. function getPredicateValue(value, index) {
  21674. var type = typeof value;
  21675. if (value === null) {
  21676. type = 'null';
  21677. } else if (type === 'object') {
  21678. value = objectValue(value);
  21679. }
  21680. return {value: value, type: type, index: index};
  21681. }
  21682. function defaultCompare(v1, v2) {
  21683. var result = 0;
  21684. var type1 = v1.type;
  21685. var type2 = v2.type;
  21686. if (type1 === type2) {
  21687. var value1 = v1.value;
  21688. var value2 = v2.value;
  21689. if (type1 === 'string') {
  21690. // Compare strings case-insensitively
  21691. value1 = value1.toLowerCase();
  21692. value2 = value2.toLowerCase();
  21693. } else if (type1 === 'object') {
  21694. // For basic objects, use the position of the object
  21695. // in the collection instead of the value
  21696. if (isObject(value1)) value1 = v1.index;
  21697. if (isObject(value2)) value2 = v2.index;
  21698. }
  21699. if (value1 !== value2) {
  21700. result = value1 < value2 ? -1 : 1;
  21701. }
  21702. } else {
  21703. result = (type1 === 'undefined') ? 1 :
  21704. (type2 === 'undefined') ? -1 :
  21705. (type1 === 'null') ? 1 :
  21706. (type2 === 'null') ? -1 :
  21707. (type1 < type2) ? -1 : 1;
  21708. }
  21709. return result;
  21710. }
  21711. }
  21712. function ngDirective(directive) {
  21713. if (isFunction(directive)) {
  21714. directive = {
  21715. link: directive
  21716. };
  21717. }
  21718. directive.restrict = directive.restrict || 'AC';
  21719. return valueFn(directive);
  21720. }
  21721. /**
  21722. * @ngdoc directive
  21723. * @name a
  21724. * @restrict E
  21725. *
  21726. * @description
  21727. * Modifies the default behavior of the html a tag so that the default action is prevented when
  21728. * the href attribute is empty.
  21729. *
  21730. * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
  21731. */
  21732. var htmlAnchorDirective = valueFn({
  21733. restrict: 'E',
  21734. compile: function(element, attr) {
  21735. if (!attr.href && !attr.xlinkHref) {
  21736. return function(scope, element) {
  21737. // If the linked element is not an anchor tag anymore, do nothing
  21738. if (element[0].nodeName.toLowerCase() !== 'a') return;
  21739. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  21740. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  21741. 'xlink:href' : 'href';
  21742. element.on('click', function(event) {
  21743. // if we have no href url, then don't navigate anywhere.
  21744. if (!element.attr(href)) {
  21745. event.preventDefault();
  21746. }
  21747. });
  21748. };
  21749. }
  21750. }
  21751. });
  21752. /**
  21753. * @ngdoc directive
  21754. * @name ngHref
  21755. * @restrict A
  21756. * @priority 99
  21757. *
  21758. * @description
  21759. * Using AngularJS markup like `{{hash}}` in an href attribute will
  21760. * make the link go to the wrong URL if the user clicks it before
  21761. * AngularJS has a chance to replace the `{{hash}}` markup with its
  21762. * value. Until AngularJS replaces the markup the link will be broken
  21763. * and will most likely return a 404 error. The `ngHref` directive
  21764. * solves this problem.
  21765. *
  21766. * The wrong way to write it:
  21767. * ```html
  21768. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  21769. * ```
  21770. *
  21771. * The correct way to write it:
  21772. * ```html
  21773. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  21774. * ```
  21775. *
  21776. * @element A
  21777. * @param {template} ngHref any string which can contain `{{}}` markup.
  21778. *
  21779. * @example
  21780. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  21781. * in links and their different behaviors:
  21782. <example name="ng-href">
  21783. <file name="index.html">
  21784. <input ng-model="value" /><br />
  21785. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  21786. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  21787. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  21788. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  21789. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  21790. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  21791. </file>
  21792. <file name="protractor.js" type="protractor">
  21793. it('should execute ng-click but not reload when href without value', function() {
  21794. element(by.id('link-1')).click();
  21795. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  21796. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  21797. });
  21798. it('should execute ng-click but not reload when href empty string', function() {
  21799. element(by.id('link-2')).click();
  21800. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  21801. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  21802. });
  21803. it('should execute ng-click and change url when ng-href specified', function() {
  21804. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  21805. element(by.id('link-3')).click();
  21806. // At this point, we navigate away from an AngularJS page, so we need
  21807. // to use browser.driver to get the base webdriver.
  21808. browser.wait(function() {
  21809. return browser.driver.getCurrentUrl().then(function(url) {
  21810. return url.match(/\/123$/);
  21811. });
  21812. }, 5000, 'page should navigate to /123');
  21813. });
  21814. it('should execute ng-click but not reload when href empty string and name specified', function() {
  21815. element(by.id('link-4')).click();
  21816. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  21817. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  21818. });
  21819. it('should execute ng-click but not reload when no href but name specified', function() {
  21820. element(by.id('link-5')).click();
  21821. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  21822. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  21823. });
  21824. it('should only change url when only ng-href', function() {
  21825. element(by.model('value')).clear();
  21826. element(by.model('value')).sendKeys('6');
  21827. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  21828. element(by.id('link-6')).click();
  21829. // At this point, we navigate away from an AngularJS page, so we need
  21830. // to use browser.driver to get the base webdriver.
  21831. browser.wait(function() {
  21832. return browser.driver.getCurrentUrl().then(function(url) {
  21833. return url.match(/\/6$/);
  21834. });
  21835. }, 5000, 'page should navigate to /6');
  21836. });
  21837. </file>
  21838. </example>
  21839. */
  21840. /**
  21841. * @ngdoc directive
  21842. * @name ngSrc
  21843. * @restrict A
  21844. * @priority 99
  21845. *
  21846. * @description
  21847. * Using AngularJS markup like `{{hash}}` in a `src` attribute doesn't
  21848. * work right: The browser will fetch from the URL with the literal
  21849. * text `{{hash}}` until AngularJS replaces the expression inside
  21850. * `{{hash}}`. The `ngSrc` directive solves this problem.
  21851. *
  21852. * The buggy way to write it:
  21853. * ```html
  21854. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  21855. * ```
  21856. *
  21857. * The correct way to write it:
  21858. * ```html
  21859. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  21860. * ```
  21861. *
  21862. * @element IMG
  21863. * @param {template} ngSrc any string which can contain `{{}}` markup.
  21864. */
  21865. /**
  21866. * @ngdoc directive
  21867. * @name ngSrcset
  21868. * @restrict A
  21869. * @priority 99
  21870. *
  21871. * @description
  21872. * Using AngularJS markup like `{{hash}}` in a `srcset` attribute doesn't
  21873. * work right: The browser will fetch from the URL with the literal
  21874. * text `{{hash}}` until AngularJS replaces the expression inside
  21875. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  21876. *
  21877. * The buggy way to write it:
  21878. * ```html
  21879. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  21880. * ```
  21881. *
  21882. * The correct way to write it:
  21883. * ```html
  21884. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  21885. * ```
  21886. *
  21887. * @element IMG
  21888. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  21889. */
  21890. /**
  21891. * @ngdoc directive
  21892. * @name ngDisabled
  21893. * @restrict A
  21894. * @priority 100
  21895. *
  21896. * @description
  21897. *
  21898. * This directive sets the `disabled` attribute on the element (typically a form control,
  21899. * e.g. `input`, `button`, `select` etc.) if the
  21900. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  21901. *
  21902. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  21903. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  21904. *
  21905. * @example
  21906. <example name="ng-disabled">
  21907. <file name="index.html">
  21908. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  21909. <button ng-model="button" ng-disabled="checked">Button</button>
  21910. </file>
  21911. <file name="protractor.js" type="protractor">
  21912. it('should toggle button', function() {
  21913. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  21914. element(by.model('checked')).click();
  21915. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  21916. });
  21917. </file>
  21918. </example>
  21919. *
  21920. * @element INPUT
  21921. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  21922. * then the `disabled` attribute will be set on the element
  21923. */
  21924. /**
  21925. * @ngdoc directive
  21926. * @name ngChecked
  21927. * @restrict A
  21928. * @priority 100
  21929. *
  21930. * @description
  21931. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  21932. *
  21933. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  21934. * as this can lead to unexpected behavior.
  21935. *
  21936. * A special directive is necessary because we cannot use interpolation inside the `checked`
  21937. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  21938. *
  21939. * @example
  21940. <example name="ng-checked">
  21941. <file name="index.html">
  21942. <label>Check me to check both: <input type="checkbox" ng-model="leader"></label><br/>
  21943. <input id="checkFollower" type="checkbox" ng-checked="leader" aria-label="Follower input">
  21944. </file>
  21945. <file name="protractor.js" type="protractor">
  21946. it('should check both checkBoxes', function() {
  21947. expect(element(by.id('checkFollower')).getAttribute('checked')).toBeFalsy();
  21948. element(by.model('leader')).click();
  21949. expect(element(by.id('checkFollower')).getAttribute('checked')).toBeTruthy();
  21950. });
  21951. </file>
  21952. </example>
  21953. *
  21954. * @element INPUT
  21955. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  21956. * then the `checked` attribute will be set on the element
  21957. */
  21958. /**
  21959. * @ngdoc directive
  21960. * @name ngReadonly
  21961. * @restrict A
  21962. * @priority 100
  21963. *
  21964. * @description
  21965. *
  21966. * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  21967. * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
  21968. * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
  21969. *
  21970. * A special directive is necessary because we cannot use interpolation inside the `readonly`
  21971. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  21972. *
  21973. * @example
  21974. <example name="ng-readonly">
  21975. <file name="index.html">
  21976. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  21977. <input type="text" ng-readonly="checked" value="I'm AngularJS" aria-label="Readonly field" />
  21978. </file>
  21979. <file name="protractor.js" type="protractor">
  21980. it('should toggle readonly attr', function() {
  21981. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  21982. element(by.model('checked')).click();
  21983. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  21984. });
  21985. </file>
  21986. </example>
  21987. *
  21988. * @element INPUT
  21989. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  21990. * then special attribute "readonly" will be set on the element
  21991. */
  21992. /**
  21993. * @ngdoc directive
  21994. * @name ngSelected
  21995. * @restrict A
  21996. * @priority 100
  21997. *
  21998. * @description
  21999. *
  22000. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  22001. *
  22002. * A special directive is necessary because we cannot use interpolation inside the `selected`
  22003. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  22004. *
  22005. * <div class="alert alert-warning">
  22006. * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
  22007. * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
  22008. * should not use `ngSelected` on the options, as `ngModel` will set the select value and
  22009. * selected options.
  22010. * </div>
  22011. *
  22012. * @example
  22013. <example name="ng-selected">
  22014. <file name="index.html">
  22015. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  22016. <select aria-label="ngSelected demo">
  22017. <option>Hello!</option>
  22018. <option id="greet" ng-selected="selected">Greetings!</option>
  22019. </select>
  22020. </file>
  22021. <file name="protractor.js" type="protractor">
  22022. it('should select Greetings!', function() {
  22023. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  22024. element(by.model('selected')).click();
  22025. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  22026. });
  22027. </file>
  22028. </example>
  22029. *
  22030. * @element OPTION
  22031. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  22032. * then special attribute "selected" will be set on the element
  22033. */
  22034. /**
  22035. * @ngdoc directive
  22036. * @name ngOpen
  22037. * @restrict A
  22038. * @priority 100
  22039. *
  22040. * @description
  22041. *
  22042. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  22043. *
  22044. * A special directive is necessary because we cannot use interpolation inside the `open`
  22045. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  22046. *
  22047. * ## A note about browser compatibility
  22048. *
  22049. * Internet Explorer and Edge do not support the `details` element, it is
  22050. * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
  22051. *
  22052. * @example
  22053. <example name="ng-open">
  22054. <file name="index.html">
  22055. <label>Toggle details: <input type="checkbox" ng-model="open"></label><br/>
  22056. <details id="details" ng-open="open">
  22057. <summary>List</summary>
  22058. <ul>
  22059. <li>Apple</li>
  22060. <li>Orange</li>
  22061. <li>Durian</li>
  22062. </ul>
  22063. </details>
  22064. </file>
  22065. <file name="protractor.js" type="protractor">
  22066. it('should toggle open', function() {
  22067. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  22068. element(by.model('open')).click();
  22069. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  22070. });
  22071. </file>
  22072. </example>
  22073. *
  22074. * @element DETAILS
  22075. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  22076. * then special attribute "open" will be set on the element
  22077. */
  22078. var ngAttributeAliasDirectives = {};
  22079. // boolean attrs are evaluated
  22080. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  22081. // binding to multiple is not supported
  22082. if (propName === 'multiple') return;
  22083. function defaultLinkFn(scope, element, attr) {
  22084. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  22085. attr.$set(attrName, !!value);
  22086. });
  22087. }
  22088. var normalized = directiveNormalize('ng-' + attrName);
  22089. var linkFn = defaultLinkFn;
  22090. if (propName === 'checked') {
  22091. linkFn = function(scope, element, attr) {
  22092. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  22093. if (attr.ngModel !== attr[normalized]) {
  22094. defaultLinkFn(scope, element, attr);
  22095. }
  22096. };
  22097. }
  22098. ngAttributeAliasDirectives[normalized] = function() {
  22099. return {
  22100. restrict: 'A',
  22101. priority: 100,
  22102. link: linkFn
  22103. };
  22104. };
  22105. });
  22106. // aliased input attrs are evaluated
  22107. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  22108. ngAttributeAliasDirectives[ngAttr] = function() {
  22109. return {
  22110. priority: 100,
  22111. link: function(scope, element, attr) {
  22112. //special case ngPattern when a literal regular expression value
  22113. //is used as the expression (this way we don't have to watch anything).
  22114. if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
  22115. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  22116. if (match) {
  22117. attr.$set('ngPattern', new RegExp(match[1], match[2]));
  22118. return;
  22119. }
  22120. }
  22121. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  22122. attr.$set(ngAttr, value);
  22123. });
  22124. }
  22125. };
  22126. };
  22127. });
  22128. // ng-src, ng-srcset, ng-href are interpolated
  22129. forEach(['src', 'srcset', 'href'], function(attrName) {
  22130. var normalized = directiveNormalize('ng-' + attrName);
  22131. ngAttributeAliasDirectives[normalized] = function() {
  22132. return {
  22133. priority: 99, // it needs to run after the attributes are interpolated
  22134. link: function(scope, element, attr) {
  22135. var propName = attrName,
  22136. name = attrName;
  22137. if (attrName === 'href' &&
  22138. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  22139. name = 'xlinkHref';
  22140. attr.$attr[name] = 'xlink:href';
  22141. propName = null;
  22142. }
  22143. attr.$observe(normalized, function(value) {
  22144. if (!value) {
  22145. if (attrName === 'href') {
  22146. attr.$set(name, null);
  22147. }
  22148. return;
  22149. }
  22150. attr.$set(name, value);
  22151. // Support: IE 9-11 only
  22152. // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  22153. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  22154. // to set the property as well to achieve the desired effect.
  22155. // We use attr[attrName] value since $set might have sanitized the url.
  22156. if (msie && propName) element.prop(propName, attr[name]);
  22157. });
  22158. }
  22159. };
  22160. };
  22161. });
  22162. /* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS
  22163. */
  22164. var nullFormCtrl = {
  22165. $addControl: noop,
  22166. $getControls: valueFn([]),
  22167. $$renameControl: nullFormRenameControl,
  22168. $removeControl: noop,
  22169. $setValidity: noop,
  22170. $setDirty: noop,
  22171. $setPristine: noop,
  22172. $setSubmitted: noop,
  22173. $$setSubmitted: noop
  22174. },
  22175. PENDING_CLASS = 'ng-pending',
  22176. SUBMITTED_CLASS = 'ng-submitted';
  22177. function nullFormRenameControl(control, name) {
  22178. control.$name = name;
  22179. }
  22180. /**
  22181. * @ngdoc type
  22182. * @name form.FormController
  22183. *
  22184. * @property {boolean} $pristine True if user has not interacted with the form yet.
  22185. * @property {boolean} $dirty True if user has already interacted with the form.
  22186. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  22187. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  22188. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  22189. *
  22190. * @property {Object} $pending An object hash, containing references to controls or forms with
  22191. * pending validators, where:
  22192. *
  22193. * - keys are validations tokens (error names).
  22194. * - values are arrays of controls or forms that have a pending validator for the given error name.
  22195. *
  22196. * See {@link form.FormController#$error $error} for a list of built-in validation tokens.
  22197. *
  22198. * @property {Object} $error An object hash, containing references to controls or forms with failing
  22199. * validators, where:
  22200. *
  22201. * - keys are validation tokens (error names),
  22202. * - values are arrays of controls or forms that have a failing validator for the given error name.
  22203. *
  22204. * Built-in validation tokens:
  22205. * - `email`
  22206. * - `max`
  22207. * - `maxlength`
  22208. * - `min`
  22209. * - `minlength`
  22210. * - `number`
  22211. * - `pattern`
  22212. * - `required`
  22213. * - `url`
  22214. * - `date`
  22215. * - `datetimelocal`
  22216. * - `time`
  22217. * - `week`
  22218. * - `month`
  22219. *
  22220. * @description
  22221. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  22222. * such as being valid/invalid or dirty/pristine.
  22223. *
  22224. * Each {@link ng.directive:form form} directive creates an instance
  22225. * of `FormController`.
  22226. *
  22227. */
  22228. //asks for $scope to fool the BC controller module
  22229. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  22230. function FormController($element, $attrs, $scope, $animate, $interpolate) {
  22231. this.$$controls = [];
  22232. // init state
  22233. this.$error = {};
  22234. this.$$success = {};
  22235. this.$pending = undefined;
  22236. this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);
  22237. this.$dirty = false;
  22238. this.$pristine = true;
  22239. this.$valid = true;
  22240. this.$invalid = false;
  22241. this.$submitted = false;
  22242. this.$$parentForm = nullFormCtrl;
  22243. this.$$element = $element;
  22244. this.$$animate = $animate;
  22245. setupValidity(this);
  22246. }
  22247. FormController.prototype = {
  22248. /**
  22249. * @ngdoc method
  22250. * @name form.FormController#$rollbackViewValue
  22251. *
  22252. * @description
  22253. * Rollback all form controls pending updates to the `$modelValue`.
  22254. *
  22255. * Updates may be pending by a debounced event or because the input is waiting for a some future
  22256. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  22257. * a form that uses `ng-model-options` to pend updates.
  22258. */
  22259. $rollbackViewValue: function() {
  22260. forEach(this.$$controls, function(control) {
  22261. control.$rollbackViewValue();
  22262. });
  22263. },
  22264. /**
  22265. * @ngdoc method
  22266. * @name form.FormController#$commitViewValue
  22267. *
  22268. * @description
  22269. * Commit all form controls pending updates to the `$modelValue`.
  22270. *
  22271. * Updates may be pending by a debounced event or because the input is waiting for a some future
  22272. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  22273. * usually handles calling this in response to input events.
  22274. */
  22275. $commitViewValue: function() {
  22276. forEach(this.$$controls, function(control) {
  22277. control.$commitViewValue();
  22278. });
  22279. },
  22280. /**
  22281. * @ngdoc method
  22282. * @name form.FormController#$addControl
  22283. * @param {object} control control object, either a {@link form.FormController} or an
  22284. * {@link ngModel.NgModelController}
  22285. *
  22286. * @description
  22287. * Register a control with the form. Input elements using ngModelController do this automatically
  22288. * when they are linked.
  22289. *
  22290. * Note that the current state of the control will not be reflected on the new parent form. This
  22291. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  22292. * state.
  22293. *
  22294. * However, if the method is used programmatically, for example by adding dynamically created controls,
  22295. * or controls that have been previously removed without destroying their corresponding DOM element,
  22296. * it's the developers responsibility to make sure the current state propagates to the parent form.
  22297. *
  22298. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  22299. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  22300. */
  22301. $addControl: function(control) {
  22302. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  22303. // and not added to the scope. Now we throw an error.
  22304. assertNotHasOwnProperty(control.$name, 'input');
  22305. this.$$controls.push(control);
  22306. if (control.$name) {
  22307. this[control.$name] = control;
  22308. }
  22309. control.$$parentForm = this;
  22310. },
  22311. /**
  22312. * @ngdoc method
  22313. * @name form.FormController#$getControls
  22314. * @returns {Array} the controls that are currently part of this form
  22315. *
  22316. * @description
  22317. * This method returns a **shallow copy** of the controls that are currently part of this form.
  22318. * The controls can be instances of {@link form.FormController `FormController`}
  22319. * ({@link ngForm "child-forms"}) and of {@link ngModel.NgModelController `NgModelController`}.
  22320. * If you need access to the controls of child-forms, you have to call `$getControls()`
  22321. * recursively on them.
  22322. * This can be used for example to iterate over all controls to validate them.
  22323. *
  22324. * The controls can be accessed normally, but adding to, or removing controls from the array has
  22325. * no effect on the form. Instead, use {@link form.FormController#$addControl `$addControl()`} and
  22326. * {@link form.FormController#$removeControl `$removeControl()`} for this use-case.
  22327. * Likewise, adding a control to, or removing a control from the form is not reflected
  22328. * in the shallow copy. That means you should get a fresh copy from `$getControls()` every time
  22329. * you need access to the controls.
  22330. */
  22331. $getControls: function() {
  22332. return shallowCopy(this.$$controls);
  22333. },
  22334. // Private API: rename a form control
  22335. $$renameControl: function(control, newName) {
  22336. var oldName = control.$name;
  22337. if (this[oldName] === control) {
  22338. delete this[oldName];
  22339. }
  22340. this[newName] = control;
  22341. control.$name = newName;
  22342. },
  22343. /**
  22344. * @ngdoc method
  22345. * @name form.FormController#$removeControl
  22346. * @param {object} control control object, either a {@link form.FormController} or an
  22347. * {@link ngModel.NgModelController}
  22348. *
  22349. * @description
  22350. * Deregister a control from the form.
  22351. *
  22352. * Input elements using ngModelController do this automatically when they are destroyed.
  22353. *
  22354. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  22355. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  22356. * different from case to case. For example, removing the only `$dirty` control from a form may or
  22357. * may not mean that the form is still `$dirty`.
  22358. */
  22359. $removeControl: function(control) {
  22360. if (control.$name && this[control.$name] === control) {
  22361. delete this[control.$name];
  22362. }
  22363. forEach(this.$pending, function(value, name) {
  22364. // eslint-disable-next-line no-invalid-this
  22365. this.$setValidity(name, null, control);
  22366. }, this);
  22367. forEach(this.$error, function(value, name) {
  22368. // eslint-disable-next-line no-invalid-this
  22369. this.$setValidity(name, null, control);
  22370. }, this);
  22371. forEach(this.$$success, function(value, name) {
  22372. // eslint-disable-next-line no-invalid-this
  22373. this.$setValidity(name, null, control);
  22374. }, this);
  22375. arrayRemove(this.$$controls, control);
  22376. control.$$parentForm = nullFormCtrl;
  22377. },
  22378. /**
  22379. * @ngdoc method
  22380. * @name form.FormController#$setDirty
  22381. *
  22382. * @description
  22383. * Sets the form to a dirty state.
  22384. *
  22385. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  22386. * state (ng-dirty class). This method will also propagate to parent forms.
  22387. */
  22388. $setDirty: function() {
  22389. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  22390. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  22391. this.$dirty = true;
  22392. this.$pristine = false;
  22393. this.$$parentForm.$setDirty();
  22394. },
  22395. /**
  22396. * @ngdoc method
  22397. * @name form.FormController#$setPristine
  22398. *
  22399. * @description
  22400. * Sets the form to its pristine state.
  22401. *
  22402. * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
  22403. * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
  22404. * state to false.
  22405. *
  22406. * This method will also propagate to all the controls contained in this form.
  22407. *
  22408. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  22409. * saving or resetting it.
  22410. */
  22411. $setPristine: function() {
  22412. this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  22413. this.$dirty = false;
  22414. this.$pristine = true;
  22415. this.$submitted = false;
  22416. forEach(this.$$controls, function(control) {
  22417. control.$setPristine();
  22418. });
  22419. },
  22420. /**
  22421. * @ngdoc method
  22422. * @name form.FormController#$setUntouched
  22423. *
  22424. * @description
  22425. * Sets the form to its untouched state.
  22426. *
  22427. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  22428. * untouched state (ng-untouched class).
  22429. *
  22430. * Setting a form controls back to their untouched state is often useful when setting the form
  22431. * back to its pristine state.
  22432. */
  22433. $setUntouched: function() {
  22434. forEach(this.$$controls, function(control) {
  22435. control.$setUntouched();
  22436. });
  22437. },
  22438. /**
  22439. * @ngdoc method
  22440. * @name form.FormController#$setSubmitted
  22441. *
  22442. * @description
  22443. * Sets the form to its `$submitted` state. This will also set `$submitted` on all child and
  22444. * parent forms of the form.
  22445. */
  22446. $setSubmitted: function() {
  22447. var rootForm = this;
  22448. while (rootForm.$$parentForm && (rootForm.$$parentForm !== nullFormCtrl)) {
  22449. rootForm = rootForm.$$parentForm;
  22450. }
  22451. rootForm.$$setSubmitted();
  22452. },
  22453. $$setSubmitted: function() {
  22454. this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);
  22455. this.$submitted = true;
  22456. forEach(this.$$controls, function(control) {
  22457. if (control.$$setSubmitted) {
  22458. control.$$setSubmitted();
  22459. }
  22460. });
  22461. }
  22462. };
  22463. /**
  22464. * @ngdoc method
  22465. * @name form.FormController#$setValidity
  22466. *
  22467. * @description
  22468. * Change the validity state of the form, and notify the parent form (if any).
  22469. *
  22470. * Application developers will rarely need to call this method directly. It is used internally, by
  22471. * {@link ngModel.NgModelController#$setValidity NgModelController.$setValidity()}, to propagate a
  22472. * control's validity state to the parent `FormController`.
  22473. *
  22474. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be
  22475. * assigned to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` (for
  22476. * unfulfilled `$asyncValidators`), so that it is available for data-binding. The
  22477. * `validationErrorKey` should be in camelCase and will get converted into dash-case for
  22478. * class name. Example: `myError` will result in `ng-valid-my-error` and
  22479. * `ng-invalid-my-error` classes and can be bound to as `{{ someForm.$error.myError }}`.
  22480. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending
  22481. * (undefined), or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  22482. * Skipped is used by AngularJS when validators do not run because of parse errors and when
  22483. * `$asyncValidators` do not run because any of the `$validators` failed.
  22484. * @param {NgModelController | FormController} controller - The controller whose validity state is
  22485. * triggering the change.
  22486. */
  22487. addSetValidityMethod({
  22488. clazz: FormController,
  22489. set: function(object, property, controller) {
  22490. var list = object[property];
  22491. if (!list) {
  22492. object[property] = [controller];
  22493. } else {
  22494. var index = list.indexOf(controller);
  22495. if (index === -1) {
  22496. list.push(controller);
  22497. }
  22498. }
  22499. },
  22500. unset: function(object, property, controller) {
  22501. var list = object[property];
  22502. if (!list) {
  22503. return;
  22504. }
  22505. arrayRemove(list, controller);
  22506. if (list.length === 0) {
  22507. delete object[property];
  22508. }
  22509. }
  22510. });
  22511. /**
  22512. * @ngdoc directive
  22513. * @name ngForm
  22514. * @restrict EAC
  22515. *
  22516. * @description
  22517. * Helper directive that makes it possible to create control groups inside a
  22518. * {@link ng.directive:form `form`} directive.
  22519. * These "child forms" can be used, for example, to determine the validity of a sub-group of
  22520. * controls.
  22521. *
  22522. * <div class="alert alert-danger">
  22523. * **Note**: `ngForm` cannot be used as a replacement for `<form>`, because it lacks its
  22524. * [built-in HTML functionality](https://html.spec.whatwg.org/#the-form-element).
  22525. * Specifically, you cannot submit `ngForm` like a `<form>` tag. That means,
  22526. * you cannot send data to the server with `ngForm`, or integrate it with
  22527. * {@link ng.directive:ngSubmit `ngSubmit`}.
  22528. * </div>
  22529. *
  22530. * @param {string=} ngForm|name Name of the form. If specified, the form controller will
  22531. * be published into the related scope, under this name.
  22532. *
  22533. */
  22534. /**
  22535. * @ngdoc directive
  22536. * @name form
  22537. * @restrict E
  22538. *
  22539. * @description
  22540. * Directive that instantiates
  22541. * {@link form.FormController FormController}.
  22542. *
  22543. * If the `name` attribute is specified, the form controller is published onto the current scope under
  22544. * this name.
  22545. *
  22546. * ## Alias: {@link ng.directive:ngForm `ngForm`}
  22547. *
  22548. * In AngularJS, forms can be nested. This means that the outer form is valid when all of the child
  22549. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  22550. * AngularJS provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  22551. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  22552. * of controls needs to be determined.
  22553. *
  22554. * ## CSS classes
  22555. * - `ng-valid` is set if the form is valid.
  22556. * - `ng-invalid` is set if the form is invalid.
  22557. * - `ng-pending` is set if the form is pending.
  22558. * - `ng-pristine` is set if the form is pristine.
  22559. * - `ng-dirty` is set if the form is dirty.
  22560. * - `ng-submitted` is set if the form was submitted.
  22561. *
  22562. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  22563. *
  22564. *
  22565. * ## Submitting a form and preventing the default action
  22566. *
  22567. * Since the role of forms in client-side AngularJS applications is different than in classical
  22568. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  22569. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  22570. * to handle the form submission in an application-specific way.
  22571. *
  22572. * For this reason, AngularJS prevents the default action (form submission to the server) unless the
  22573. * `<form>` element has an `action` attribute specified.
  22574. *
  22575. * You can use one of the following two ways to specify what javascript method should be called when
  22576. * a form is submitted:
  22577. *
  22578. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  22579. * - {@link ng.directive:ngClick ngClick} directive on the first
  22580. * button or input field of type submit (input[type=submit])
  22581. *
  22582. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  22583. * or {@link ng.directive:ngClick ngClick} directives.
  22584. * This is because of the following form submission rules in the HTML specification:
  22585. *
  22586. * - If a form has only one input field then hitting enter in this field triggers form submit
  22587. * (`ngSubmit`)
  22588. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  22589. * doesn't trigger submit
  22590. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  22591. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  22592. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  22593. *
  22594. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  22595. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  22596. * to have access to the updated model.
  22597. *
  22598. * @animations
  22599. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  22600. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  22601. * other validations that are performed within the form. Animations in ngForm are similar to how
  22602. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  22603. * as JS animations.
  22604. *
  22605. * The following example shows a simple way to utilize CSS transitions to style a form element
  22606. * that has been rendered as invalid after it has been validated:
  22607. *
  22608. * <pre>
  22609. * //be sure to include ngAnimate as a module to hook into more
  22610. * //advanced animations
  22611. * .my-form {
  22612. * transition:0.5s linear all;
  22613. * background: white;
  22614. * }
  22615. * .my-form.ng-invalid {
  22616. * background: red;
  22617. * color:white;
  22618. * }
  22619. * </pre>
  22620. *
  22621. * @example
  22622. <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  22623. <file name="index.html">
  22624. <script>
  22625. angular.module('formExample', [])
  22626. .controller('FormController', ['$scope', function($scope) {
  22627. $scope.userType = 'guest';
  22628. }]);
  22629. </script>
  22630. <style>
  22631. .my-form {
  22632. transition:all linear 0.5s;
  22633. background: transparent;
  22634. }
  22635. .my-form.ng-invalid {
  22636. background: red;
  22637. }
  22638. </style>
  22639. <form name="myForm" ng-controller="FormController" class="my-form">
  22640. userType: <input name="input" ng-model="userType" required>
  22641. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  22642. <code>userType = {{userType}}</code><br>
  22643. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  22644. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  22645. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  22646. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  22647. </form>
  22648. </file>
  22649. <file name="protractor.js" type="protractor">
  22650. it('should initialize to model', function() {
  22651. var userType = element(by.binding('userType'));
  22652. var valid = element(by.binding('myForm.input.$valid'));
  22653. expect(userType.getText()).toContain('guest');
  22654. expect(valid.getText()).toContain('true');
  22655. });
  22656. it('should be invalid if empty', function() {
  22657. var userType = element(by.binding('userType'));
  22658. var valid = element(by.binding('myForm.input.$valid'));
  22659. var userInput = element(by.model('userType'));
  22660. userInput.clear();
  22661. userInput.sendKeys('');
  22662. expect(userType.getText()).toEqual('userType =');
  22663. expect(valid.getText()).toContain('false');
  22664. });
  22665. </file>
  22666. </example>
  22667. *
  22668. * @param {string=} name Name of the form. If specified, the form controller will be published into
  22669. * related scope, under this name.
  22670. */
  22671. var formDirectiveFactory = function(isNgForm) {
  22672. return ['$timeout', '$parse', function($timeout, $parse) {
  22673. var formDirective = {
  22674. name: 'form',
  22675. restrict: isNgForm ? 'EAC' : 'E',
  22676. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  22677. controller: FormController,
  22678. compile: function ngFormCompile(formElement, attr) {
  22679. // Setup initial state of the control
  22680. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  22681. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  22682. return {
  22683. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  22684. var controller = ctrls[0];
  22685. // if `action` attr is not present on the form, prevent the default action (submission)
  22686. if (!('action' in attr)) {
  22687. // we can't use jq events because if a form is destroyed during submission the default
  22688. // action is not prevented. see #1238
  22689. //
  22690. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  22691. // page reload if the form was destroyed by submission of the form via a click handler
  22692. // on a button in the form. Looks like an IE9 specific bug.
  22693. var handleFormSubmission = function(event) {
  22694. scope.$apply(function() {
  22695. controller.$commitViewValue();
  22696. controller.$setSubmitted();
  22697. });
  22698. event.preventDefault();
  22699. };
  22700. formElement[0].addEventListener('submit', handleFormSubmission);
  22701. // unregister the preventDefault listener so that we don't not leak memory but in a
  22702. // way that will achieve the prevention of the default action.
  22703. formElement.on('$destroy', function() {
  22704. $timeout(function() {
  22705. formElement[0].removeEventListener('submit', handleFormSubmission);
  22706. }, 0, false);
  22707. });
  22708. }
  22709. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  22710. parentFormCtrl.$addControl(controller);
  22711. var setter = nameAttr ? getSetter(controller.$name) : noop;
  22712. if (nameAttr) {
  22713. setter(scope, controller);
  22714. attr.$observe(nameAttr, function(newValue) {
  22715. if (controller.$name === newValue) return;
  22716. setter(scope, undefined);
  22717. controller.$$parentForm.$$renameControl(controller, newValue);
  22718. setter = getSetter(controller.$name);
  22719. setter(scope, controller);
  22720. });
  22721. }
  22722. formElement.on('$destroy', function() {
  22723. controller.$$parentForm.$removeControl(controller);
  22724. setter(scope, undefined);
  22725. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  22726. });
  22727. }
  22728. };
  22729. }
  22730. };
  22731. return formDirective;
  22732. function getSetter(expression) {
  22733. if (expression === '') {
  22734. //create an assignable expression, so forms with an empty name can be renamed later
  22735. return $parse('this[""]').assign;
  22736. }
  22737. return $parse(expression).assign || noop;
  22738. }
  22739. }];
  22740. };
  22741. var formDirective = formDirectiveFactory();
  22742. var ngFormDirective = formDirectiveFactory(true);
  22743. // helper methods
  22744. function setupValidity(instance) {
  22745. instance.$$classCache = {};
  22746. instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));
  22747. }
  22748. function addSetValidityMethod(context) {
  22749. var clazz = context.clazz,
  22750. set = context.set,
  22751. unset = context.unset;
  22752. clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {
  22753. if (isUndefined(state)) {
  22754. createAndSet(this, '$pending', validationErrorKey, controller);
  22755. } else {
  22756. unsetAndCleanup(this, '$pending', validationErrorKey, controller);
  22757. }
  22758. if (!isBoolean(state)) {
  22759. unset(this.$error, validationErrorKey, controller);
  22760. unset(this.$$success, validationErrorKey, controller);
  22761. } else {
  22762. if (state) {
  22763. unset(this.$error, validationErrorKey, controller);
  22764. set(this.$$success, validationErrorKey, controller);
  22765. } else {
  22766. set(this.$error, validationErrorKey, controller);
  22767. unset(this.$$success, validationErrorKey, controller);
  22768. }
  22769. }
  22770. if (this.$pending) {
  22771. cachedToggleClass(this, PENDING_CLASS, true);
  22772. this.$valid = this.$invalid = undefined;
  22773. toggleValidationCss(this, '', null);
  22774. } else {
  22775. cachedToggleClass(this, PENDING_CLASS, false);
  22776. this.$valid = isObjectEmpty(this.$error);
  22777. this.$invalid = !this.$valid;
  22778. toggleValidationCss(this, '', this.$valid);
  22779. }
  22780. // re-read the state as the set/unset methods could have
  22781. // combined state in this.$error[validationError] (used for forms),
  22782. // where setting/unsetting only increments/decrements the value,
  22783. // and does not replace it.
  22784. var combinedState;
  22785. if (this.$pending && this.$pending[validationErrorKey]) {
  22786. combinedState = undefined;
  22787. } else if (this.$error[validationErrorKey]) {
  22788. combinedState = false;
  22789. } else if (this.$$success[validationErrorKey]) {
  22790. combinedState = true;
  22791. } else {
  22792. combinedState = null;
  22793. }
  22794. toggleValidationCss(this, validationErrorKey, combinedState);
  22795. this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);
  22796. };
  22797. function createAndSet(ctrl, name, value, controller) {
  22798. if (!ctrl[name]) {
  22799. ctrl[name] = {};
  22800. }
  22801. set(ctrl[name], value, controller);
  22802. }
  22803. function unsetAndCleanup(ctrl, name, value, controller) {
  22804. if (ctrl[name]) {
  22805. unset(ctrl[name], value, controller);
  22806. }
  22807. if (isObjectEmpty(ctrl[name])) {
  22808. ctrl[name] = undefined;
  22809. }
  22810. }
  22811. function cachedToggleClass(ctrl, className, switchValue) {
  22812. if (switchValue && !ctrl.$$classCache[className]) {
  22813. ctrl.$$animate.addClass(ctrl.$$element, className);
  22814. ctrl.$$classCache[className] = true;
  22815. } else if (!switchValue && ctrl.$$classCache[className]) {
  22816. ctrl.$$animate.removeClass(ctrl.$$element, className);
  22817. ctrl.$$classCache[className] = false;
  22818. }
  22819. }
  22820. function toggleValidationCss(ctrl, validationErrorKey, isValid) {
  22821. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  22822. cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);
  22823. cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);
  22824. }
  22825. }
  22826. function isObjectEmpty(obj) {
  22827. if (obj) {
  22828. for (var prop in obj) {
  22829. if (obj.hasOwnProperty(prop)) {
  22830. return false;
  22831. }
  22832. }
  22833. }
  22834. return true;
  22835. }
  22836. /* global
  22837. VALID_CLASS: false,
  22838. INVALID_CLASS: false,
  22839. PRISTINE_CLASS: false,
  22840. DIRTY_CLASS: false,
  22841. ngModelMinErr: false
  22842. */
  22843. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  22844. 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)$/;
  22845. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  22846. // Note: We are being more lenient, because browsers are too.
  22847. // 1. Scheme
  22848. // 2. Slashes
  22849. // 3. Username
  22850. // 4. Password
  22851. // 5. Hostname
  22852. // 6. Port
  22853. // 7. Path
  22854. // 8. Query
  22855. // 9. Fragment
  22856. // 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
  22857. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  22858. // eslint-disable-next-line max-len
  22859. 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])?)*$/;
  22860. var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  22861. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  22862. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  22863. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  22864. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  22865. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  22866. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  22867. var PARTIAL_VALIDATION_TYPES = createMap();
  22868. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  22869. PARTIAL_VALIDATION_TYPES[type] = true;
  22870. });
  22871. var inputType = {
  22872. /**
  22873. * @ngdoc input
  22874. * @name input[text]
  22875. *
  22876. * @description
  22877. * Standard HTML text input with AngularJS data binding, inherited by most of the `input` elements.
  22878. *
  22879. *
  22880. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22881. * @param {string=} name Property name of the form under which the control is published.
  22882. * @param {string=} required Adds `required` validation error key if the value is not entered.
  22883. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22884. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22885. * `required` when you want to data-bind to the `required` attribute.
  22886. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22887. * minlength.
  22888. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22889. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22890. * any length.
  22891. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22892. * that contains the regular expression body that will be converted to a regular expression
  22893. * as in the ngPattern directive.
  22894. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22895. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  22896. * If the expression evaluates to a RegExp object, then this is used directly.
  22897. * If the expression evaluates to a string, then it will be converted to a RegExp
  22898. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22899. * `new RegExp('^abc$')`.<br />
  22900. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22901. * start at the index of the last search's match, thus not taking the whole input value into
  22902. * account.
  22903. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  22904. * interaction with the input element.
  22905. * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input.
  22906. * This parameter is ignored for input[type=password] controls, which will never trim the
  22907. * input.
  22908. *
  22909. * @example
  22910. <example name="text-input-directive" module="textInputExample">
  22911. <file name="index.html">
  22912. <script>
  22913. angular.module('textInputExample', [])
  22914. .controller('ExampleController', ['$scope', function($scope) {
  22915. $scope.example = {
  22916. text: 'guest',
  22917. word: /^\s*\w*\s*$/
  22918. };
  22919. }]);
  22920. </script>
  22921. <form name="myForm" ng-controller="ExampleController">
  22922. <label>Single word:
  22923. <input type="text" name="input" ng-model="example.text"
  22924. ng-pattern="example.word" required ng-trim="false">
  22925. </label>
  22926. <div role="alert">
  22927. <span class="error" ng-show="myForm.input.$error.required">
  22928. Required!</span>
  22929. <span class="error" ng-show="myForm.input.$error.pattern">
  22930. Single word only!</span>
  22931. </div>
  22932. <code>text = {{example.text}}</code><br/>
  22933. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  22934. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  22935. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  22936. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  22937. </form>
  22938. </file>
  22939. <file name="protractor.js" type="protractor">
  22940. var text = element(by.binding('example.text'));
  22941. var valid = element(by.binding('myForm.input.$valid'));
  22942. var input = element(by.model('example.text'));
  22943. it('should initialize to model', function() {
  22944. expect(text.getText()).toContain('guest');
  22945. expect(valid.getText()).toContain('true');
  22946. });
  22947. it('should be invalid if empty', function() {
  22948. input.clear();
  22949. input.sendKeys('');
  22950. expect(text.getText()).toEqual('text =');
  22951. expect(valid.getText()).toContain('false');
  22952. });
  22953. it('should be invalid if multi word', function() {
  22954. input.clear();
  22955. input.sendKeys('hello world');
  22956. expect(valid.getText()).toContain('false');
  22957. });
  22958. </file>
  22959. </example>
  22960. */
  22961. 'text': textInputType,
  22962. /**
  22963. * @ngdoc input
  22964. * @name input[date]
  22965. *
  22966. * @description
  22967. * Input with date validation and transformation. In browsers that do not yet support
  22968. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  22969. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  22970. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  22971. * expected input format via a placeholder or label.
  22972. *
  22973. * The model must always be a Date object, otherwise AngularJS will throw an error.
  22974. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22975. *
  22976. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22977. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22978. *
  22979. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  22980. * @param {string=} name Property name of the form under which the control is published.
  22981. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  22982. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  22983. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  22984. * constraint validation.
  22985. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  22986. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  22987. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  22988. * constraint validation.
  22989. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  22990. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22991. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  22992. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22993. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22994. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22995. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22996. * `required` when you want to data-bind to the `required` attribute.
  22997. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  22998. * interaction with the input element.
  22999. *
  23000. * @example
  23001. <example name="date-input-directive" module="dateInputExample">
  23002. <file name="index.html">
  23003. <script>
  23004. angular.module('dateInputExample', [])
  23005. .controller('DateController', ['$scope', function($scope) {
  23006. $scope.example = {
  23007. value: new Date(2013, 9, 22)
  23008. };
  23009. }]);
  23010. </script>
  23011. <form name="myForm" ng-controller="DateController as dateCtrl">
  23012. <label for="exampleInput">Pick a date in 2013:</label>
  23013. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  23014. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  23015. <div role="alert">
  23016. <span class="error" ng-show="myForm.input.$error.required">
  23017. Required!</span>
  23018. <span class="error" ng-show="myForm.input.$error.date">
  23019. Not a valid date!</span>
  23020. </div>
  23021. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  23022. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23023. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23024. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23025. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23026. </form>
  23027. </file>
  23028. <file name="protractor.js" type="protractor">
  23029. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  23030. var valid = element(by.binding('myForm.input.$valid'));
  23031. // currently protractor/webdriver does not support
  23032. // sending keys to all known HTML5 input controls
  23033. // for various browsers (see https://github.com/angular/protractor/issues/562).
  23034. function setInput(val) {
  23035. // set the value of the element and force validation.
  23036. var scr = "var ipt = document.getElementById('exampleInput'); " +
  23037. "ipt.value = '" + val + "';" +
  23038. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  23039. browser.executeScript(scr);
  23040. }
  23041. it('should initialize to model', function() {
  23042. expect(value.getText()).toContain('2013-10-22');
  23043. expect(valid.getText()).toContain('myForm.input.$valid = true');
  23044. });
  23045. it('should be invalid if empty', function() {
  23046. setInput('');
  23047. expect(value.getText()).toEqual('value =');
  23048. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23049. });
  23050. it('should be invalid if over max', function() {
  23051. setInput('2015-01-01');
  23052. expect(value.getText()).toContain('');
  23053. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23054. });
  23055. </file>
  23056. </example>
  23057. */
  23058. 'date': createDateInputType('date', DATE_REGEXP,
  23059. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  23060. 'yyyy-MM-dd'),
  23061. /**
  23062. * @ngdoc input
  23063. * @name input[datetime-local]
  23064. *
  23065. * @description
  23066. * Input with datetime validation and transformation. In browsers that do not yet support
  23067. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  23068. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  23069. *
  23070. * The model must always be a Date object, otherwise AngularJS will throw an error.
  23071. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  23072. *
  23073. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  23074. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  23075. *
  23076. * The format of the displayed time can be adjusted with the
  23077. * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions} `timeSecondsFormat`
  23078. * and `timeStripZeroSeconds`.
  23079. *
  23080. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23081. * @param {string=} name Property name of the form under which the control is published.
  23082. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  23083. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  23084. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  23085. * Note that `min` will also add native HTML5 constraint validation.
  23086. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  23087. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  23088. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  23089. * Note that `max` will also add native HTML5 constraint validation.
  23090. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  23091. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  23092. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  23093. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  23094. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23095. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23096. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23097. * `required` when you want to data-bind to the `required` attribute.
  23098. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23099. * interaction with the input element.
  23100. *
  23101. * @example
  23102. <example name="datetimelocal-input-directive" module="dateExample">
  23103. <file name="index.html">
  23104. <script>
  23105. angular.module('dateExample', [])
  23106. .controller('DateController', ['$scope', function($scope) {
  23107. $scope.example = {
  23108. value: new Date(2010, 11, 28, 14, 57)
  23109. };
  23110. }]);
  23111. </script>
  23112. <form name="myForm" ng-controller="DateController as dateCtrl">
  23113. <label for="exampleInput">Pick a date between in 2013:</label>
  23114. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  23115. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  23116. <div role="alert">
  23117. <span class="error" ng-show="myForm.input.$error.required">
  23118. Required!</span>
  23119. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  23120. Not a valid date!</span>
  23121. </div>
  23122. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  23123. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23124. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23125. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23126. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23127. </form>
  23128. </file>
  23129. <file name="protractor.js" type="protractor">
  23130. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  23131. var valid = element(by.binding('myForm.input.$valid'));
  23132. // currently protractor/webdriver does not support
  23133. // sending keys to all known HTML5 input controls
  23134. // for various browsers (https://github.com/angular/protractor/issues/562).
  23135. function setInput(val) {
  23136. // set the value of the element and force validation.
  23137. var scr = "var ipt = document.getElementById('exampleInput'); " +
  23138. "ipt.value = '" + val + "';" +
  23139. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  23140. browser.executeScript(scr);
  23141. }
  23142. it('should initialize to model', function() {
  23143. expect(value.getText()).toContain('2010-12-28T14:57:00');
  23144. expect(valid.getText()).toContain('myForm.input.$valid = true');
  23145. });
  23146. it('should be invalid if empty', function() {
  23147. setInput('');
  23148. expect(value.getText()).toEqual('value =');
  23149. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23150. });
  23151. it('should be invalid if over max', function() {
  23152. setInput('2015-01-01T23:59:00');
  23153. expect(value.getText()).toContain('');
  23154. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23155. });
  23156. </file>
  23157. </example>
  23158. */
  23159. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  23160. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  23161. 'yyyy-MM-ddTHH:mm:ss.sss'),
  23162. /**
  23163. * @ngdoc input
  23164. * @name input[time]
  23165. *
  23166. * @description
  23167. * Input with time validation and transformation. In browsers that do not yet support
  23168. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  23169. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  23170. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  23171. *
  23172. * The model must always be a Date object, otherwise AngularJS will throw an error.
  23173. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  23174. *
  23175. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  23176. * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions}. By default,
  23177. * this is the timezone of the browser.
  23178. *
  23179. * The format of the displayed time can be adjusted with the
  23180. * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions} `timeSecondsFormat`
  23181. * and `timeStripZeroSeconds`.
  23182. *
  23183. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23184. * @param {string=} name Property name of the form under which the control is published.
  23185. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  23186. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  23187. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  23188. * native HTML5 constraint validation.
  23189. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  23190. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  23191. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  23192. * native HTML5 constraint validation.
  23193. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  23194. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  23195. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  23196. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  23197. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23198. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23199. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23200. * `required` when you want to data-bind to the `required` attribute.
  23201. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23202. * interaction with the input element.
  23203. *
  23204. * @example
  23205. <example name="time-input-directive" module="timeExample">
  23206. <file name="index.html">
  23207. <script>
  23208. angular.module('timeExample', [])
  23209. .controller('DateController', ['$scope', function($scope) {
  23210. $scope.example = {
  23211. value: new Date(1970, 0, 1, 14, 57, 0)
  23212. };
  23213. }]);
  23214. </script>
  23215. <form name="myForm" ng-controller="DateController as dateCtrl">
  23216. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  23217. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  23218. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  23219. <div role="alert">
  23220. <span class="error" ng-show="myForm.input.$error.required">
  23221. Required!</span>
  23222. <span class="error" ng-show="myForm.input.$error.time">
  23223. Not a valid date!</span>
  23224. </div>
  23225. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  23226. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23227. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23228. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23229. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23230. </form>
  23231. </file>
  23232. <file name="protractor.js" type="protractor">
  23233. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  23234. var valid = element(by.binding('myForm.input.$valid'));
  23235. // currently protractor/webdriver does not support
  23236. // sending keys to all known HTML5 input controls
  23237. // for various browsers (https://github.com/angular/protractor/issues/562).
  23238. function setInput(val) {
  23239. // set the value of the element and force validation.
  23240. var scr = "var ipt = document.getElementById('exampleInput'); " +
  23241. "ipt.value = '" + val + "';" +
  23242. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  23243. browser.executeScript(scr);
  23244. }
  23245. it('should initialize to model', function() {
  23246. expect(value.getText()).toContain('14:57:00');
  23247. expect(valid.getText()).toContain('myForm.input.$valid = true');
  23248. });
  23249. it('should be invalid if empty', function() {
  23250. setInput('');
  23251. expect(value.getText()).toEqual('value =');
  23252. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23253. });
  23254. it('should be invalid if over max', function() {
  23255. setInput('23:59:00');
  23256. expect(value.getText()).toContain('');
  23257. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23258. });
  23259. </file>
  23260. </example>
  23261. */
  23262. 'time': createDateInputType('time', TIME_REGEXP,
  23263. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  23264. 'HH:mm:ss.sss'),
  23265. /**
  23266. * @ngdoc input
  23267. * @name input[week]
  23268. *
  23269. * @description
  23270. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  23271. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  23272. * week format (yyyy-W##), for example: `2013-W02`.
  23273. *
  23274. * The model must always be a Date object, otherwise AngularJS will throw an error.
  23275. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  23276. *
  23277. * The value of the resulting Date object will be set to Thursday at 00:00:00 of the requested week,
  23278. * due to ISO-8601 week numbering standards. Information on ISO's system for numbering the weeks of the
  23279. * year can be found at: https://en.wikipedia.org/wiki/ISO_8601#Week_dates
  23280. *
  23281. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  23282. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  23283. *
  23284. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23285. * @param {string=} name Property name of the form under which the control is published.
  23286. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  23287. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  23288. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  23289. * native HTML5 constraint validation.
  23290. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  23291. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  23292. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  23293. * native HTML5 constraint validation.
  23294. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  23295. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  23296. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  23297. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  23298. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23299. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23300. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23301. * `required` when you want to data-bind to the `required` attribute.
  23302. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23303. * interaction with the input element.
  23304. *
  23305. * @example
  23306. <example name="week-input-directive" module="weekExample">
  23307. <file name="index.html">
  23308. <script>
  23309. angular.module('weekExample', [])
  23310. .controller('DateController', ['$scope', function($scope) {
  23311. $scope.example = {
  23312. value: new Date(2013, 0, 3)
  23313. };
  23314. }]);
  23315. </script>
  23316. <form name="myForm" ng-controller="DateController as dateCtrl">
  23317. <label>Pick a date between in 2013:
  23318. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  23319. placeholder="YYYY-W##" min="2012-W32"
  23320. max="2013-W52" required />
  23321. </label>
  23322. <div role="alert">
  23323. <span class="error" ng-show="myForm.input.$error.required">
  23324. Required!</span>
  23325. <span class="error" ng-show="myForm.input.$error.week">
  23326. Not a valid date!</span>
  23327. </div>
  23328. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  23329. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23330. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23331. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23332. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23333. </form>
  23334. </file>
  23335. <file name="protractor.js" type="protractor">
  23336. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  23337. var valid = element(by.binding('myForm.input.$valid'));
  23338. // currently protractor/webdriver does not support
  23339. // sending keys to all known HTML5 input controls
  23340. // for various browsers (https://github.com/angular/protractor/issues/562).
  23341. function setInput(val) {
  23342. // set the value of the element and force validation.
  23343. var scr = "var ipt = document.getElementById('exampleInput'); " +
  23344. "ipt.value = '" + val + "';" +
  23345. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  23346. browser.executeScript(scr);
  23347. }
  23348. it('should initialize to model', function() {
  23349. expect(value.getText()).toContain('2013-W01');
  23350. expect(valid.getText()).toContain('myForm.input.$valid = true');
  23351. });
  23352. it('should be invalid if empty', function() {
  23353. setInput('');
  23354. expect(value.getText()).toEqual('value =');
  23355. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23356. });
  23357. it('should be invalid if over max', function() {
  23358. setInput('2015-W01');
  23359. expect(value.getText()).toContain('');
  23360. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23361. });
  23362. </file>
  23363. </example>
  23364. */
  23365. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  23366. /**
  23367. * @ngdoc input
  23368. * @name input[month]
  23369. *
  23370. * @description
  23371. * Input with month validation and transformation. In browsers that do not yet support
  23372. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  23373. * month format (yyyy-MM), for example: `2009-01`.
  23374. *
  23375. * The model must always be a Date object, otherwise AngularJS will throw an error.
  23376. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  23377. * If the model is not set to the first of the month, the next view to model update will set it
  23378. * to the first of the month.
  23379. *
  23380. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  23381. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  23382. *
  23383. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23384. * @param {string=} name Property name of the form under which the control is published.
  23385. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  23386. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  23387. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  23388. * native HTML5 constraint validation.
  23389. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  23390. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  23391. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  23392. * native HTML5 constraint validation.
  23393. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  23394. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  23395. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  23396. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  23397. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23398. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23399. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23400. * `required` when you want to data-bind to the `required` attribute.
  23401. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23402. * interaction with the input element.
  23403. *
  23404. * @example
  23405. <example name="month-input-directive" module="monthExample">
  23406. <file name="index.html">
  23407. <script>
  23408. angular.module('monthExample', [])
  23409. .controller('DateController', ['$scope', function($scope) {
  23410. $scope.example = {
  23411. value: new Date(2013, 9, 1)
  23412. };
  23413. }]);
  23414. </script>
  23415. <form name="myForm" ng-controller="DateController as dateCtrl">
  23416. <label for="exampleInput">Pick a month in 2013:</label>
  23417. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  23418. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  23419. <div role="alert">
  23420. <span class="error" ng-show="myForm.input.$error.required">
  23421. Required!</span>
  23422. <span class="error" ng-show="myForm.input.$error.month">
  23423. Not a valid month!</span>
  23424. </div>
  23425. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  23426. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23427. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23428. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23429. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23430. </form>
  23431. </file>
  23432. <file name="protractor.js" type="protractor">
  23433. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  23434. var valid = element(by.binding('myForm.input.$valid'));
  23435. // currently protractor/webdriver does not support
  23436. // sending keys to all known HTML5 input controls
  23437. // for various browsers (https://github.com/angular/protractor/issues/562).
  23438. function setInput(val) {
  23439. // set the value of the element and force validation.
  23440. var scr = "var ipt = document.getElementById('exampleInput'); " +
  23441. "ipt.value = '" + val + "';" +
  23442. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  23443. browser.executeScript(scr);
  23444. }
  23445. it('should initialize to model', function() {
  23446. expect(value.getText()).toContain('2013-10');
  23447. expect(valid.getText()).toContain('myForm.input.$valid = true');
  23448. });
  23449. it('should be invalid if empty', function() {
  23450. setInput('');
  23451. expect(value.getText()).toEqual('value =');
  23452. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23453. });
  23454. it('should be invalid if over max', function() {
  23455. setInput('2015-01');
  23456. expect(value.getText()).toContain('');
  23457. expect(valid.getText()).toContain('myForm.input.$valid = false');
  23458. });
  23459. </file>
  23460. </example>
  23461. */
  23462. 'month': createDateInputType('month', MONTH_REGEXP,
  23463. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  23464. 'yyyy-MM'),
  23465. /**
  23466. * @ngdoc input
  23467. * @name input[number]
  23468. *
  23469. * @description
  23470. * Text input with number validation and transformation. Sets the `number` validation
  23471. * error if not a valid number.
  23472. *
  23473. * <div class="alert alert-warning">
  23474. * The model must always be of type `number` otherwise AngularJS will throw an error.
  23475. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  23476. * error docs for more information and an example of how to convert your model if necessary.
  23477. * </div>
  23478. *
  23479. *
  23480. *
  23481. * @knownIssue
  23482. *
  23483. * ### HTML5 constraint validation and `allowInvalid`
  23484. *
  23485. * In browsers that follow the
  23486. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  23487. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  23488. * If a non-number is entered in the input, the browser will report the value as an empty string,
  23489. * which means the view / model values in `ngModel` and subsequently the scope value
  23490. * will also be an empty string.
  23491. *
  23492. * @knownIssue
  23493. *
  23494. * ### Large numbers and `step` validation
  23495. *
  23496. * The `step` validation will not work correctly for very large numbers (e.g. 9999999999) due to
  23497. * Javascript's arithmetic limitations. If you need to handle large numbers, purpose-built
  23498. * libraries (e.g. https://github.com/MikeMcl/big.js/), can be included into AngularJS by
  23499. * {@link guide/forms#modifying-built-in-validators overwriting the validators}
  23500. * for `number` and / or `step`, or by {@link guide/forms#custom-validation applying custom validators}
  23501. * to an `input[text]` element. The source for `input[number]` type can be used as a starting
  23502. * point for both implementations.
  23503. *
  23504. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23505. * @param {string=} name Property name of the form under which the control is published.
  23506. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  23507. * Can be interpolated.
  23508. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  23509. * Can be interpolated.
  23510. * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
  23511. * but does not trigger HTML5 native validation. Takes an expression.
  23512. * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
  23513. * but does not trigger HTML5 native validation. Takes an expression.
  23514. * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
  23515. * Can be interpolated.
  23516. * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,
  23517. * but does not trigger HTML5 native validation. Takes an expression.
  23518. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23519. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23520. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23521. * `required` when you want to data-bind to the `required` attribute.
  23522. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23523. * minlength.
  23524. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23525. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  23526. * any length.
  23527. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  23528. * that contains the regular expression body that will be converted to a regular expression
  23529. * as in the ngPattern directive.
  23530. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23531. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  23532. * If the expression evaluates to a RegExp object, then this is used directly.
  23533. * If the expression evaluates to a string, then it will be converted to a RegExp
  23534. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23535. * `new RegExp('^abc$')`.<br />
  23536. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23537. * start at the index of the last search's match, thus not taking the whole input value into
  23538. * account.
  23539. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23540. * interaction with the input element.
  23541. *
  23542. * @example
  23543. <example name="number-input-directive" module="numberExample">
  23544. <file name="index.html">
  23545. <script>
  23546. angular.module('numberExample', [])
  23547. .controller('ExampleController', ['$scope', function($scope) {
  23548. $scope.example = {
  23549. value: 12
  23550. };
  23551. }]);
  23552. </script>
  23553. <form name="myForm" ng-controller="ExampleController">
  23554. <label>Number:
  23555. <input type="number" name="input" ng-model="example.value"
  23556. min="0" max="99" required>
  23557. </label>
  23558. <div role="alert">
  23559. <span class="error" ng-show="myForm.input.$error.required">
  23560. Required!</span>
  23561. <span class="error" ng-show="myForm.input.$error.number">
  23562. Not valid number!</span>
  23563. </div>
  23564. <tt>value = {{example.value}}</tt><br/>
  23565. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23566. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23567. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23568. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23569. </form>
  23570. </file>
  23571. <file name="protractor.js" type="protractor">
  23572. var value = element(by.binding('example.value'));
  23573. var valid = element(by.binding('myForm.input.$valid'));
  23574. var input = element(by.model('example.value'));
  23575. it('should initialize to model', function() {
  23576. expect(value.getText()).toContain('12');
  23577. expect(valid.getText()).toContain('true');
  23578. });
  23579. it('should be invalid if empty', function() {
  23580. input.clear();
  23581. input.sendKeys('');
  23582. expect(value.getText()).toEqual('value =');
  23583. expect(valid.getText()).toContain('false');
  23584. });
  23585. it('should be invalid if over max', function() {
  23586. input.clear();
  23587. input.sendKeys('123');
  23588. expect(value.getText()).toEqual('value =');
  23589. expect(valid.getText()).toContain('false');
  23590. });
  23591. </file>
  23592. </example>
  23593. */
  23594. 'number': numberInputType,
  23595. /**
  23596. * @ngdoc input
  23597. * @name input[url]
  23598. *
  23599. * @description
  23600. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  23601. * valid URL.
  23602. *
  23603. * <div class="alert alert-warning">
  23604. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  23605. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  23606. * the built-in validators (see the {@link guide/forms Forms guide})
  23607. * </div>
  23608. *
  23609. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23610. * @param {string=} name Property name of the form under which the control is published.
  23611. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23612. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23613. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23614. * `required` when you want to data-bind to the `required` attribute.
  23615. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23616. * minlength.
  23617. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23618. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  23619. * any length.
  23620. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  23621. * that contains the regular expression body that will be converted to a regular expression
  23622. * as in the ngPattern directive.
  23623. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23624. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  23625. * If the expression evaluates to a RegExp object, then this is used directly.
  23626. * If the expression evaluates to a string, then it will be converted to a RegExp
  23627. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23628. * `new RegExp('^abc$')`.<br />
  23629. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23630. * start at the index of the last search's match, thus not taking the whole input value into
  23631. * account.
  23632. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23633. * interaction with the input element.
  23634. *
  23635. * @example
  23636. <example name="url-input-directive" module="urlExample">
  23637. <file name="index.html">
  23638. <script>
  23639. angular.module('urlExample', [])
  23640. .controller('ExampleController', ['$scope', function($scope) {
  23641. $scope.url = {
  23642. text: 'http://google.com'
  23643. };
  23644. }]);
  23645. </script>
  23646. <form name="myForm" ng-controller="ExampleController">
  23647. <label>URL:
  23648. <input type="url" name="input" ng-model="url.text" required>
  23649. <label>
  23650. <div role="alert">
  23651. <span class="error" ng-show="myForm.input.$error.required">
  23652. Required!</span>
  23653. <span class="error" ng-show="myForm.input.$error.url">
  23654. Not valid url!</span>
  23655. </div>
  23656. <tt>text = {{url.text}}</tt><br/>
  23657. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23658. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23659. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23660. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23661. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  23662. </form>
  23663. </file>
  23664. <file name="protractor.js" type="protractor">
  23665. var text = element(by.binding('url.text'));
  23666. var valid = element(by.binding('myForm.input.$valid'));
  23667. var input = element(by.model('url.text'));
  23668. it('should initialize to model', function() {
  23669. expect(text.getText()).toContain('http://google.com');
  23670. expect(valid.getText()).toContain('true');
  23671. });
  23672. it('should be invalid if empty', function() {
  23673. input.clear();
  23674. input.sendKeys('');
  23675. expect(text.getText()).toEqual('text =');
  23676. expect(valid.getText()).toContain('false');
  23677. });
  23678. it('should be invalid if not url', function() {
  23679. input.clear();
  23680. input.sendKeys('box');
  23681. expect(valid.getText()).toContain('false');
  23682. });
  23683. </file>
  23684. </example>
  23685. */
  23686. 'url': urlInputType,
  23687. /**
  23688. * @ngdoc input
  23689. * @name input[email]
  23690. *
  23691. * @description
  23692. * Text input with email validation. Sets the `email` validation error key if not a valid email
  23693. * address.
  23694. *
  23695. * <div class="alert alert-warning">
  23696. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  23697. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  23698. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  23699. * </div>
  23700. *
  23701. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23702. * @param {string=} name Property name of the form under which the control is published.
  23703. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23704. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23705. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23706. * `required` when you want to data-bind to the `required` attribute.
  23707. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23708. * minlength.
  23709. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23710. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  23711. * any length.
  23712. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  23713. * that contains the regular expression body that will be converted to a regular expression
  23714. * as in the ngPattern directive.
  23715. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23716. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  23717. * If the expression evaluates to a RegExp object, then this is used directly.
  23718. * If the expression evaluates to a string, then it will be converted to a RegExp
  23719. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23720. * `new RegExp('^abc$')`.<br />
  23721. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23722. * start at the index of the last search's match, thus not taking the whole input value into
  23723. * account.
  23724. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23725. * interaction with the input element.
  23726. *
  23727. * @example
  23728. <example name="email-input-directive" module="emailExample">
  23729. <file name="index.html">
  23730. <script>
  23731. angular.module('emailExample', [])
  23732. .controller('ExampleController', ['$scope', function($scope) {
  23733. $scope.email = {
  23734. text: 'me@example.com'
  23735. };
  23736. }]);
  23737. </script>
  23738. <form name="myForm" ng-controller="ExampleController">
  23739. <label>Email:
  23740. <input type="email" name="input" ng-model="email.text" required>
  23741. </label>
  23742. <div role="alert">
  23743. <span class="error" ng-show="myForm.input.$error.required">
  23744. Required!</span>
  23745. <span class="error" ng-show="myForm.input.$error.email">
  23746. Not valid email!</span>
  23747. </div>
  23748. <tt>text = {{email.text}}</tt><br/>
  23749. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  23750. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  23751. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23752. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23753. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  23754. </form>
  23755. </file>
  23756. <file name="protractor.js" type="protractor">
  23757. var text = element(by.binding('email.text'));
  23758. var valid = element(by.binding('myForm.input.$valid'));
  23759. var input = element(by.model('email.text'));
  23760. it('should initialize to model', function() {
  23761. expect(text.getText()).toContain('me@example.com');
  23762. expect(valid.getText()).toContain('true');
  23763. });
  23764. it('should be invalid if empty', function() {
  23765. input.clear();
  23766. input.sendKeys('');
  23767. expect(text.getText()).toEqual('text =');
  23768. expect(valid.getText()).toContain('false');
  23769. });
  23770. it('should be invalid if not email', function() {
  23771. input.clear();
  23772. input.sendKeys('xxx');
  23773. expect(valid.getText()).toContain('false');
  23774. });
  23775. </file>
  23776. </example>
  23777. */
  23778. 'email': emailInputType,
  23779. /**
  23780. * @ngdoc input
  23781. * @name input[radio]
  23782. *
  23783. * @description
  23784. * HTML radio button.
  23785. *
  23786. * **Note:**<br>
  23787. * All inputs controlled by {@link ngModel ngModel} (including those of type `radio`) will use the
  23788. * value of their `name` attribute to determine the property under which their
  23789. * {@link ngModel.NgModelController NgModelController} will be published on the parent
  23790. * {@link form.FormController FormController}. Thus, if you use the same `name` for multiple
  23791. * inputs of a form (e.g. a group of radio inputs), only _one_ `NgModelController` will be
  23792. * published on the parent `FormController` under that name. The rest of the controllers will
  23793. * continue to work as expected, but you won't be able to access them as properties on the parent
  23794. * `FormController`.
  23795. *
  23796. * <div class="alert alert-info">
  23797. * <p>
  23798. * In plain HTML forms, the `name` attribute is used to identify groups of radio inputs, so
  23799. * that the browser can manage their state (checked/unchecked) based on the state of other
  23800. * inputs in the same group.
  23801. * </p>
  23802. * <p>
  23803. * In AngularJS forms, this is not necessary. The input's state will be updated based on the
  23804. * value of the underlying model data.
  23805. * </p>
  23806. * </div>
  23807. *
  23808. * <div class="alert alert-success">
  23809. * If you omit the `name` attribute on a radio input, `ngModel` will automatically assign it a
  23810. * unique name.
  23811. * </div>
  23812. *
  23813. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23814. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  23815. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  23816. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  23817. * @param {string=} name Property name of the form under which the control is published.
  23818. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23819. * interaction with the input element.
  23820. * @param {string} ngValue AngularJS expression to which `ngModel` will be be set when the radio
  23821. * is selected. Should be used instead of the `value` attribute if you need
  23822. * a non-string `ngModel` (`boolean`, `array`, ...).
  23823. *
  23824. * @example
  23825. <example name="radio-input-directive" module="radioExample">
  23826. <file name="index.html">
  23827. <script>
  23828. angular.module('radioExample', [])
  23829. .controller('ExampleController', ['$scope', function($scope) {
  23830. $scope.color = {
  23831. name: 'blue'
  23832. };
  23833. $scope.specialValue = {
  23834. "id": "12345",
  23835. "value": "green"
  23836. };
  23837. }]);
  23838. </script>
  23839. <form name="myForm" ng-controller="ExampleController">
  23840. <label>
  23841. <input type="radio" ng-model="color.name" value="red">
  23842. Red
  23843. </label><br/>
  23844. <label>
  23845. <input type="radio" ng-model="color.name" ng-value="specialValue">
  23846. Green
  23847. </label><br/>
  23848. <label>
  23849. <input type="radio" ng-model="color.name" value="blue">
  23850. Blue
  23851. </label><br/>
  23852. <tt>color = {{color.name | json}}</tt><br/>
  23853. </form>
  23854. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  23855. </file>
  23856. <file name="protractor.js" type="protractor">
  23857. it('should change state', function() {
  23858. var inputs = element.all(by.model('color.name'));
  23859. var color = element(by.binding('color.name'));
  23860. expect(color.getText()).toContain('blue');
  23861. inputs.get(0).click();
  23862. expect(color.getText()).toContain('red');
  23863. inputs.get(1).click();
  23864. expect(color.getText()).toContain('green');
  23865. });
  23866. </file>
  23867. </example>
  23868. */
  23869. 'radio': radioInputType,
  23870. /**
  23871. * @ngdoc input
  23872. * @name input[range]
  23873. *
  23874. * @description
  23875. * Native range input with validation and transformation.
  23876. *
  23877. * The model for the range input must always be a `Number`.
  23878. *
  23879. * IE9 and other browsers that do not support the `range` type fall back
  23880. * to a text input without any default values for `min`, `max` and `step`. Model binding,
  23881. * validation and number parsing are nevertheless supported.
  23882. *
  23883. * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
  23884. * in a way that never allows the input to hold an invalid value. That means:
  23885. * - any non-numerical value is set to `(max + min) / 2`.
  23886. * - any numerical value that is less than the current min val, or greater than the current max val
  23887. * is set to the min / max val respectively.
  23888. * - additionally, the current `step` is respected, so the nearest value that satisfies a step
  23889. * is used.
  23890. *
  23891. * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
  23892. * for more info.
  23893. *
  23894. * This has the following consequences for AngularJS:
  23895. *
  23896. * Since the element value should always reflect the current model value, a range input
  23897. * will set the bound ngModel expression to the value that the browser has set for the
  23898. * input element. For example, in the following input `<input type="range" ng-model="model.value">`,
  23899. * if the application sets `model.value = null`, the browser will set the input to `'50'`.
  23900. * AngularJS will then set the model to `50`, to prevent input and model value being out of sync.
  23901. *
  23902. * That means the model for range will immediately be set to `50` after `ngModel` has been
  23903. * initialized. It also means a range input can never have the required error.
  23904. *
  23905. * This does not only affect changes to the model value, but also to the values of the `min`,
  23906. * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
  23907. * the input value, AngularJS will also update the model value.
  23908. *
  23909. * Automatic value adjustment also means that a range input element can never have the `required`,
  23910. * `min`, or `max` errors.
  23911. *
  23912. * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
  23913. * when the step value changes dynamically - they do not adjust the element value correctly, but
  23914. * instead may set the `stepMismatch` error. If that's the case, the AngularJS will set the `step`
  23915. * error on the input, and set the model to `undefined`.
  23916. *
  23917. * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
  23918. * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
  23919. * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
  23920. *
  23921. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23922. * @param {string=} name Property name of the form under which the control is published.
  23923. * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
  23924. * than `min`. Can be interpolated.
  23925. * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
  23926. * Can be interpolated.
  23927. * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
  23928. * Can be interpolated.
  23929. * @param {expression=} ngChange AngularJS expression to be executed when the ngModel value changes due
  23930. * to user interaction with the input element.
  23931. * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
  23932. * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
  23933. * Checkout {@link ng.directive:ngChecked ngChecked} for usage.
  23934. *
  23935. * @example
  23936. <example name="range-input-directive" module="rangeExample">
  23937. <file name="index.html">
  23938. <script>
  23939. angular.module('rangeExample', [])
  23940. .controller('ExampleController', ['$scope', function($scope) {
  23941. $scope.value = 75;
  23942. $scope.min = 10;
  23943. $scope.max = 90;
  23944. }]);
  23945. </script>
  23946. <form name="myForm" ng-controller="ExampleController">
  23947. Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
  23948. <hr>
  23949. Model as number: <input type="number" ng-model="value"><br>
  23950. Min: <input type="number" ng-model="min"><br>
  23951. Max: <input type="number" ng-model="max"><br>
  23952. value = <code>{{value}}</code><br/>
  23953. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  23954. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  23955. </form>
  23956. </file>
  23957. </example>
  23958. * ## Range Input with ngMin & ngMax attributes
  23959. * @example
  23960. <example name="range-input-directive-ng" module="rangeExample">
  23961. <file name="index.html">
  23962. <script>
  23963. angular.module('rangeExample', [])
  23964. .controller('ExampleController', ['$scope', function($scope) {
  23965. $scope.value = 75;
  23966. $scope.min = 10;
  23967. $scope.max = 90;
  23968. }]);
  23969. </script>
  23970. <form name="myForm" ng-controller="ExampleController">
  23971. Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
  23972. <hr>
  23973. Model as number: <input type="number" ng-model="value"><br>
  23974. Min: <input type="number" ng-model="min"><br>
  23975. Max: <input type="number" ng-model="max"><br>
  23976. value = <code>{{value}}</code><br/>
  23977. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  23978. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  23979. </form>
  23980. </file>
  23981. </example>
  23982. */
  23983. 'range': rangeInputType,
  23984. /**
  23985. * @ngdoc input
  23986. * @name input[checkbox]
  23987. *
  23988. * @description
  23989. * HTML checkbox.
  23990. *
  23991. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  23992. * @param {string=} name Property name of the form under which the control is published.
  23993. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  23994. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  23995. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  23996. * interaction with the input element.
  23997. *
  23998. * @example
  23999. <example name="checkbox-input-directive" module="checkboxExample">
  24000. <file name="index.html">
  24001. <script>
  24002. angular.module('checkboxExample', [])
  24003. .controller('ExampleController', ['$scope', function($scope) {
  24004. $scope.checkboxModel = {
  24005. value1 : true,
  24006. value2 : 'YES'
  24007. };
  24008. }]);
  24009. </script>
  24010. <form name="myForm" ng-controller="ExampleController">
  24011. <label>Value1:
  24012. <input type="checkbox" ng-model="checkboxModel.value1">
  24013. </label><br/>
  24014. <label>Value2:
  24015. <input type="checkbox" ng-model="checkboxModel.value2"
  24016. ng-true-value="'YES'" ng-false-value="'NO'">
  24017. </label><br/>
  24018. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  24019. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  24020. </form>
  24021. </file>
  24022. <file name="protractor.js" type="protractor">
  24023. it('should change state', function() {
  24024. var value1 = element(by.binding('checkboxModel.value1'));
  24025. var value2 = element(by.binding('checkboxModel.value2'));
  24026. expect(value1.getText()).toContain('true');
  24027. expect(value2.getText()).toContain('YES');
  24028. element(by.model('checkboxModel.value1')).click();
  24029. element(by.model('checkboxModel.value2')).click();
  24030. expect(value1.getText()).toContain('false');
  24031. expect(value2.getText()).toContain('NO');
  24032. });
  24033. </file>
  24034. </example>
  24035. */
  24036. 'checkbox': checkboxInputType,
  24037. 'hidden': noop,
  24038. 'button': noop,
  24039. 'submit': noop,
  24040. 'reset': noop,
  24041. 'file': noop
  24042. };
  24043. function stringBasedInputType(ctrl) {
  24044. ctrl.$formatters.push(function(value) {
  24045. return ctrl.$isEmpty(value) ? value : value.toString();
  24046. });
  24047. }
  24048. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  24049. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24050. stringBasedInputType(ctrl);
  24051. }
  24052. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  24053. var type = lowercase(element[0].type);
  24054. // In composition mode, users are still inputting intermediate text buffer,
  24055. // hold the listener until composition is done.
  24056. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  24057. if (!$sniffer.android) {
  24058. var composing = false;
  24059. element.on('compositionstart', function() {
  24060. composing = true;
  24061. });
  24062. // Support: IE9+
  24063. element.on('compositionupdate', function(ev) {
  24064. // End composition when ev.data is empty string on 'compositionupdate' event.
  24065. // When the input de-focusses (e.g. by clicking away), IE triggers 'compositionupdate'
  24066. // instead of 'compositionend'.
  24067. if (isUndefined(ev.data) || ev.data === '') {
  24068. composing = false;
  24069. }
  24070. });
  24071. element.on('compositionend', function() {
  24072. composing = false;
  24073. listener();
  24074. });
  24075. }
  24076. var timeout;
  24077. var listener = function(ev) {
  24078. if (timeout) {
  24079. $browser.defer.cancel(timeout);
  24080. timeout = null;
  24081. }
  24082. if (composing) return;
  24083. var value = element.val(),
  24084. event = ev && ev.type;
  24085. // By default we will trim the value
  24086. // If the attribute ng-trim exists we will avoid trimming
  24087. // If input type is 'password', the value is never trimmed
  24088. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  24089. value = trim(value);
  24090. }
  24091. // If a control is suffering from bad input (due to native validators), browsers discard its
  24092. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  24093. // control's value is the same empty value twice in a row.
  24094. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  24095. ctrl.$setViewValue(value, event);
  24096. }
  24097. };
  24098. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  24099. // input event on backspace, delete or cut
  24100. if ($sniffer.hasEvent('input')) {
  24101. element.on('input', listener);
  24102. } else {
  24103. var deferListener = function(ev, input, origValue) {
  24104. if (!timeout) {
  24105. timeout = $browser.defer(function() {
  24106. timeout = null;
  24107. if (!input || input.value !== origValue) {
  24108. listener(ev);
  24109. }
  24110. });
  24111. }
  24112. };
  24113. element.on('keydown', /** @this */ function(event) {
  24114. var key = event.keyCode;
  24115. // ignore
  24116. // command modifiers arrows
  24117. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  24118. deferListener(event, this, this.value);
  24119. });
  24120. // if user modifies input value using context menu in IE, we need "paste", "cut" and "drop" events to catch it
  24121. if ($sniffer.hasEvent('paste')) {
  24122. element.on('paste cut drop', deferListener);
  24123. }
  24124. }
  24125. // if user paste into input using mouse on older browser
  24126. // or form autocomplete on newer browser, we need "change" event to catch it
  24127. element.on('change', listener);
  24128. // Some native input types (date-family) have the ability to change validity without
  24129. // firing any input/change events.
  24130. // For these event types, when native validators are present and the browser supports the type,
  24131. // check for validity changes on various DOM events.
  24132. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  24133. element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
  24134. if (!timeout) {
  24135. var validity = this[VALIDITY_STATE_PROPERTY];
  24136. var origBadInput = validity.badInput;
  24137. var origTypeMismatch = validity.typeMismatch;
  24138. timeout = $browser.defer(function() {
  24139. timeout = null;
  24140. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  24141. listener(ev);
  24142. }
  24143. });
  24144. }
  24145. });
  24146. }
  24147. ctrl.$render = function() {
  24148. // Workaround for Firefox validation #12102.
  24149. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  24150. if (element.val() !== value) {
  24151. element.val(value);
  24152. }
  24153. };
  24154. }
  24155. function weekParser(isoWeek, existingDate) {
  24156. if (isDate(isoWeek)) {
  24157. return isoWeek;
  24158. }
  24159. if (isString(isoWeek)) {
  24160. WEEK_REGEXP.lastIndex = 0;
  24161. var parts = WEEK_REGEXP.exec(isoWeek);
  24162. if (parts) {
  24163. var year = +parts[1],
  24164. week = +parts[2],
  24165. hours = 0,
  24166. minutes = 0,
  24167. seconds = 0,
  24168. milliseconds = 0,
  24169. firstThurs = getFirstThursdayOfYear(year),
  24170. addDays = (week - 1) * 7;
  24171. if (existingDate) {
  24172. hours = existingDate.getHours();
  24173. minutes = existingDate.getMinutes();
  24174. seconds = existingDate.getSeconds();
  24175. milliseconds = existingDate.getMilliseconds();
  24176. }
  24177. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  24178. }
  24179. }
  24180. return NaN;
  24181. }
  24182. function createDateParser(regexp, mapping) {
  24183. return function(iso, previousDate) {
  24184. var parts, map;
  24185. if (isDate(iso)) {
  24186. return iso;
  24187. }
  24188. if (isString(iso)) {
  24189. // When a date is JSON'ified to wraps itself inside of an extra
  24190. // set of double quotes. This makes the date parsing code unable
  24191. // to match the date string and parse it as a date.
  24192. if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
  24193. iso = iso.substring(1, iso.length - 1);
  24194. }
  24195. if (ISO_DATE_REGEXP.test(iso)) {
  24196. return new Date(iso);
  24197. }
  24198. regexp.lastIndex = 0;
  24199. parts = regexp.exec(iso);
  24200. if (parts) {
  24201. parts.shift();
  24202. if (previousDate) {
  24203. map = {
  24204. yyyy: previousDate.getFullYear(),
  24205. MM: previousDate.getMonth() + 1,
  24206. dd: previousDate.getDate(),
  24207. HH: previousDate.getHours(),
  24208. mm: previousDate.getMinutes(),
  24209. ss: previousDate.getSeconds(),
  24210. sss: previousDate.getMilliseconds() / 1000
  24211. };
  24212. } else {
  24213. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  24214. }
  24215. forEach(parts, function(part, index) {
  24216. if (index < mapping.length) {
  24217. map[mapping[index]] = +part;
  24218. }
  24219. });
  24220. var date = new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  24221. if (map.yyyy < 100) {
  24222. // In the constructor, 2-digit years map to 1900-1999.
  24223. // Use `setFullYear()` to set the correct year.
  24224. date.setFullYear(map.yyyy);
  24225. }
  24226. return date;
  24227. }
  24228. }
  24229. return NaN;
  24230. };
  24231. }
  24232. function createDateInputType(type, regexp, parseDate, format) {
  24233. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  24234. badInputChecker(scope, element, attr, ctrl, type);
  24235. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24236. var isTimeType = type === 'time' || type === 'datetimelocal';
  24237. var previousDate;
  24238. var previousTimezone;
  24239. ctrl.$parsers.push(function(value) {
  24240. if (ctrl.$isEmpty(value)) return null;
  24241. if (regexp.test(value)) {
  24242. // Note: We cannot read ctrl.$modelValue, as there might be a different
  24243. // parser/formatter in the processing chain so that the model
  24244. // contains some different data format!
  24245. return parseDateAndConvertTimeZoneToLocal(value, previousDate);
  24246. }
  24247. ctrl.$$parserName = type;
  24248. return undefined;
  24249. });
  24250. ctrl.$formatters.push(function(value) {
  24251. if (value && !isDate(value)) {
  24252. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  24253. }
  24254. if (isValidDate(value)) {
  24255. previousDate = value;
  24256. var timezone = ctrl.$options.getOption('timezone');
  24257. if (timezone) {
  24258. previousTimezone = timezone;
  24259. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  24260. }
  24261. return formatter(value, timezone);
  24262. } else {
  24263. previousDate = null;
  24264. previousTimezone = null;
  24265. return '';
  24266. }
  24267. });
  24268. if (isDefined(attr.min) || attr.ngMin) {
  24269. var minVal;
  24270. ctrl.$validators.min = function(value) {
  24271. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  24272. };
  24273. attr.$observe('min', function(val) {
  24274. minVal = parseObservedDateValue(val);
  24275. ctrl.$validate();
  24276. });
  24277. }
  24278. if (isDefined(attr.max) || attr.ngMax) {
  24279. var maxVal;
  24280. ctrl.$validators.max = function(value) {
  24281. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  24282. };
  24283. attr.$observe('max', function(val) {
  24284. maxVal = parseObservedDateValue(val);
  24285. ctrl.$validate();
  24286. });
  24287. }
  24288. function isValidDate(value) {
  24289. // Invalid Date: getTime() returns NaN
  24290. return value && !(value.getTime && value.getTime() !== value.getTime());
  24291. }
  24292. function parseObservedDateValue(val) {
  24293. return isDefined(val) && !isDate(val) ? parseDateAndConvertTimeZoneToLocal(val) || undefined : val;
  24294. }
  24295. function parseDateAndConvertTimeZoneToLocal(value, previousDate) {
  24296. var timezone = ctrl.$options.getOption('timezone');
  24297. if (previousTimezone && previousTimezone !== timezone) {
  24298. // If the timezone has changed, adjust the previousDate to the default timezone
  24299. // so that the new date is converted with the correct timezone offset
  24300. previousDate = addDateMinutes(previousDate, timezoneToOffset(previousTimezone));
  24301. }
  24302. var parsedDate = parseDate(value, previousDate);
  24303. if (!isNaN(parsedDate) && timezone) {
  24304. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  24305. }
  24306. return parsedDate;
  24307. }
  24308. function formatter(value, timezone) {
  24309. var targetFormat = format;
  24310. if (isTimeType && isString(ctrl.$options.getOption('timeSecondsFormat'))) {
  24311. targetFormat = format
  24312. .replace('ss.sss', ctrl.$options.getOption('timeSecondsFormat'))
  24313. .replace(/:$/, '');
  24314. }
  24315. var formatted = $filter('date')(value, targetFormat, timezone);
  24316. if (isTimeType && ctrl.$options.getOption('timeStripZeroSeconds')) {
  24317. formatted = formatted.replace(/(?::00)?(?:\.000)?$/, '');
  24318. }
  24319. return formatted;
  24320. }
  24321. };
  24322. }
  24323. function badInputChecker(scope, element, attr, ctrl, parserName) {
  24324. var node = element[0];
  24325. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  24326. if (nativeValidation) {
  24327. ctrl.$parsers.push(function(value) {
  24328. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  24329. if (validity.badInput || validity.typeMismatch) {
  24330. ctrl.$$parserName = parserName;
  24331. return undefined;
  24332. }
  24333. return value;
  24334. });
  24335. }
  24336. }
  24337. function numberFormatterParser(ctrl) {
  24338. ctrl.$parsers.push(function(value) {
  24339. if (ctrl.$isEmpty(value)) return null;
  24340. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  24341. ctrl.$$parserName = 'number';
  24342. return undefined;
  24343. });
  24344. ctrl.$formatters.push(function(value) {
  24345. if (!ctrl.$isEmpty(value)) {
  24346. if (!isNumber(value)) {
  24347. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  24348. }
  24349. value = value.toString();
  24350. }
  24351. return value;
  24352. });
  24353. }
  24354. function parseNumberAttrVal(val) {
  24355. if (isDefined(val) && !isNumber(val)) {
  24356. val = parseFloat(val);
  24357. }
  24358. return !isNumberNaN(val) ? val : undefined;
  24359. }
  24360. function isNumberInteger(num) {
  24361. // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
  24362. // (minus the assumption that `num` is a number)
  24363. // eslint-disable-next-line no-bitwise
  24364. return (num | 0) === num;
  24365. }
  24366. function countDecimals(num) {
  24367. var numString = num.toString();
  24368. var decimalSymbolIndex = numString.indexOf('.');
  24369. if (decimalSymbolIndex === -1) {
  24370. if (-1 < num && num < 1) {
  24371. // It may be in the exponential notation format (`1e-X`)
  24372. var match = /e-(\d+)$/.exec(numString);
  24373. if (match) {
  24374. return Number(match[1]);
  24375. }
  24376. }
  24377. return 0;
  24378. }
  24379. return numString.length - decimalSymbolIndex - 1;
  24380. }
  24381. function isValidForStep(viewValue, stepBase, step) {
  24382. // At this point `stepBase` and `step` are expected to be non-NaN values
  24383. // and `viewValue` is expected to be a valid stringified number.
  24384. var value = Number(viewValue);
  24385. var isNonIntegerValue = !isNumberInteger(value);
  24386. var isNonIntegerStepBase = !isNumberInteger(stepBase);
  24387. var isNonIntegerStep = !isNumberInteger(step);
  24388. // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
  24389. // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
  24390. if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) {
  24391. var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0;
  24392. var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0;
  24393. var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0;
  24394. var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals);
  24395. var multiplier = Math.pow(10, decimalCount);
  24396. value = value * multiplier;
  24397. stepBase = stepBase * multiplier;
  24398. step = step * multiplier;
  24399. if (isNonIntegerValue) value = Math.round(value);
  24400. if (isNonIntegerStepBase) stepBase = Math.round(stepBase);
  24401. if (isNonIntegerStep) step = Math.round(step);
  24402. }
  24403. return (value - stepBase) % step === 0;
  24404. }
  24405. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  24406. badInputChecker(scope, element, attr, ctrl, 'number');
  24407. numberFormatterParser(ctrl);
  24408. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24409. var minVal;
  24410. var maxVal;
  24411. if (isDefined(attr.min) || attr.ngMin) {
  24412. ctrl.$validators.min = function(modelValue, viewValue) {
  24413. return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
  24414. };
  24415. attr.$observe('min', function(val) {
  24416. minVal = parseNumberAttrVal(val);
  24417. // TODO(matsko): implement validateLater to reduce number of validations
  24418. ctrl.$validate();
  24419. });
  24420. }
  24421. if (isDefined(attr.max) || attr.ngMax) {
  24422. ctrl.$validators.max = function(modelValue, viewValue) {
  24423. return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
  24424. };
  24425. attr.$observe('max', function(val) {
  24426. maxVal = parseNumberAttrVal(val);
  24427. // TODO(matsko): implement validateLater to reduce number of validations
  24428. ctrl.$validate();
  24429. });
  24430. }
  24431. if (isDefined(attr.step) || attr.ngStep) {
  24432. var stepVal;
  24433. ctrl.$validators.step = function(modelValue, viewValue) {
  24434. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  24435. isValidForStep(viewValue, minVal || 0, stepVal);
  24436. };
  24437. attr.$observe('step', function(val) {
  24438. stepVal = parseNumberAttrVal(val);
  24439. // TODO(matsko): implement validateLater to reduce number of validations
  24440. ctrl.$validate();
  24441. });
  24442. }
  24443. }
  24444. function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  24445. badInputChecker(scope, element, attr, ctrl, 'range');
  24446. numberFormatterParser(ctrl);
  24447. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24448. var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
  24449. minVal = supportsRange ? 0 : undefined,
  24450. maxVal = supportsRange ? 100 : undefined,
  24451. stepVal = supportsRange ? 1 : undefined,
  24452. validity = element[0].validity,
  24453. hasMinAttr = isDefined(attr.min),
  24454. hasMaxAttr = isDefined(attr.max),
  24455. hasStepAttr = isDefined(attr.step);
  24456. var originalRender = ctrl.$render;
  24457. ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
  24458. //Browsers that implement range will set these values automatically, but reading the adjusted values after
  24459. //$render would cause the min / max validators to be applied with the wrong value
  24460. function rangeRender() {
  24461. originalRender();
  24462. ctrl.$setViewValue(element.val());
  24463. } :
  24464. originalRender;
  24465. if (hasMinAttr) {
  24466. ctrl.$validators.min = supportsRange ?
  24467. // Since all browsers set the input to a valid value, we don't need to check validity
  24468. function noopMinValidator() { return true; } :
  24469. // non-support browsers validate the min val
  24470. function minValidator(modelValue, viewValue) {
  24471. return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
  24472. };
  24473. setInitialValueAndObserver('min', minChange);
  24474. }
  24475. if (hasMaxAttr) {
  24476. ctrl.$validators.max = supportsRange ?
  24477. // Since all browsers set the input to a valid value, we don't need to check validity
  24478. function noopMaxValidator() { return true; } :
  24479. // non-support browsers validate the max val
  24480. function maxValidator(modelValue, viewValue) {
  24481. return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
  24482. };
  24483. setInitialValueAndObserver('max', maxChange);
  24484. }
  24485. if (hasStepAttr) {
  24486. ctrl.$validators.step = supportsRange ?
  24487. function nativeStepValidator() {
  24488. // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
  24489. // input element value to a valid value). It's possible that other browsers set the stepMismatch
  24490. // validity error instead, so we can at least report an error in that case.
  24491. return !validity.stepMismatch;
  24492. } :
  24493. // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
  24494. function stepValidator(modelValue, viewValue) {
  24495. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  24496. isValidForStep(viewValue, minVal || 0, stepVal);
  24497. };
  24498. setInitialValueAndObserver('step', stepChange);
  24499. }
  24500. function setInitialValueAndObserver(htmlAttrName, changeFn) {
  24501. // interpolated attributes set the attribute value only after a digest, but we need the
  24502. // attribute value when the input is first rendered, so that the browser can adjust the
  24503. // input value based on the min/max value
  24504. element.attr(htmlAttrName, attr[htmlAttrName]);
  24505. attr.$observe(htmlAttrName, changeFn);
  24506. }
  24507. function minChange(val) {
  24508. minVal = parseNumberAttrVal(val);
  24509. // ignore changes before model is initialized
  24510. if (isNumberNaN(ctrl.$modelValue)) {
  24511. return;
  24512. }
  24513. if (supportsRange) {
  24514. var elVal = element.val();
  24515. // IE11 doesn't set the el val correctly if the minVal is greater than the element value
  24516. if (minVal > elVal) {
  24517. elVal = minVal;
  24518. element.val(elVal);
  24519. }
  24520. ctrl.$setViewValue(elVal);
  24521. } else {
  24522. // TODO(matsko): implement validateLater to reduce number of validations
  24523. ctrl.$validate();
  24524. }
  24525. }
  24526. function maxChange(val) {
  24527. maxVal = parseNumberAttrVal(val);
  24528. // ignore changes before model is initialized
  24529. if (isNumberNaN(ctrl.$modelValue)) {
  24530. return;
  24531. }
  24532. if (supportsRange) {
  24533. var elVal = element.val();
  24534. // IE11 doesn't set the el val correctly if the maxVal is less than the element value
  24535. if (maxVal < elVal) {
  24536. element.val(maxVal);
  24537. // IE11 and Chrome don't set the value to the minVal when max < min
  24538. elVal = maxVal < minVal ? minVal : maxVal;
  24539. }
  24540. ctrl.$setViewValue(elVal);
  24541. } else {
  24542. // TODO(matsko): implement validateLater to reduce number of validations
  24543. ctrl.$validate();
  24544. }
  24545. }
  24546. function stepChange(val) {
  24547. stepVal = parseNumberAttrVal(val);
  24548. // ignore changes before model is initialized
  24549. if (isNumberNaN(ctrl.$modelValue)) {
  24550. return;
  24551. }
  24552. // Some browsers don't adjust the input value correctly, but set the stepMismatch error
  24553. if (supportsRange && ctrl.$viewValue !== element.val()) {
  24554. ctrl.$setViewValue(element.val());
  24555. } else {
  24556. // TODO(matsko): implement validateLater to reduce number of validations
  24557. ctrl.$validate();
  24558. }
  24559. }
  24560. }
  24561. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  24562. // Note: no badInputChecker here by purpose as `url` is only a validation
  24563. // in browsers, i.e. we can always read out input.value even if it is not valid!
  24564. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24565. stringBasedInputType(ctrl);
  24566. ctrl.$validators.url = function(modelValue, viewValue) {
  24567. var value = modelValue || viewValue;
  24568. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  24569. };
  24570. }
  24571. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  24572. // Note: no badInputChecker here by purpose as `url` is only a validation
  24573. // in browsers, i.e. we can always read out input.value even if it is not valid!
  24574. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  24575. stringBasedInputType(ctrl);
  24576. ctrl.$validators.email = function(modelValue, viewValue) {
  24577. var value = modelValue || viewValue;
  24578. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  24579. };
  24580. }
  24581. function radioInputType(scope, element, attr, ctrl) {
  24582. var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
  24583. // make the name unique, if not defined
  24584. if (isUndefined(attr.name)) {
  24585. element.attr('name', nextUid());
  24586. }
  24587. var listener = function(ev) {
  24588. var value;
  24589. if (element[0].checked) {
  24590. value = attr.value;
  24591. if (doTrim) {
  24592. value = trim(value);
  24593. }
  24594. ctrl.$setViewValue(value, ev && ev.type);
  24595. }
  24596. };
  24597. element.on('change', listener);
  24598. ctrl.$render = function() {
  24599. var value = attr.value;
  24600. if (doTrim) {
  24601. value = trim(value);
  24602. }
  24603. element[0].checked = (value === ctrl.$viewValue);
  24604. };
  24605. attr.$observe('value', ctrl.$render);
  24606. }
  24607. function parseConstantExpr($parse, context, name, expression, fallback) {
  24608. var parseFn;
  24609. if (isDefined(expression)) {
  24610. parseFn = $parse(expression);
  24611. if (!parseFn.constant) {
  24612. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  24613. '`{1}`.', name, expression);
  24614. }
  24615. return parseFn(context);
  24616. }
  24617. return fallback;
  24618. }
  24619. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  24620. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  24621. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  24622. var listener = function(ev) {
  24623. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  24624. };
  24625. element.on('change', listener);
  24626. ctrl.$render = function() {
  24627. element[0].checked = ctrl.$viewValue;
  24628. };
  24629. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  24630. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  24631. // it to a boolean.
  24632. ctrl.$isEmpty = function(value) {
  24633. return value === false;
  24634. };
  24635. ctrl.$formatters.push(function(value) {
  24636. return equals(value, trueValue);
  24637. });
  24638. ctrl.$parsers.push(function(value) {
  24639. return value ? trueValue : falseValue;
  24640. });
  24641. }
  24642. /**
  24643. * @ngdoc directive
  24644. * @name textarea
  24645. * @restrict E
  24646. *
  24647. * @description
  24648. * HTML textarea element control with AngularJS data-binding. The data-binding and validation
  24649. * properties of this element are exactly the same as those of the
  24650. * {@link ng.directive:input input element}.
  24651. *
  24652. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  24653. * @param {string=} name Property name of the form under which the control is published.
  24654. * @param {string=} required Sets `required` validation error key if the value is not entered.
  24655. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  24656. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  24657. * `required` when you want to data-bind to the `required` attribute.
  24658. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  24659. * minlength.
  24660. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  24661. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  24662. * length.
  24663. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  24664. * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  24665. * If the expression evaluates to a RegExp object, then this is used directly.
  24666. * If the expression evaluates to a string, then it will be converted to a RegExp
  24667. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  24668. * `new RegExp('^abc$')`.<br />
  24669. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  24670. * start at the index of the last search's match, thus not taking the whole input value into
  24671. * account.
  24672. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  24673. * interaction with the input element.
  24674. * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input.
  24675. *
  24676. * @knownIssue
  24677. *
  24678. * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
  24679. * insert the placeholder value as the textarea's content. If the placeholder value contains
  24680. * interpolation (`{{ ... }}`), an error will be logged in the console when AngularJS tries to update
  24681. * the value of the by-then-removed text node. This doesn't affect the functionality of the
  24682. * textarea, but can be undesirable.
  24683. *
  24684. * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
  24685. * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
  24686. * find more details on `ngAttr` in the
  24687. * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
  24688. * Developer Guide.
  24689. */
  24690. /**
  24691. * @ngdoc directive
  24692. * @name input
  24693. * @restrict E
  24694. *
  24695. * @description
  24696. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  24697. * input state control, and validation.
  24698. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  24699. *
  24700. * <div class="alert alert-warning">
  24701. * **Note:** Not every feature offered is available for all input types.
  24702. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  24703. * </div>
  24704. *
  24705. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  24706. * @param {string=} name Property name of the form under which the control is published.
  24707. * @param {string=} required Sets `required` validation error key if the value is not entered.
  24708. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  24709. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  24710. * minlength.
  24711. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  24712. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  24713. * length.
  24714. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  24715. * value does not match a RegExp found by evaluating the AngularJS expression given in the attribute value.
  24716. * If the expression evaluates to a RegExp object, then this is used directly.
  24717. * If the expression evaluates to a string, then it will be converted to a RegExp
  24718. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  24719. * `new RegExp('^abc$')`.<br />
  24720. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  24721. * start at the index of the last search's match, thus not taking the whole input value into
  24722. * account.
  24723. * @param {string=} ngChange AngularJS expression to be executed when input changes due to user
  24724. * interaction with the input element.
  24725. * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input.
  24726. * This parameter is ignored for input[type=password] controls, which will never trim the
  24727. * input.
  24728. *
  24729. * @example
  24730. <example name="input-directive" module="inputExample">
  24731. <file name="index.html">
  24732. <script>
  24733. angular.module('inputExample', [])
  24734. .controller('ExampleController', ['$scope', function($scope) {
  24735. $scope.user = {name: 'guest', last: 'visitor'};
  24736. }]);
  24737. </script>
  24738. <div ng-controller="ExampleController">
  24739. <form name="myForm">
  24740. <label>
  24741. User name:
  24742. <input type="text" name="userName" ng-model="user.name" required>
  24743. </label>
  24744. <div role="alert">
  24745. <span class="error" ng-show="myForm.userName.$error.required">
  24746. Required!</span>
  24747. </div>
  24748. <label>
  24749. Last name:
  24750. <input type="text" name="lastName" ng-model="user.last"
  24751. ng-minlength="3" ng-maxlength="10">
  24752. </label>
  24753. <div role="alert">
  24754. <span class="error" ng-show="myForm.lastName.$error.minlength">
  24755. Too short!</span>
  24756. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  24757. Too long!</span>
  24758. </div>
  24759. </form>
  24760. <hr>
  24761. <tt>user = {{user}}</tt><br/>
  24762. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  24763. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  24764. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  24765. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  24766. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  24767. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  24768. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  24769. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  24770. </div>
  24771. </file>
  24772. <file name="protractor.js" type="protractor">
  24773. var user = element(by.exactBinding('user'));
  24774. var userNameValid = element(by.binding('myForm.userName.$valid'));
  24775. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  24776. var lastNameError = element(by.binding('myForm.lastName.$error'));
  24777. var formValid = element(by.binding('myForm.$valid'));
  24778. var userNameInput = element(by.model('user.name'));
  24779. var userLastInput = element(by.model('user.last'));
  24780. it('should initialize to model', function() {
  24781. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  24782. expect(userNameValid.getText()).toContain('true');
  24783. expect(formValid.getText()).toContain('true');
  24784. });
  24785. it('should be invalid if empty when required', function() {
  24786. userNameInput.clear();
  24787. userNameInput.sendKeys('');
  24788. expect(user.getText()).toContain('{"last":"visitor"}');
  24789. expect(userNameValid.getText()).toContain('false');
  24790. expect(formValid.getText()).toContain('false');
  24791. });
  24792. it('should be valid if empty when min length is set', function() {
  24793. userLastInput.clear();
  24794. userLastInput.sendKeys('');
  24795. expect(user.getText()).toContain('{"name":"guest","last":""}');
  24796. expect(lastNameValid.getText()).toContain('true');
  24797. expect(formValid.getText()).toContain('true');
  24798. });
  24799. it('should be invalid if less than required min length', function() {
  24800. userLastInput.clear();
  24801. userLastInput.sendKeys('xx');
  24802. expect(user.getText()).toContain('{"name":"guest"}');
  24803. expect(lastNameValid.getText()).toContain('false');
  24804. expect(lastNameError.getText()).toContain('minlength');
  24805. expect(formValid.getText()).toContain('false');
  24806. });
  24807. it('should be invalid if longer than max length', function() {
  24808. userLastInput.clear();
  24809. userLastInput.sendKeys('some ridiculously long name');
  24810. expect(user.getText()).toContain('{"name":"guest"}');
  24811. expect(lastNameValid.getText()).toContain('false');
  24812. expect(lastNameError.getText()).toContain('maxlength');
  24813. expect(formValid.getText()).toContain('false');
  24814. });
  24815. </file>
  24816. </example>
  24817. */
  24818. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  24819. function($browser, $sniffer, $filter, $parse) {
  24820. return {
  24821. restrict: 'E',
  24822. require: ['?ngModel'],
  24823. link: {
  24824. pre: function(scope, element, attr, ctrls) {
  24825. if (ctrls[0]) {
  24826. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  24827. $browser, $filter, $parse);
  24828. }
  24829. }
  24830. }
  24831. };
  24832. }];
  24833. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  24834. /**
  24835. * @ngdoc directive
  24836. * @name ngValue
  24837. * @restrict A
  24838. * @priority 100
  24839. *
  24840. * @description
  24841. * Binds the given expression to the value of the element.
  24842. *
  24843. * It is mainly used on {@link input[radio] `input[radio]`} and option elements,
  24844. * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
  24845. * {@link select `select`} parent element) is set to the bound value. It is especially useful
  24846. * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
  24847. *
  24848. * It can also be used to achieve one-way binding of a given expression to an input element
  24849. * such as an `input[text]` or a `textarea`, when that element does not use ngModel.
  24850. *
  24851. * @element ANY
  24852. * @param {string=} ngValue AngularJS expression, whose value will be bound to the `value` attribute
  24853. * and `value` property of the element.
  24854. *
  24855. * @example
  24856. <example name="ngValue-directive" module="valueExample">
  24857. <file name="index.html">
  24858. <script>
  24859. angular.module('valueExample', [])
  24860. .controller('ExampleController', ['$scope', function($scope) {
  24861. $scope.names = ['pizza', 'unicorns', 'robots'];
  24862. $scope.my = { favorite: 'unicorns' };
  24863. }]);
  24864. </script>
  24865. <form ng-controller="ExampleController">
  24866. <h2>Which is your favorite?</h2>
  24867. <label ng-repeat="name in names" for="{{name}}">
  24868. {{name}}
  24869. <input type="radio"
  24870. ng-model="my.favorite"
  24871. ng-value="name"
  24872. id="{{name}}"
  24873. name="favorite">
  24874. </label>
  24875. <div>You chose {{my.favorite}}</div>
  24876. </form>
  24877. </file>
  24878. <file name="protractor.js" type="protractor">
  24879. var favorite = element(by.binding('my.favorite'));
  24880. it('should initialize to model', function() {
  24881. expect(favorite.getText()).toContain('unicorns');
  24882. });
  24883. it('should bind the values to the inputs', function() {
  24884. element.all(by.model('my.favorite')).get(0).click();
  24885. expect(favorite.getText()).toContain('pizza');
  24886. });
  24887. </file>
  24888. </example>
  24889. */
  24890. var ngValueDirective = function() {
  24891. /**
  24892. * inputs use the value attribute as their default value if the value property is not set.
  24893. * Once the value property has been set (by adding input), it will not react to changes to
  24894. * the value attribute anymore. Setting both attribute and property fixes this behavior, and
  24895. * makes it possible to use ngValue as a sort of one-way bind.
  24896. */
  24897. function updateElementValue(element, attr, value) {
  24898. // Support: IE9 only
  24899. // In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`).
  24900. var propValue = isDefined(value) ? value : (msie === 9) ? '' : null;
  24901. element.prop('value', propValue);
  24902. attr.$set('value', value);
  24903. }
  24904. return {
  24905. restrict: 'A',
  24906. priority: 100,
  24907. compile: function(tpl, tplAttr) {
  24908. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  24909. return function ngValueConstantLink(scope, elm, attr) {
  24910. var value = scope.$eval(attr.ngValue);
  24911. updateElementValue(elm, attr, value);
  24912. };
  24913. } else {
  24914. return function ngValueLink(scope, elm, attr) {
  24915. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  24916. updateElementValue(elm, attr, value);
  24917. });
  24918. };
  24919. }
  24920. }
  24921. };
  24922. };
  24923. /**
  24924. * @ngdoc directive
  24925. * @name ngBind
  24926. * @restrict AC
  24927. *
  24928. * @description
  24929. * The `ngBind` attribute tells AngularJS to replace the text content of the specified HTML element
  24930. * with the value of a given expression, and to update the text content when the value of that
  24931. * expression changes.
  24932. *
  24933. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  24934. * `{{ expression }}` which is similar but less verbose.
  24935. *
  24936. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  24937. * displayed by the browser in its raw state before AngularJS compiles it. Since `ngBind` is an
  24938. * element attribute, it makes the bindings invisible to the user while the page is loading.
  24939. *
  24940. * An alternative solution to this problem would be using the
  24941. * {@link ng.directive:ngCloak ngCloak} directive.
  24942. *
  24943. *
  24944. * @element ANY
  24945. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  24946. *
  24947. * @example
  24948. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  24949. <example module="bindExample" name="ng-bind">
  24950. <file name="index.html">
  24951. <script>
  24952. angular.module('bindExample', [])
  24953. .controller('ExampleController', ['$scope', function($scope) {
  24954. $scope.name = 'Whirled';
  24955. }]);
  24956. </script>
  24957. <div ng-controller="ExampleController">
  24958. <label>Enter name: <input type="text" ng-model="name"></label><br>
  24959. Hello <span ng-bind="name"></span>!
  24960. </div>
  24961. </file>
  24962. <file name="protractor.js" type="protractor">
  24963. it('should check ng-bind', function() {
  24964. var nameInput = element(by.model('name'));
  24965. expect(element(by.binding('name')).getText()).toBe('Whirled');
  24966. nameInput.clear();
  24967. nameInput.sendKeys('world');
  24968. expect(element(by.binding('name')).getText()).toBe('world');
  24969. });
  24970. </file>
  24971. </example>
  24972. */
  24973. var ngBindDirective = ['$compile', function($compile) {
  24974. return {
  24975. restrict: 'AC',
  24976. compile: function ngBindCompile(templateElement) {
  24977. $compile.$$addBindingClass(templateElement);
  24978. return function ngBindLink(scope, element, attr) {
  24979. $compile.$$addBindingInfo(element, attr.ngBind);
  24980. element = element[0];
  24981. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  24982. element.textContent = stringify(value);
  24983. });
  24984. };
  24985. }
  24986. };
  24987. }];
  24988. /**
  24989. * @ngdoc directive
  24990. * @name ngBindTemplate
  24991. *
  24992. * @description
  24993. * The `ngBindTemplate` directive specifies that the element
  24994. * text content should be replaced with the interpolation of the template
  24995. * in the `ngBindTemplate` attribute.
  24996. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  24997. * expressions. This directive is needed since some HTML elements
  24998. * (such as TITLE and OPTION) cannot contain SPAN elements.
  24999. *
  25000. * @element ANY
  25001. * @param {string} ngBindTemplate template of form
  25002. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  25003. *
  25004. * @example
  25005. * Try it here: enter text in text box and watch the greeting change.
  25006. <example module="bindExample" name="ng-bind-template">
  25007. <file name="index.html">
  25008. <script>
  25009. angular.module('bindExample', [])
  25010. .controller('ExampleController', ['$scope', function($scope) {
  25011. $scope.salutation = 'Hello';
  25012. $scope.name = 'World';
  25013. }]);
  25014. </script>
  25015. <div ng-controller="ExampleController">
  25016. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  25017. <label>Name: <input type="text" ng-model="name"></label><br>
  25018. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  25019. </div>
  25020. </file>
  25021. <file name="protractor.js" type="protractor">
  25022. it('should check ng-bind', function() {
  25023. var salutationElem = element(by.binding('salutation'));
  25024. var salutationInput = element(by.model('salutation'));
  25025. var nameInput = element(by.model('name'));
  25026. expect(salutationElem.getText()).toBe('Hello World!');
  25027. salutationInput.clear();
  25028. salutationInput.sendKeys('Greetings');
  25029. nameInput.clear();
  25030. nameInput.sendKeys('user');
  25031. expect(salutationElem.getText()).toBe('Greetings user!');
  25032. });
  25033. </file>
  25034. </example>
  25035. */
  25036. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  25037. return {
  25038. compile: function ngBindTemplateCompile(templateElement) {
  25039. $compile.$$addBindingClass(templateElement);
  25040. return function ngBindTemplateLink(scope, element, attr) {
  25041. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  25042. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  25043. element = element[0];
  25044. attr.$observe('ngBindTemplate', function(value) {
  25045. element.textContent = isUndefined(value) ? '' : value;
  25046. });
  25047. };
  25048. }
  25049. };
  25050. }];
  25051. /**
  25052. * @ngdoc directive
  25053. * @name ngBindHtml
  25054. *
  25055. * @description
  25056. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  25057. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  25058. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  25059. * ngSanitize} in your module's dependencies (not in core AngularJS). In order to use {@link ngSanitize}
  25060. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  25061. *
  25062. * You may also bypass sanitization for values you know are safe. To do so, bind to
  25063. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  25064. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  25065. *
  25066. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  25067. * will have an exception (instead of an exploit.)
  25068. *
  25069. * @element ANY
  25070. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  25071. *
  25072. * @example
  25073. <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
  25074. <file name="index.html">
  25075. <div ng-controller="ExampleController">
  25076. <p ng-bind-html="myHTML"></p>
  25077. </div>
  25078. </file>
  25079. <file name="script.js">
  25080. angular.module('bindHtmlExample', ['ngSanitize'])
  25081. .controller('ExampleController', ['$scope', function($scope) {
  25082. $scope.myHTML =
  25083. 'I am an <code>HTML</code>string with ' +
  25084. '<a href="#">links!</a> and other <em>stuff</em>';
  25085. }]);
  25086. </file>
  25087. <file name="protractor.js" type="protractor">
  25088. it('should check ng-bind-html', function() {
  25089. expect(element(by.binding('myHTML')).getText()).toBe(
  25090. 'I am an HTMLstring with links! and other stuff');
  25091. });
  25092. </file>
  25093. </example>
  25094. */
  25095. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  25096. return {
  25097. restrict: 'A',
  25098. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  25099. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  25100. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  25101. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  25102. return $sce.valueOf(val);
  25103. });
  25104. $compile.$$addBindingClass(tElement);
  25105. return function ngBindHtmlLink(scope, element, attr) {
  25106. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  25107. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  25108. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  25109. var value = ngBindHtmlGetter(scope);
  25110. element.html($sce.getTrustedHtml(value) || '');
  25111. });
  25112. };
  25113. }
  25114. };
  25115. }];
  25116. /**
  25117. * @ngdoc directive
  25118. * @name ngChange
  25119. * @restrict A
  25120. *
  25121. * @description
  25122. * Evaluate the given expression when the user changes the input.
  25123. * The expression is evaluated immediately, unlike the JavaScript onchange event
  25124. * which only triggers at the end of a change (usually, when the user leaves the
  25125. * form element or presses the return key).
  25126. *
  25127. * The `ngChange` expression is only evaluated when a change in the input value causes
  25128. * a new value to be committed to the model.
  25129. *
  25130. * It will not be evaluated:
  25131. * * if the value returned from the `$parsers` transformation pipeline has not changed
  25132. * * if the input has continued to be invalid since the model will stay `null`
  25133. * * if the model is changed programmatically and not by a change to the input value
  25134. *
  25135. *
  25136. * Note, this directive requires `ngModel` to be present.
  25137. *
  25138. * @element ANY
  25139. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  25140. * in input value.
  25141. *
  25142. * @example
  25143. * <example name="ngChange-directive" module="changeExample">
  25144. * <file name="index.html">
  25145. * <script>
  25146. * angular.module('changeExample', [])
  25147. * .controller('ExampleController', ['$scope', function($scope) {
  25148. * $scope.counter = 0;
  25149. * $scope.change = function() {
  25150. * $scope.counter++;
  25151. * };
  25152. * }]);
  25153. * </script>
  25154. * <div ng-controller="ExampleController">
  25155. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  25156. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  25157. * <label for="ng-change-example2">Confirmed</label><br />
  25158. * <tt>debug = {{confirmed}}</tt><br/>
  25159. * <tt>counter = {{counter}}</tt><br/>
  25160. * </div>
  25161. * </file>
  25162. * <file name="protractor.js" type="protractor">
  25163. * var counter = element(by.binding('counter'));
  25164. * var debug = element(by.binding('confirmed'));
  25165. *
  25166. * it('should evaluate the expression if changing from view', function() {
  25167. * expect(counter.getText()).toContain('0');
  25168. *
  25169. * element(by.id('ng-change-example1')).click();
  25170. *
  25171. * expect(counter.getText()).toContain('1');
  25172. * expect(debug.getText()).toContain('true');
  25173. * });
  25174. *
  25175. * it('should not evaluate the expression if changing from model', function() {
  25176. * element(by.id('ng-change-example2')).click();
  25177. * expect(counter.getText()).toContain('0');
  25178. * expect(debug.getText()).toContain('true');
  25179. * });
  25180. * </file>
  25181. * </example>
  25182. */
  25183. var ngChangeDirective = valueFn({
  25184. restrict: 'A',
  25185. require: 'ngModel',
  25186. link: function(scope, element, attr, ctrl) {
  25187. ctrl.$viewChangeListeners.push(function() {
  25188. scope.$eval(attr.ngChange);
  25189. });
  25190. }
  25191. });
  25192. /* exported
  25193. ngClassDirective,
  25194. ngClassEvenDirective,
  25195. ngClassOddDirective
  25196. */
  25197. function classDirective(name, selector) {
  25198. name = 'ngClass' + name;
  25199. var indexWatchExpression;
  25200. return ['$parse', function($parse) {
  25201. return {
  25202. restrict: 'AC',
  25203. link: function(scope, element, attr) {
  25204. var classCounts = element.data('$classCounts');
  25205. var oldModulo = true;
  25206. var oldClassString;
  25207. if (!classCounts) {
  25208. // Use createMap() to prevent class assumptions involving property
  25209. // names in Object.prototype
  25210. classCounts = createMap();
  25211. element.data('$classCounts', classCounts);
  25212. }
  25213. if (name !== 'ngClass') {
  25214. if (!indexWatchExpression) {
  25215. indexWatchExpression = $parse('$index', function moduloTwo($index) {
  25216. // eslint-disable-next-line no-bitwise
  25217. return $index & 1;
  25218. });
  25219. }
  25220. scope.$watch(indexWatchExpression, ngClassIndexWatchAction);
  25221. }
  25222. scope.$watch($parse(attr[name], toClassString), ngClassWatchAction);
  25223. function addClasses(classString) {
  25224. classString = digestClassCounts(split(classString), 1);
  25225. attr.$addClass(classString);
  25226. }
  25227. function removeClasses(classString) {
  25228. classString = digestClassCounts(split(classString), -1);
  25229. attr.$removeClass(classString);
  25230. }
  25231. function updateClasses(oldClassString, newClassString) {
  25232. var oldClassArray = split(oldClassString);
  25233. var newClassArray = split(newClassString);
  25234. var toRemoveArray = arrayDifference(oldClassArray, newClassArray);
  25235. var toAddArray = arrayDifference(newClassArray, oldClassArray);
  25236. var toRemoveString = digestClassCounts(toRemoveArray, -1);
  25237. var toAddString = digestClassCounts(toAddArray, 1);
  25238. attr.$addClass(toAddString);
  25239. attr.$removeClass(toRemoveString);
  25240. }
  25241. function digestClassCounts(classArray, count) {
  25242. var classesToUpdate = [];
  25243. forEach(classArray, function(className) {
  25244. if (count > 0 || classCounts[className]) {
  25245. classCounts[className] = (classCounts[className] || 0) + count;
  25246. if (classCounts[className] === +(count > 0)) {
  25247. classesToUpdate.push(className);
  25248. }
  25249. }
  25250. });
  25251. return classesToUpdate.join(' ');
  25252. }
  25253. function ngClassIndexWatchAction(newModulo) {
  25254. // This watch-action should run before the `ngClassWatchAction()`, thus it
  25255. // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the
  25256. // `ngClassWatchAction()` will update the classes.
  25257. if (newModulo === selector) {
  25258. addClasses(oldClassString);
  25259. } else {
  25260. removeClasses(oldClassString);
  25261. }
  25262. oldModulo = newModulo;
  25263. }
  25264. function ngClassWatchAction(newClassString) {
  25265. if (oldModulo === selector) {
  25266. updateClasses(oldClassString, newClassString);
  25267. }
  25268. oldClassString = newClassString;
  25269. }
  25270. }
  25271. };
  25272. }];
  25273. // Helpers
  25274. function arrayDifference(tokens1, tokens2) {
  25275. if (!tokens1 || !tokens1.length) return [];
  25276. if (!tokens2 || !tokens2.length) return tokens1;
  25277. var values = [];
  25278. outer:
  25279. for (var i = 0; i < tokens1.length; i++) {
  25280. var token = tokens1[i];
  25281. for (var j = 0; j < tokens2.length; j++) {
  25282. if (token === tokens2[j]) continue outer;
  25283. }
  25284. values.push(token);
  25285. }
  25286. return values;
  25287. }
  25288. function split(classString) {
  25289. return classString && classString.split(' ');
  25290. }
  25291. function toClassString(classValue) {
  25292. if (!classValue) return classValue;
  25293. var classString = classValue;
  25294. if (isArray(classValue)) {
  25295. classString = classValue.map(toClassString).join(' ');
  25296. } else if (isObject(classValue)) {
  25297. classString = Object.keys(classValue).
  25298. filter(function(key) { return classValue[key]; }).
  25299. join(' ');
  25300. } else if (!isString(classValue)) {
  25301. classString = classValue + '';
  25302. }
  25303. return classString;
  25304. }
  25305. }
  25306. /**
  25307. * @ngdoc directive
  25308. * @name ngClass
  25309. * @restrict AC
  25310. * @element ANY
  25311. *
  25312. * @description
  25313. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  25314. * an expression that represents all classes to be added.
  25315. *
  25316. * The directive operates in three different ways, depending on which of three types the expression
  25317. * evaluates to:
  25318. *
  25319. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  25320. * names.
  25321. *
  25322. * 2. If the expression evaluates to an object, then for each key-value pair of the
  25323. * object with a truthy value the corresponding key is used as a class name.
  25324. *
  25325. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  25326. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  25327. * to give you more control over what CSS classes appear. See the code below for an example of this.
  25328. *
  25329. *
  25330. * The directive won't add duplicate classes if a particular class was already set.
  25331. *
  25332. * When the expression changes, the previously added classes are removed and only then are the
  25333. * new classes added.
  25334. *
  25335. * @knownIssue
  25336. * You should not use {@link guide/interpolation interpolation} in the value of the `class`
  25337. * attribute, when using the `ngClass` directive on the same element.
  25338. * See {@link guide/interpolation#known-issues here} for more info.
  25339. *
  25340. * @animations
  25341. * | Animation | Occurs |
  25342. * |----------------------------------|-------------------------------------|
  25343. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  25344. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  25345. * | {@link ng.$animate#setClass setClass} | just before classes are added and classes are removed from the element at the same time |
  25346. *
  25347. * ### ngClass and pre-existing CSS3 Transitions/Animations
  25348. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  25349. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  25350. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  25351. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  25352. {@link $animate#removeClass $animate.removeClass}.
  25353. *
  25354. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  25355. * of the evaluation can be a string representing space delimited class
  25356. * names, an array, or a map of class names to boolean values. In the case of a map, the
  25357. * names of the properties whose values are truthy will be added as css classes to the
  25358. * element.
  25359. *
  25360. * @example
  25361. * ### Basic
  25362. <example name="ng-class">
  25363. <file name="index.html">
  25364. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  25365. <label>
  25366. <input type="checkbox" ng-model="deleted">
  25367. deleted (apply "strike" class)
  25368. </label><br>
  25369. <label>
  25370. <input type="checkbox" ng-model="important">
  25371. important (apply "bold" class)
  25372. </label><br>
  25373. <label>
  25374. <input type="checkbox" ng-model="error">
  25375. error (apply "has-error" class)
  25376. </label>
  25377. <hr>
  25378. <p ng-class="style">Using String Syntax</p>
  25379. <input type="text" ng-model="style"
  25380. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  25381. <hr>
  25382. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  25383. <input ng-model="style1"
  25384. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  25385. <input ng-model="style2"
  25386. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  25387. <input ng-model="style3"
  25388. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  25389. <hr>
  25390. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  25391. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  25392. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  25393. </file>
  25394. <file name="style.css">
  25395. .strike {
  25396. text-decoration: line-through;
  25397. }
  25398. .bold {
  25399. font-weight: bold;
  25400. }
  25401. .red {
  25402. color: red;
  25403. }
  25404. .has-error {
  25405. color: red;
  25406. background-color: yellow;
  25407. }
  25408. .orange {
  25409. color: orange;
  25410. }
  25411. </file>
  25412. <file name="protractor.js" type="protractor">
  25413. var ps = element.all(by.css('p'));
  25414. it('should let you toggle the class', function() {
  25415. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  25416. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  25417. element(by.model('important')).click();
  25418. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  25419. element(by.model('error')).click();
  25420. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  25421. });
  25422. it('should let you toggle string example', function() {
  25423. expect(ps.get(1).getAttribute('class')).toBe('');
  25424. element(by.model('style')).clear();
  25425. element(by.model('style')).sendKeys('red');
  25426. expect(ps.get(1).getAttribute('class')).toBe('red');
  25427. });
  25428. it('array example should have 3 classes', function() {
  25429. expect(ps.get(2).getAttribute('class')).toBe('');
  25430. element(by.model('style1')).sendKeys('bold');
  25431. element(by.model('style2')).sendKeys('strike');
  25432. element(by.model('style3')).sendKeys('red');
  25433. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  25434. });
  25435. it('array with map example should have 2 classes', function() {
  25436. expect(ps.last().getAttribute('class')).toBe('');
  25437. element(by.model('style4')).sendKeys('bold');
  25438. element(by.model('warning')).click();
  25439. expect(ps.last().getAttribute('class')).toBe('bold orange');
  25440. });
  25441. </file>
  25442. </example>
  25443. @example
  25444. ### Animations
  25445. The example below demonstrates how to perform animations using ngClass.
  25446. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
  25447. <file name="index.html">
  25448. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  25449. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  25450. <br>
  25451. <span class="base-class" ng-class="myVar">Sample Text</span>
  25452. </file>
  25453. <file name="style.css">
  25454. .base-class {
  25455. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25456. }
  25457. .base-class.my-class {
  25458. color: red;
  25459. font-size:3em;
  25460. }
  25461. </file>
  25462. <file name="protractor.js" type="protractor">
  25463. it('should check ng-class', function() {
  25464. expect(element(by.css('.base-class')).getAttribute('class')).not.
  25465. toMatch(/my-class/);
  25466. element(by.id('setbtn')).click();
  25467. expect(element(by.css('.base-class')).getAttribute('class')).
  25468. toMatch(/my-class/);
  25469. element(by.id('clearbtn')).click();
  25470. expect(element(by.css('.base-class')).getAttribute('class')).not.
  25471. toMatch(/my-class/);
  25472. });
  25473. </file>
  25474. </example>
  25475. */
  25476. var ngClassDirective = classDirective('', true);
  25477. /**
  25478. * @ngdoc directive
  25479. * @name ngClassOdd
  25480. * @restrict AC
  25481. *
  25482. * @description
  25483. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  25484. * {@link ng.directive:ngClass ngClass}, except they work in
  25485. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  25486. *
  25487. * This directive can be applied only within the scope of an
  25488. * {@link ng.directive:ngRepeat ngRepeat}.
  25489. *
  25490. * @animations
  25491. * | Animation | Occurs |
  25492. * |----------------------------------|-------------------------------------|
  25493. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  25494. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  25495. *
  25496. * @element ANY
  25497. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  25498. * of the evaluation can be a string representing space delimited class names or an array.
  25499. *
  25500. * @example
  25501. <example name="ng-class-odd">
  25502. <file name="index.html">
  25503. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  25504. <li ng-repeat="name in names">
  25505. <span ng-class-odd="'odd'" ng-class-even="'even'">
  25506. {{name}}
  25507. </span>
  25508. </li>
  25509. </ol>
  25510. </file>
  25511. <file name="style.css">
  25512. .odd {
  25513. color: red;
  25514. }
  25515. .even {
  25516. color: blue;
  25517. }
  25518. </file>
  25519. <file name="protractor.js" type="protractor">
  25520. it('should check ng-class-odd and ng-class-even', function() {
  25521. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  25522. toMatch(/odd/);
  25523. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  25524. toMatch(/even/);
  25525. });
  25526. </file>
  25527. </example>
  25528. *
  25529. * <hr />
  25530. * @example
  25531. * An example on how to implement animations using `ngClassOdd`:
  25532. *
  25533. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class-odd-animate">
  25534. <file name="index.html">
  25535. <div ng-init="items=['Item 3', 'Item 2', 'Item 1', 'Item 0']">
  25536. <button ng-click="items.unshift('Item ' + items.length)">Add item</button>
  25537. <hr />
  25538. <table>
  25539. <tr ng-repeat="item in items" ng-class-odd="'odd'">
  25540. <td>{{ item }}</td>
  25541. </tr>
  25542. </table>
  25543. </div>
  25544. </file>
  25545. <file name="style.css">
  25546. .odd {
  25547. background: rgba(255, 255, 0, 0.25);
  25548. }
  25549. .odd-add, .odd-remove {
  25550. transition: 1.5s;
  25551. }
  25552. </file>
  25553. <file name="protractor.js" type="protractor">
  25554. it('should add new entries to the beginning of the list', function() {
  25555. var button = element(by.buttonText('Add item'));
  25556. var rows = element.all(by.repeater('item in items'));
  25557. expect(rows.count()).toBe(4);
  25558. expect(rows.get(0).getText()).toBe('Item 3');
  25559. expect(rows.get(1).getText()).toBe('Item 2');
  25560. button.click();
  25561. expect(rows.count()).toBe(5);
  25562. expect(rows.get(0).getText()).toBe('Item 4');
  25563. expect(rows.get(1).getText()).toBe('Item 3');
  25564. });
  25565. it('should add odd class to odd entries', function() {
  25566. var button = element(by.buttonText('Add item'));
  25567. var rows = element.all(by.repeater('item in items'));
  25568. expect(rows.get(0).getAttribute('class')).toMatch(/odd/);
  25569. expect(rows.get(1).getAttribute('class')).not.toMatch(/odd/);
  25570. button.click();
  25571. expect(rows.get(0).getAttribute('class')).toMatch(/odd/);
  25572. expect(rows.get(1).getAttribute('class')).not.toMatch(/odd/);
  25573. });
  25574. </file>
  25575. </example>
  25576. */
  25577. var ngClassOddDirective = classDirective('Odd', 0);
  25578. /**
  25579. * @ngdoc directive
  25580. * @name ngClassEven
  25581. * @restrict AC
  25582. *
  25583. * @description
  25584. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  25585. * {@link ng.directive:ngClass ngClass}, except they work in
  25586. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  25587. *
  25588. * This directive can be applied only within the scope of an
  25589. * {@link ng.directive:ngRepeat ngRepeat}.
  25590. *
  25591. * @animations
  25592. * | Animation | Occurs |
  25593. * |----------------------------------|-------------------------------------|
  25594. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  25595. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  25596. *
  25597. * @element ANY
  25598. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  25599. * result of the evaluation can be a string representing space delimited class names or an array.
  25600. *
  25601. * @example
  25602. <example name="ng-class-even">
  25603. <file name="index.html">
  25604. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  25605. <li ng-repeat="name in names">
  25606. <span ng-class-odd="'odd'" ng-class-even="'even'">
  25607. {{name}} &nbsp; &nbsp; &nbsp;
  25608. </span>
  25609. </li>
  25610. </ol>
  25611. </file>
  25612. <file name="style.css">
  25613. .odd {
  25614. color: red;
  25615. }
  25616. .even {
  25617. color: blue;
  25618. }
  25619. </file>
  25620. <file name="protractor.js" type="protractor">
  25621. it('should check ng-class-odd and ng-class-even', function() {
  25622. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  25623. toMatch(/odd/);
  25624. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  25625. toMatch(/even/);
  25626. });
  25627. </file>
  25628. </example>
  25629. *
  25630. * <hr />
  25631. * @example
  25632. * An example on how to implement animations using `ngClassEven`:
  25633. *
  25634. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class-even-animate">
  25635. <file name="index.html">
  25636. <div ng-init="items=['Item 3', 'Item 2', 'Item 1', 'Item 0']">
  25637. <button ng-click="items.unshift('Item ' + items.length)">Add item</button>
  25638. <hr />
  25639. <table>
  25640. <tr ng-repeat="item in items" ng-class-even="'even'">
  25641. <td>{{ item }}</td>
  25642. </tr>
  25643. </table>
  25644. </div>
  25645. </file>
  25646. <file name="style.css">
  25647. .even {
  25648. background: rgba(255, 255, 0, 0.25);
  25649. }
  25650. .even-add, .even-remove {
  25651. transition: 1.5s;
  25652. }
  25653. </file>
  25654. <file name="protractor.js" type="protractor">
  25655. it('should add new entries to the beginning of the list', function() {
  25656. var button = element(by.buttonText('Add item'));
  25657. var rows = element.all(by.repeater('item in items'));
  25658. expect(rows.count()).toBe(4);
  25659. expect(rows.get(0).getText()).toBe('Item 3');
  25660. expect(rows.get(1).getText()).toBe('Item 2');
  25661. button.click();
  25662. expect(rows.count()).toBe(5);
  25663. expect(rows.get(0).getText()).toBe('Item 4');
  25664. expect(rows.get(1).getText()).toBe('Item 3');
  25665. });
  25666. it('should add even class to even entries', function() {
  25667. var button = element(by.buttonText('Add item'));
  25668. var rows = element.all(by.repeater('item in items'));
  25669. expect(rows.get(0).getAttribute('class')).not.toMatch(/even/);
  25670. expect(rows.get(1).getAttribute('class')).toMatch(/even/);
  25671. button.click();
  25672. expect(rows.get(0).getAttribute('class')).not.toMatch(/even/);
  25673. expect(rows.get(1).getAttribute('class')).toMatch(/even/);
  25674. });
  25675. </file>
  25676. </example>
  25677. */
  25678. var ngClassEvenDirective = classDirective('Even', 1);
  25679. /**
  25680. * @ngdoc directive
  25681. * @name ngCloak
  25682. * @restrict AC
  25683. *
  25684. * @description
  25685. * The `ngCloak` directive is used to prevent the AngularJS html template from being briefly
  25686. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  25687. * directive to avoid the undesirable flicker effect caused by the html template display.
  25688. *
  25689. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  25690. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  25691. * of the browser view.
  25692. *
  25693. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  25694. * `angular.min.js`.
  25695. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  25696. *
  25697. * ```css
  25698. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  25699. * display: none !important;
  25700. * }
  25701. * ```
  25702. *
  25703. * When this css rule is loaded by the browser, all html elements (including their children) that
  25704. * are tagged with the `ngCloak` directive are hidden. When AngularJS encounters this directive
  25705. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  25706. * the compiled element visible.
  25707. *
  25708. * For the best result, the `angular.js` script must be loaded in the head section of the html
  25709. * document; alternatively, the css rule above must be included in the external stylesheet of the
  25710. * application.
  25711. *
  25712. * @element ANY
  25713. *
  25714. * @example
  25715. <example name="ng-cloak">
  25716. <file name="index.html">
  25717. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  25718. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  25719. </file>
  25720. <file name="protractor.js" type="protractor">
  25721. it('should remove the template directive and css class', function() {
  25722. expect($('#template1').getAttribute('ng-cloak')).
  25723. toBeNull();
  25724. expect($('#template2').getAttribute('ng-cloak')).
  25725. toBeNull();
  25726. });
  25727. </file>
  25728. </example>
  25729. *
  25730. */
  25731. var ngCloakDirective = ngDirective({
  25732. compile: function(element, attr) {
  25733. attr.$set('ngCloak', undefined);
  25734. element.removeClass('ng-cloak');
  25735. }
  25736. });
  25737. /**
  25738. * @ngdoc directive
  25739. * @name ngController
  25740. *
  25741. * @description
  25742. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  25743. * supports the principles behind the Model-View-Controller design pattern.
  25744. *
  25745. * MVC components in angular:
  25746. *
  25747. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  25748. * are accessed through bindings.
  25749. * * View — The template (HTML with data bindings) that is rendered into the View.
  25750. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  25751. * logic behind the application to decorate the scope with functions and values
  25752. *
  25753. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  25754. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  25755. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  25756. * and executed twice.
  25757. *
  25758. * @element ANY
  25759. * @scope
  25760. * @priority 500
  25761. * @param {expression} ngController Name of a constructor function registered with the current
  25762. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  25763. * that on the current scope evaluates to a constructor function.
  25764. *
  25765. * The controller instance can be published into a scope property by specifying
  25766. * `ng-controller="as propertyName"`.
  25767. *
  25768. * @example
  25769. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  25770. * greeting are methods declared on the controller (see source tab). These methods can
  25771. * easily be called from the AngularJS markup. Any changes to the data are automatically reflected
  25772. * in the View without the need for a manual update.
  25773. *
  25774. * Two different declaration styles are included below:
  25775. *
  25776. * * one binds methods and properties directly onto the controller using `this`:
  25777. * `ng-controller="SettingsController1 as settings"`
  25778. * * one injects `$scope` into the controller:
  25779. * `ng-controller="SettingsController2"`
  25780. *
  25781. * The second option is more common in the AngularJS community, and is generally used in boilerplates
  25782. * and in this guide. However, there are advantages to binding properties directly to the controller
  25783. * and avoiding scope.
  25784. *
  25785. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  25786. * multiple controllers apply to an element.
  25787. * * If you are writing your controllers as classes you have easier access to the properties and
  25788. * methods, which will appear on the scope, from inside the controller code.
  25789. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  25790. * inheritance masking primitives.
  25791. *
  25792. * This example demonstrates the `controller as` syntax.
  25793. *
  25794. * <example name="ngControllerAs" module="controllerAsExample">
  25795. * <file name="index.html">
  25796. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  25797. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  25798. * <button ng-click="settings.greet()">greet</button><br/>
  25799. * Contact:
  25800. * <ul>
  25801. * <li ng-repeat="contact in settings.contacts">
  25802. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  25803. * <option>phone</option>
  25804. * <option>email</option>
  25805. * </select>
  25806. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  25807. * <button ng-click="settings.clearContact(contact)">clear</button>
  25808. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  25809. * </li>
  25810. * <li><button ng-click="settings.addContact()">add</button></li>
  25811. * </ul>
  25812. * </div>
  25813. * </file>
  25814. * <file name="app.js">
  25815. * angular.module('controllerAsExample', [])
  25816. * .controller('SettingsController1', SettingsController1);
  25817. *
  25818. * function SettingsController1() {
  25819. * this.name = 'John Smith';
  25820. * this.contacts = [
  25821. * {type: 'phone', value: '408 555 1212'},
  25822. * {type: 'email', value: 'john.smith@example.org'}
  25823. * ];
  25824. * }
  25825. *
  25826. * SettingsController1.prototype.greet = function() {
  25827. * alert(this.name);
  25828. * };
  25829. *
  25830. * SettingsController1.prototype.addContact = function() {
  25831. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  25832. * };
  25833. *
  25834. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  25835. * var index = this.contacts.indexOf(contactToRemove);
  25836. * this.contacts.splice(index, 1);
  25837. * };
  25838. *
  25839. * SettingsController1.prototype.clearContact = function(contact) {
  25840. * contact.type = 'phone';
  25841. * contact.value = '';
  25842. * };
  25843. * </file>
  25844. * <file name="protractor.js" type="protractor">
  25845. * it('should check controller as', function() {
  25846. * var container = element(by.id('ctrl-as-exmpl'));
  25847. * expect(container.element(by.model('settings.name'))
  25848. * .getAttribute('value')).toBe('John Smith');
  25849. *
  25850. * var firstRepeat =
  25851. * container.element(by.repeater('contact in settings.contacts').row(0));
  25852. * var secondRepeat =
  25853. * container.element(by.repeater('contact in settings.contacts').row(1));
  25854. *
  25855. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  25856. * .toBe('408 555 1212');
  25857. *
  25858. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  25859. * .toBe('john.smith@example.org');
  25860. *
  25861. * firstRepeat.element(by.buttonText('clear')).click();
  25862. *
  25863. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  25864. * .toBe('');
  25865. *
  25866. * container.element(by.buttonText('add')).click();
  25867. *
  25868. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  25869. * .element(by.model('contact.value'))
  25870. * .getAttribute('value'))
  25871. * .toBe('yourname@example.org');
  25872. * });
  25873. * </file>
  25874. * </example>
  25875. *
  25876. * This example demonstrates the "attach to `$scope`" style of controller.
  25877. *
  25878. * <example name="ngController" module="controllerExample">
  25879. * <file name="index.html">
  25880. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  25881. * <label>Name: <input type="text" ng-model="name"/></label>
  25882. * <button ng-click="greet()">greet</button><br/>
  25883. * Contact:
  25884. * <ul>
  25885. * <li ng-repeat="contact in contacts">
  25886. * <select ng-model="contact.type" id="select_{{$index}}">
  25887. * <option>phone</option>
  25888. * <option>email</option>
  25889. * </select>
  25890. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  25891. * <button ng-click="clearContact(contact)">clear</button>
  25892. * <button ng-click="removeContact(contact)">X</button>
  25893. * </li>
  25894. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  25895. * </ul>
  25896. * </div>
  25897. * </file>
  25898. * <file name="app.js">
  25899. * angular.module('controllerExample', [])
  25900. * .controller('SettingsController2', ['$scope', SettingsController2]);
  25901. *
  25902. * function SettingsController2($scope) {
  25903. * $scope.name = 'John Smith';
  25904. * $scope.contacts = [
  25905. * {type:'phone', value:'408 555 1212'},
  25906. * {type:'email', value:'john.smith@example.org'}
  25907. * ];
  25908. *
  25909. * $scope.greet = function() {
  25910. * alert($scope.name);
  25911. * };
  25912. *
  25913. * $scope.addContact = function() {
  25914. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  25915. * };
  25916. *
  25917. * $scope.removeContact = function(contactToRemove) {
  25918. * var index = $scope.contacts.indexOf(contactToRemove);
  25919. * $scope.contacts.splice(index, 1);
  25920. * };
  25921. *
  25922. * $scope.clearContact = function(contact) {
  25923. * contact.type = 'phone';
  25924. * contact.value = '';
  25925. * };
  25926. * }
  25927. * </file>
  25928. * <file name="protractor.js" type="protractor">
  25929. * it('should check controller', function() {
  25930. * var container = element(by.id('ctrl-exmpl'));
  25931. *
  25932. * expect(container.element(by.model('name'))
  25933. * .getAttribute('value')).toBe('John Smith');
  25934. *
  25935. * var firstRepeat =
  25936. * container.element(by.repeater('contact in contacts').row(0));
  25937. * var secondRepeat =
  25938. * container.element(by.repeater('contact in contacts').row(1));
  25939. *
  25940. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  25941. * .toBe('408 555 1212');
  25942. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  25943. * .toBe('john.smith@example.org');
  25944. *
  25945. * firstRepeat.element(by.buttonText('clear')).click();
  25946. *
  25947. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  25948. * .toBe('');
  25949. *
  25950. * container.element(by.buttonText('add')).click();
  25951. *
  25952. * expect(container.element(by.repeater('contact in contacts').row(2))
  25953. * .element(by.model('contact.value'))
  25954. * .getAttribute('value'))
  25955. * .toBe('yourname@example.org');
  25956. * });
  25957. * </file>
  25958. *</example>
  25959. */
  25960. var ngControllerDirective = [function() {
  25961. return {
  25962. restrict: 'A',
  25963. scope: true,
  25964. controller: '@',
  25965. priority: 500
  25966. };
  25967. }];
  25968. /**
  25969. * @ngdoc directive
  25970. * @name ngCsp
  25971. *
  25972. * @restrict A
  25973. * @element ANY
  25974. * @description
  25975. *
  25976. * AngularJS has some features that can conflict with certain restrictions that are applied when using
  25977. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  25978. *
  25979. * If you intend to implement CSP with these rules then you must tell AngularJS not to use these
  25980. * features.
  25981. *
  25982. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  25983. *
  25984. *
  25985. * The following default rules in CSP affect AngularJS:
  25986. *
  25987. * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute
  25988. * code from strings is forbidden. AngularJS makes use of this in the {@link $parse} service to
  25989. * provide a 30% increase in the speed of evaluating AngularJS expressions. (This CSP rule can be
  25990. * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would
  25991. * weaken the protections offered by CSP.)
  25992. *
  25993. * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden.
  25994. * This prevents apps from injecting custom styles directly into the document. AngularJS makes use of
  25995. * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these
  25996. * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css`
  25997. * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but
  25998. * it is generally not recommended as it would weaken the protections offered by CSP.)
  25999. *
  26000. * If you do not provide `ngCsp` then AngularJS tries to autodetect if CSP is blocking dynamic code
  26001. * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically
  26002. * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a
  26003. * CSP error to be logged in the console:
  26004. *
  26005. * ```
  26006. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  26007. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  26008. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  26009. * ```
  26010. *
  26011. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  26012. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  26013. * the `angular.js` file.
  26014. *
  26015. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  26016. *
  26017. * You can specify which of the CSP related AngularJS features should be deactivated by providing
  26018. * a value for the `ng-csp` attribute. The options are as follows:
  26019. *
  26020. * * no-inline-style: this stops AngularJS from injecting CSS styles into the DOM
  26021. *
  26022. * * no-unsafe-eval: this stops AngularJS from optimizing $parse with unsafe eval of strings
  26023. *
  26024. * You can use these values in the following combinations:
  26025. *
  26026. *
  26027. * * No declaration means that AngularJS will assume that you can do inline styles, but it will do
  26028. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous
  26029. * versions of AngularJS.
  26030. *
  26031. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell AngularJS to deactivate both inline
  26032. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous
  26033. * versions of AngularJS.
  26034. *
  26035. * * Specifying only `no-unsafe-eval` tells AngularJS that we must not use eval, but that we can
  26036. * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  26037. *
  26038. * * Specifying only `no-inline-style` tells AngularJS that we must not inject styles, but that we can
  26039. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  26040. *
  26041. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells AngularJS that we must not inject
  26042. * styles nor use eval, which is the same as an empty: ng-csp.
  26043. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  26044. *
  26045. * @example
  26046. *
  26047. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  26048. ```html
  26049. <!doctype html>
  26050. <html ng-app ng-csp>
  26051. ...
  26052. ...
  26053. </html>
  26054. ```
  26055. <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! -->
  26056. <example name="example.csp" module="cspExample" ng-csp="true">
  26057. <file name="index.html">
  26058. <div ng-controller="MainController as ctrl">
  26059. <div>
  26060. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  26061. <span id="counter">
  26062. {{ctrl.counter}}
  26063. </span>
  26064. </div>
  26065. <div>
  26066. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  26067. <span id="evilError">
  26068. {{ctrl.evilError}}
  26069. </span>
  26070. </div>
  26071. </div>
  26072. </file>
  26073. <file name="script.js">
  26074. angular.module('cspExample', [])
  26075. .controller('MainController', function MainController() {
  26076. this.counter = 0;
  26077. this.inc = function() {
  26078. this.counter++;
  26079. };
  26080. this.evil = function() {
  26081. try {
  26082. eval('1+2'); // eslint-disable-line no-eval
  26083. } catch (e) {
  26084. this.evilError = e.message;
  26085. }
  26086. };
  26087. });
  26088. </file>
  26089. <file name="protractor.js" type="protractor">
  26090. var util, webdriver;
  26091. var incBtn = element(by.id('inc'));
  26092. var counter = element(by.id('counter'));
  26093. var evilBtn = element(by.id('evil'));
  26094. var evilError = element(by.id('evilError'));
  26095. function getAndClearSevereErrors() {
  26096. return browser.manage().logs().get('browser').then(function(browserLog) {
  26097. return browserLog.filter(function(logEntry) {
  26098. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  26099. });
  26100. });
  26101. }
  26102. function clearErrors() {
  26103. getAndClearSevereErrors();
  26104. }
  26105. function expectNoErrors() {
  26106. getAndClearSevereErrors().then(function(filteredLog) {
  26107. expect(filteredLog.length).toEqual(0);
  26108. if (filteredLog.length) {
  26109. console.log('browser console errors: ' + util.inspect(filteredLog));
  26110. }
  26111. });
  26112. }
  26113. function expectError(regex) {
  26114. getAndClearSevereErrors().then(function(filteredLog) {
  26115. var found = false;
  26116. filteredLog.forEach(function(log) {
  26117. if (log.message.match(regex)) {
  26118. found = true;
  26119. }
  26120. });
  26121. if (!found) {
  26122. throw new Error('expected an error that matches ' + regex);
  26123. }
  26124. });
  26125. }
  26126. beforeEach(function() {
  26127. util = require('util');
  26128. webdriver = require('selenium-webdriver');
  26129. });
  26130. // For now, we only test on Chrome,
  26131. // as Safari does not load the page with Protractor's injected scripts,
  26132. // and Firefox webdriver always disables content security policy (#6358)
  26133. if (browser.params.browser !== 'chrome') {
  26134. return;
  26135. }
  26136. it('should not report errors when the page is loaded', function() {
  26137. // clear errors so we are not dependent on previous tests
  26138. clearErrors();
  26139. // Need to reload the page as the page is already loaded when
  26140. // we come here
  26141. browser.driver.getCurrentUrl().then(function(url) {
  26142. browser.get(url);
  26143. });
  26144. expectNoErrors();
  26145. });
  26146. it('should evaluate expressions', function() {
  26147. expect(counter.getText()).toEqual('0');
  26148. incBtn.click();
  26149. expect(counter.getText()).toEqual('1');
  26150. expectNoErrors();
  26151. });
  26152. it('should throw and report an error when using "eval"', function() {
  26153. evilBtn.click();
  26154. expect(evilError.getText()).toMatch(/Content Security Policy/);
  26155. expectError(/Content Security Policy/);
  26156. });
  26157. </file>
  26158. </example>
  26159. */
  26160. // `ngCsp` is not implemented as a proper directive any more, because we need it be processed while
  26161. // we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()`
  26162. // fn that looks for the `ng-csp` attribute anywhere in the current doc.
  26163. /**
  26164. * @ngdoc directive
  26165. * @name ngClick
  26166. * @restrict A
  26167. * @element ANY
  26168. * @priority 0
  26169. *
  26170. * @description
  26171. * The ngClick directive allows you to specify custom behavior when
  26172. * an element is clicked.
  26173. *
  26174. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  26175. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  26176. *
  26177. * @example
  26178. <example name="ng-click">
  26179. <file name="index.html">
  26180. <button ng-click="count = count + 1" ng-init="count=0">
  26181. Increment
  26182. </button>
  26183. <span>
  26184. count: {{count}}
  26185. </span>
  26186. </file>
  26187. <file name="protractor.js" type="protractor">
  26188. it('should check ng-click', function() {
  26189. expect(element(by.binding('count')).getText()).toMatch('0');
  26190. element(by.css('button')).click();
  26191. expect(element(by.binding('count')).getText()).toMatch('1');
  26192. });
  26193. </file>
  26194. </example>
  26195. */
  26196. /*
  26197. * A collection of directives that allows creation of custom event handlers that are defined as
  26198. * AngularJS expressions and are compiled and executed within the current scope.
  26199. */
  26200. var ngEventDirectives = {};
  26201. // For events that might fire synchronously during DOM manipulation
  26202. // we need to execute their event handlers asynchronously using $evalAsync,
  26203. // so that they are not executed in an inconsistent state.
  26204. var forceAsyncEvents = {
  26205. 'blur': true,
  26206. 'focus': true
  26207. };
  26208. forEach(
  26209. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  26210. function(eventName) {
  26211. var directiveName = directiveNormalize('ng-' + eventName);
  26212. ngEventDirectives[directiveName] = ['$parse', '$rootScope', '$exceptionHandler', function($parse, $rootScope, $exceptionHandler) {
  26213. return createEventDirective($parse, $rootScope, $exceptionHandler, directiveName, eventName, forceAsyncEvents[eventName]);
  26214. }];
  26215. }
  26216. );
  26217. function createEventDirective($parse, $rootScope, $exceptionHandler, directiveName, eventName, forceAsync) {
  26218. return {
  26219. restrict: 'A',
  26220. compile: function($element, attr) {
  26221. // NOTE:
  26222. // We expose the powerful `$event` object on the scope that provides access to the Window,
  26223. // etc. This is OK, because expressions are not sandboxed any more (and the expression
  26224. // sandbox was never meant to be a security feature anyway).
  26225. var fn = $parse(attr[directiveName]);
  26226. return function ngEventHandler(scope, element) {
  26227. element.on(eventName, function(event) {
  26228. var callback = function() {
  26229. fn(scope, {$event: event});
  26230. };
  26231. if (!$rootScope.$$phase) {
  26232. scope.$apply(callback);
  26233. } else if (forceAsync) {
  26234. scope.$evalAsync(callback);
  26235. } else {
  26236. try {
  26237. callback();
  26238. } catch (error) {
  26239. $exceptionHandler(error);
  26240. }
  26241. }
  26242. });
  26243. };
  26244. }
  26245. };
  26246. }
  26247. /**
  26248. * @ngdoc directive
  26249. * @name ngDblclick
  26250. * @restrict A
  26251. * @element ANY
  26252. * @priority 0
  26253. *
  26254. * @description
  26255. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  26256. *
  26257. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  26258. * a dblclick. (The Event object is available as `$event`)
  26259. *
  26260. * @example
  26261. <example name="ng-dblclick">
  26262. <file name="index.html">
  26263. <button ng-dblclick="count = count + 1" ng-init="count=0">
  26264. Increment (on double click)
  26265. </button>
  26266. count: {{count}}
  26267. </file>
  26268. </example>
  26269. */
  26270. /**
  26271. * @ngdoc directive
  26272. * @name ngMousedown
  26273. * @restrict A
  26274. * @element ANY
  26275. * @priority 0
  26276. *
  26277. * @description
  26278. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  26279. *
  26280. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  26281. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  26282. *
  26283. * @example
  26284. <example name="ng-mousedown">
  26285. <file name="index.html">
  26286. <button ng-mousedown="count = count + 1" ng-init="count=0">
  26287. Increment (on mouse down)
  26288. </button>
  26289. count: {{count}}
  26290. </file>
  26291. </example>
  26292. */
  26293. /**
  26294. * @ngdoc directive
  26295. * @name ngMouseup
  26296. * @restrict A
  26297. * @element ANY
  26298. * @priority 0
  26299. *
  26300. * @description
  26301. * Specify custom behavior on mouseup event.
  26302. *
  26303. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  26304. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  26305. *
  26306. * @example
  26307. <example name="ng-mouseup">
  26308. <file name="index.html">
  26309. <button ng-mouseup="count = count + 1" ng-init="count=0">
  26310. Increment (on mouse up)
  26311. </button>
  26312. count: {{count}}
  26313. </file>
  26314. </example>
  26315. */
  26316. /**
  26317. * @ngdoc directive
  26318. * @name ngMouseover
  26319. * @restrict A
  26320. * @element ANY
  26321. * @priority 0
  26322. *
  26323. * @description
  26324. * Specify custom behavior on mouseover event.
  26325. *
  26326. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  26327. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  26328. *
  26329. * @example
  26330. <example name="ng-mouseover">
  26331. <file name="index.html">
  26332. <button ng-mouseover="count = count + 1" ng-init="count=0">
  26333. Increment (when mouse is over)
  26334. </button>
  26335. count: {{count}}
  26336. </file>
  26337. </example>
  26338. */
  26339. /**
  26340. * @ngdoc directive
  26341. * @name ngMouseenter
  26342. * @restrict A
  26343. * @element ANY
  26344. * @priority 0
  26345. *
  26346. * @description
  26347. * Specify custom behavior on mouseenter event.
  26348. *
  26349. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  26350. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  26351. *
  26352. * @example
  26353. <example name="ng-mouseenter">
  26354. <file name="index.html">
  26355. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  26356. Increment (when mouse enters)
  26357. </button>
  26358. count: {{count}}
  26359. </file>
  26360. </example>
  26361. */
  26362. /**
  26363. * @ngdoc directive
  26364. * @name ngMouseleave
  26365. * @restrict A
  26366. * @element ANY
  26367. * @priority 0
  26368. *
  26369. * @description
  26370. * Specify custom behavior on mouseleave event.
  26371. *
  26372. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  26373. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  26374. *
  26375. * @example
  26376. <example name="ng-mouseleave">
  26377. <file name="index.html">
  26378. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  26379. Increment (when mouse leaves)
  26380. </button>
  26381. count: {{count}}
  26382. </file>
  26383. </example>
  26384. */
  26385. /**
  26386. * @ngdoc directive
  26387. * @name ngMousemove
  26388. * @restrict A
  26389. * @element ANY
  26390. * @priority 0
  26391. *
  26392. * @description
  26393. * Specify custom behavior on mousemove event.
  26394. *
  26395. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  26396. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  26397. *
  26398. * @example
  26399. <example name="ng-mousemove">
  26400. <file name="index.html">
  26401. <button ng-mousemove="count = count + 1" ng-init="count=0">
  26402. Increment (when mouse moves)
  26403. </button>
  26404. count: {{count}}
  26405. </file>
  26406. </example>
  26407. */
  26408. /**
  26409. * @ngdoc directive
  26410. * @name ngKeydown
  26411. * @restrict A
  26412. * @element ANY
  26413. * @priority 0
  26414. *
  26415. * @description
  26416. * Specify custom behavior on keydown event.
  26417. *
  26418. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  26419. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  26420. *
  26421. * @example
  26422. <example name="ng-keydown">
  26423. <file name="index.html">
  26424. <input ng-keydown="count = count + 1" ng-init="count=0">
  26425. key down count: {{count}}
  26426. </file>
  26427. </example>
  26428. */
  26429. /**
  26430. * @ngdoc directive
  26431. * @name ngKeyup
  26432. * @restrict A
  26433. * @element ANY
  26434. * @priority 0
  26435. *
  26436. * @description
  26437. * Specify custom behavior on keyup event.
  26438. *
  26439. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  26440. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  26441. *
  26442. * @example
  26443. <example name="ng-keyup">
  26444. <file name="index.html">
  26445. <p>Typing in the input box below updates the key count</p>
  26446. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  26447. <p>Typing in the input box below updates the keycode</p>
  26448. <input ng-keyup="event=$event">
  26449. <p>event keyCode: {{ event.keyCode }}</p>
  26450. <p>event altKey: {{ event.altKey }}</p>
  26451. </file>
  26452. </example>
  26453. */
  26454. /**
  26455. * @ngdoc directive
  26456. * @name ngKeypress
  26457. * @restrict A
  26458. * @element ANY
  26459. *
  26460. * @description
  26461. * Specify custom behavior on keypress event.
  26462. *
  26463. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  26464. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  26465. * and can be interrogated for keyCode, altKey, etc.)
  26466. *
  26467. * @example
  26468. <example name="ng-keypress">
  26469. <file name="index.html">
  26470. <input ng-keypress="count = count + 1" ng-init="count=0">
  26471. key press count: {{count}}
  26472. </file>
  26473. </example>
  26474. */
  26475. /**
  26476. * @ngdoc directive
  26477. * @name ngSubmit
  26478. * @restrict A
  26479. * @element form
  26480. * @priority 0
  26481. *
  26482. * @description
  26483. * Enables binding AngularJS expressions to onsubmit events.
  26484. *
  26485. * Additionally it prevents the default action (which for form means sending the request to the
  26486. * server and reloading the current page), but only if the form does not contain `action`,
  26487. * `data-action`, or `x-action` attributes.
  26488. *
  26489. * <div class="alert alert-warning">
  26490. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  26491. * `ngSubmit` handlers together. See the
  26492. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  26493. * for a detailed discussion of when `ngSubmit` may be triggered.
  26494. * </div>
  26495. *
  26496. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  26497. * ({@link guide/expression#-event- Event object is available as `$event`})
  26498. *
  26499. * @example
  26500. <example module="submitExample" name="ng-submit">
  26501. <file name="index.html">
  26502. <script>
  26503. angular.module('submitExample', [])
  26504. .controller('ExampleController', ['$scope', function($scope) {
  26505. $scope.list = [];
  26506. $scope.text = 'hello';
  26507. $scope.submit = function() {
  26508. if ($scope.text) {
  26509. $scope.list.push(this.text);
  26510. $scope.text = '';
  26511. }
  26512. };
  26513. }]);
  26514. </script>
  26515. <form ng-submit="submit()" ng-controller="ExampleController">
  26516. Enter text and hit enter:
  26517. <input type="text" ng-model="text" name="text" />
  26518. <input type="submit" id="submit" value="Submit" />
  26519. <pre>list={{list}}</pre>
  26520. </form>
  26521. </file>
  26522. <file name="protractor.js" type="protractor">
  26523. it('should check ng-submit', function() {
  26524. expect(element(by.binding('list')).getText()).toBe('list=[]');
  26525. element(by.css('#submit')).click();
  26526. expect(element(by.binding('list')).getText()).toContain('hello');
  26527. expect(element(by.model('text')).getAttribute('value')).toBe('');
  26528. });
  26529. it('should ignore empty strings', function() {
  26530. expect(element(by.binding('list')).getText()).toBe('list=[]');
  26531. element(by.css('#submit')).click();
  26532. element(by.css('#submit')).click();
  26533. expect(element(by.binding('list')).getText()).toContain('hello');
  26534. });
  26535. </file>
  26536. </example>
  26537. */
  26538. /**
  26539. * @ngdoc directive
  26540. * @name ngFocus
  26541. * @restrict A
  26542. * @element window, input, select, textarea, a
  26543. * @priority 0
  26544. *
  26545. * @description
  26546. * Specify custom behavior on focus event.
  26547. *
  26548. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  26549. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  26550. * during an `$apply` to ensure a consistent state.
  26551. *
  26552. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  26553. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  26554. *
  26555. * @example
  26556. * See {@link ng.directive:ngClick ngClick}
  26557. */
  26558. /**
  26559. * @ngdoc directive
  26560. * @name ngBlur
  26561. * @restrict A
  26562. * @element window, input, select, textarea, a
  26563. * @priority 0
  26564. *
  26565. * @description
  26566. * Specify custom behavior on blur event.
  26567. *
  26568. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  26569. * an element has lost focus.
  26570. *
  26571. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  26572. * (e.g. removing a focussed input),
  26573. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  26574. * during an `$apply` to ensure a consistent state.
  26575. *
  26576. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  26577. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  26578. *
  26579. * @example
  26580. * See {@link ng.directive:ngClick ngClick}
  26581. */
  26582. /**
  26583. * @ngdoc directive
  26584. * @name ngCopy
  26585. * @restrict A
  26586. * @element window, input, select, textarea, a
  26587. * @priority 0
  26588. *
  26589. * @description
  26590. * Specify custom behavior on copy event.
  26591. *
  26592. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  26593. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  26594. *
  26595. * @example
  26596. <example name="ng-copy">
  26597. <file name="index.html">
  26598. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  26599. copied: {{copied}}
  26600. </file>
  26601. </example>
  26602. */
  26603. /**
  26604. * @ngdoc directive
  26605. * @name ngCut
  26606. * @restrict A
  26607. * @element window, input, select, textarea, a
  26608. * @priority 0
  26609. *
  26610. * @description
  26611. * Specify custom behavior on cut event.
  26612. *
  26613. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  26614. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  26615. *
  26616. * @example
  26617. <example name="ng-cut">
  26618. <file name="index.html">
  26619. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  26620. cut: {{cut}}
  26621. </file>
  26622. </example>
  26623. */
  26624. /**
  26625. * @ngdoc directive
  26626. * @name ngPaste
  26627. * @restrict A
  26628. * @element window, input, select, textarea, a
  26629. * @priority 0
  26630. *
  26631. * @description
  26632. * Specify custom behavior on paste event.
  26633. *
  26634. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  26635. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  26636. *
  26637. * @example
  26638. <example name="ng-paste">
  26639. <file name="index.html">
  26640. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  26641. pasted: {{paste}}
  26642. </file>
  26643. </example>
  26644. */
  26645. /**
  26646. * @ngdoc directive
  26647. * @name ngIf
  26648. * @restrict A
  26649. * @multiElement
  26650. *
  26651. * @description
  26652. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  26653. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  26654. * value then the element is removed from the DOM, otherwise a clone of the
  26655. * element is reinserted into the DOM.
  26656. *
  26657. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  26658. * element in the DOM rather than changing its visibility via the `display` css property. A common
  26659. * case when this difference is significant is when using css selectors that rely on an element's
  26660. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  26661. *
  26662. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  26663. * is created when the element is restored. The scope created within `ngIf` inherits from
  26664. * its parent scope using
  26665. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  26666. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  26667. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  26668. * variable within the child scope will override (hide) the value in the parent scope.
  26669. *
  26670. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  26671. * is if an element's class attribute is directly modified after it's compiled, using something like
  26672. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  26673. * the added class will be lost because the original compiled state is used to regenerate the element.
  26674. *
  26675. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  26676. * and `leave` effects.
  26677. *
  26678. * @animations
  26679. * | Animation | Occurs |
  26680. * |----------------------------------|-------------------------------------|
  26681. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  26682. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  26683. *
  26684. * @element ANY
  26685. * @scope
  26686. * @priority 600
  26687. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  26688. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  26689. * element is added to the DOM tree.
  26690. *
  26691. * @example
  26692. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
  26693. <file name="index.html">
  26694. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  26695. Show when checked:
  26696. <span ng-if="checked" class="animate-if">
  26697. This is removed when the checkbox is unchecked.
  26698. </span>
  26699. </file>
  26700. <file name="animations.css">
  26701. .animate-if {
  26702. background:white;
  26703. border:1px solid black;
  26704. padding:10px;
  26705. }
  26706. .animate-if.ng-enter, .animate-if.ng-leave {
  26707. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  26708. }
  26709. .animate-if.ng-enter,
  26710. .animate-if.ng-leave.ng-leave-active {
  26711. opacity:0;
  26712. }
  26713. .animate-if.ng-leave,
  26714. .animate-if.ng-enter.ng-enter-active {
  26715. opacity:1;
  26716. }
  26717. </file>
  26718. </example>
  26719. */
  26720. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  26721. return {
  26722. multiElement: true,
  26723. transclude: 'element',
  26724. priority: 600,
  26725. terminal: true,
  26726. restrict: 'A',
  26727. $$tlb: true,
  26728. link: function($scope, $element, $attr, ctrl, $transclude) {
  26729. var block, childScope, previousElements;
  26730. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  26731. if (value) {
  26732. if (!childScope) {
  26733. $transclude(function(clone, newScope) {
  26734. childScope = newScope;
  26735. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  26736. // Note: We only need the first/last node of the cloned nodes.
  26737. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  26738. // by a directive with templateUrl when its template arrives.
  26739. block = {
  26740. clone: clone
  26741. };
  26742. $animate.enter(clone, $element.parent(), $element);
  26743. });
  26744. }
  26745. } else {
  26746. if (previousElements) {
  26747. previousElements.remove();
  26748. previousElements = null;
  26749. }
  26750. if (childScope) {
  26751. childScope.$destroy();
  26752. childScope = null;
  26753. }
  26754. if (block) {
  26755. previousElements = getBlockNodes(block.clone);
  26756. $animate.leave(previousElements).done(function(response) {
  26757. if (response !== false) previousElements = null;
  26758. });
  26759. block = null;
  26760. }
  26761. }
  26762. });
  26763. }
  26764. };
  26765. }];
  26766. /**
  26767. * @ngdoc directive
  26768. * @name ngInclude
  26769. * @restrict ECA
  26770. * @scope
  26771. * @priority -400
  26772. *
  26773. * @description
  26774. * Fetches, compiles and includes an external HTML fragment.
  26775. *
  26776. * By default, the template URL is restricted to the same domain and protocol as the
  26777. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  26778. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  26779. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  26780. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to AngularJS's {@link
  26781. * ng.$sce Strict Contextual Escaping}.
  26782. *
  26783. * In addition, the browser's
  26784. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  26785. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  26786. * policy may further restrict whether the template is successfully loaded.
  26787. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  26788. * access on some browsers.
  26789. *
  26790. * @animations
  26791. * | Animation | Occurs |
  26792. * |----------------------------------|-------------------------------------|
  26793. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  26794. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  26795. *
  26796. * The enter and leave animation occur concurrently.
  26797. *
  26798. * @param {string} ngInclude|src AngularJS expression evaluating to URL. If the source is a string constant,
  26799. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  26800. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  26801. * <div class="alert alert-warning">
  26802. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  26803. * a function with the name on the window element, which will usually throw a
  26804. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  26805. * different form that {@link guide/directive#normalization matches} `onload`.
  26806. * </div>
  26807. *
  26808. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  26809. * $anchorScroll} to scroll the viewport after the content is loaded.
  26810. *
  26811. * - If the attribute is not set, disable scrolling.
  26812. * - If the attribute is set without value, enable scrolling.
  26813. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  26814. *
  26815. * @example
  26816. <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
  26817. <file name="index.html">
  26818. <div ng-controller="ExampleController">
  26819. <select ng-model="template" ng-options="t.name for t in templates">
  26820. <option value="">(blank)</option>
  26821. </select>
  26822. url of the template: <code>{{template.url}}</code>
  26823. <hr/>
  26824. <div class="slide-animate-container">
  26825. <div class="slide-animate" ng-include="template.url"></div>
  26826. </div>
  26827. </div>
  26828. </file>
  26829. <file name="script.js">
  26830. angular.module('includeExample', ['ngAnimate'])
  26831. .controller('ExampleController', ['$scope', function($scope) {
  26832. $scope.templates =
  26833. [{ name: 'template1.html', url: 'template1.html'},
  26834. { name: 'template2.html', url: 'template2.html'}];
  26835. $scope.template = $scope.templates[0];
  26836. }]);
  26837. </file>
  26838. <file name="template1.html">
  26839. Content of template1.html
  26840. </file>
  26841. <file name="template2.html">
  26842. Content of template2.html
  26843. </file>
  26844. <file name="animations.css">
  26845. .slide-animate-container {
  26846. position:relative;
  26847. background:white;
  26848. border:1px solid black;
  26849. height:40px;
  26850. overflow:hidden;
  26851. }
  26852. .slide-animate {
  26853. padding:10px;
  26854. }
  26855. .slide-animate.ng-enter, .slide-animate.ng-leave {
  26856. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  26857. position:absolute;
  26858. top:0;
  26859. left:0;
  26860. right:0;
  26861. bottom:0;
  26862. display:block;
  26863. padding:10px;
  26864. }
  26865. .slide-animate.ng-enter {
  26866. top:-50px;
  26867. }
  26868. .slide-animate.ng-enter.ng-enter-active {
  26869. top:0;
  26870. }
  26871. .slide-animate.ng-leave {
  26872. top:0;
  26873. }
  26874. .slide-animate.ng-leave.ng-leave-active {
  26875. top:50px;
  26876. }
  26877. </file>
  26878. <file name="protractor.js" type="protractor">
  26879. var templateSelect = element(by.model('template'));
  26880. var includeElem = element(by.css('[ng-include]'));
  26881. it('should load template1.html', function() {
  26882. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  26883. });
  26884. it('should load template2.html', function() {
  26885. if (browser.params.browser === 'firefox') {
  26886. // Firefox can't handle using selects
  26887. // See https://github.com/angular/protractor/issues/480
  26888. return;
  26889. }
  26890. templateSelect.click();
  26891. templateSelect.all(by.css('option')).get(2).click();
  26892. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  26893. });
  26894. it('should change to blank', function() {
  26895. if (browser.params.browser === 'firefox') {
  26896. // Firefox can't handle using selects
  26897. return;
  26898. }
  26899. templateSelect.click();
  26900. templateSelect.all(by.css('option')).get(0).click();
  26901. expect(includeElem.isPresent()).toBe(false);
  26902. });
  26903. </file>
  26904. </example>
  26905. */
  26906. /**
  26907. * @ngdoc event
  26908. * @name ngInclude#$includeContentRequested
  26909. * @eventType emit on the scope ngInclude was declared in
  26910. * @description
  26911. * Emitted every time the ngInclude content is requested.
  26912. *
  26913. * @param {Object} angularEvent Synthetic event object.
  26914. * @param {String} src URL of content to load.
  26915. */
  26916. /**
  26917. * @ngdoc event
  26918. * @name ngInclude#$includeContentLoaded
  26919. * @eventType emit on the current ngInclude scope
  26920. * @description
  26921. * Emitted every time the ngInclude content is reloaded.
  26922. *
  26923. * @param {Object} angularEvent Synthetic event object.
  26924. * @param {String} src URL of content to load.
  26925. */
  26926. /**
  26927. * @ngdoc event
  26928. * @name ngInclude#$includeContentError
  26929. * @eventType emit on the scope ngInclude was declared in
  26930. * @description
  26931. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  26932. *
  26933. * @param {Object} angularEvent Synthetic event object.
  26934. * @param {String} src URL of content to load.
  26935. */
  26936. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  26937. function($templateRequest, $anchorScroll, $animate) {
  26938. return {
  26939. restrict: 'ECA',
  26940. priority: 400,
  26941. terminal: true,
  26942. transclude: 'element',
  26943. controller: angular.noop,
  26944. compile: function(element, attr) {
  26945. var srcExp = attr.ngInclude || attr.src,
  26946. onloadExp = attr.onload || '',
  26947. autoScrollExp = attr.autoscroll;
  26948. return function(scope, $element, $attr, ctrl, $transclude) {
  26949. var changeCounter = 0,
  26950. currentScope,
  26951. previousElement,
  26952. currentElement;
  26953. var cleanupLastIncludeContent = function() {
  26954. if (previousElement) {
  26955. previousElement.remove();
  26956. previousElement = null;
  26957. }
  26958. if (currentScope) {
  26959. currentScope.$destroy();
  26960. currentScope = null;
  26961. }
  26962. if (currentElement) {
  26963. $animate.leave(currentElement).done(function(response) {
  26964. if (response !== false) previousElement = null;
  26965. });
  26966. previousElement = currentElement;
  26967. currentElement = null;
  26968. }
  26969. };
  26970. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  26971. var afterAnimation = function(response) {
  26972. if (response !== false && isDefined(autoScrollExp) &&
  26973. (!autoScrollExp || scope.$eval(autoScrollExp))) {
  26974. $anchorScroll();
  26975. }
  26976. };
  26977. var thisChangeId = ++changeCounter;
  26978. if (src) {
  26979. //set the 2nd param to true to ignore the template request error so that the inner
  26980. //contents and scope can be cleaned up.
  26981. $templateRequest(src, true).then(function(response) {
  26982. if (scope.$$destroyed) return;
  26983. if (thisChangeId !== changeCounter) return;
  26984. var newScope = scope.$new();
  26985. ctrl.template = response;
  26986. // Note: This will also link all children of ng-include that were contained in the original
  26987. // html. If that content contains controllers, ... they could pollute/change the scope.
  26988. // However, using ng-include on an element with additional content does not make sense...
  26989. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  26990. // function is called before linking the content, which would apply child
  26991. // directives to non existing elements.
  26992. var clone = $transclude(newScope, function(clone) {
  26993. cleanupLastIncludeContent();
  26994. $animate.enter(clone, null, $element).done(afterAnimation);
  26995. });
  26996. currentScope = newScope;
  26997. currentElement = clone;
  26998. currentScope.$emit('$includeContentLoaded', src);
  26999. scope.$eval(onloadExp);
  27000. }, function() {
  27001. if (scope.$$destroyed) return;
  27002. if (thisChangeId === changeCounter) {
  27003. cleanupLastIncludeContent();
  27004. scope.$emit('$includeContentError', src);
  27005. }
  27006. });
  27007. scope.$emit('$includeContentRequested', src);
  27008. } else {
  27009. cleanupLastIncludeContent();
  27010. ctrl.template = null;
  27011. }
  27012. });
  27013. };
  27014. }
  27015. };
  27016. }];
  27017. // This directive is called during the $transclude call of the first `ngInclude` directive.
  27018. // It will replace and compile the content of the element with the loaded template.
  27019. // We need this directive so that the element content is already filled when
  27020. // the link function of another directive on the same element as ngInclude
  27021. // is called.
  27022. var ngIncludeFillContentDirective = ['$compile',
  27023. function($compile) {
  27024. return {
  27025. restrict: 'ECA',
  27026. priority: -400,
  27027. require: 'ngInclude',
  27028. link: function(scope, $element, $attr, ctrl) {
  27029. if (toString.call($element[0]).match(/SVG/)) {
  27030. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  27031. // support innerHTML, so detect this here and try to generate the contents
  27032. // specially.
  27033. $element.empty();
  27034. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  27035. function namespaceAdaptedClone(clone) {
  27036. $element.append(clone);
  27037. }, {futureParentElement: $element});
  27038. return;
  27039. }
  27040. $element.html(ctrl.template);
  27041. $compile($element.contents())(scope);
  27042. }
  27043. };
  27044. }];
  27045. /**
  27046. * @ngdoc directive
  27047. * @name ngInit
  27048. * @restrict AC
  27049. * @priority 450
  27050. * @element ANY
  27051. *
  27052. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  27053. *
  27054. * @description
  27055. * The `ngInit` directive allows you to evaluate an expression in the
  27056. * current scope.
  27057. *
  27058. * <div class="alert alert-danger">
  27059. * This directive can be abused to add unnecessary amounts of logic into your templates.
  27060. * There are only a few appropriate uses of `ngInit`:
  27061. * <ul>
  27062. * <li>aliasing special properties of {@link ng.directive:ngRepeat `ngRepeat`},
  27063. * as seen in the demo below.</li>
  27064. * <li>initializing data during development, or for examples, as seen throughout these docs.</li>
  27065. * <li>injecting data via server side scripting.</li>
  27066. * </ul>
  27067. *
  27068. * Besides these few cases, you should use {@link guide/component Components} or
  27069. * {@link guide/controller Controllers} rather than `ngInit` to initialize values on a scope.
  27070. * </div>
  27071. *
  27072. * <div class="alert alert-warning">
  27073. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  27074. * sure you have parentheses to ensure correct operator precedence:
  27075. * <pre class="prettyprint">
  27076. * `<div ng-init="test1 = ($index | toString)"></div>`
  27077. * </pre>
  27078. * </div>
  27079. *
  27080. * @example
  27081. <example module="initExample" name="ng-init">
  27082. <file name="index.html">
  27083. <script>
  27084. angular.module('initExample', [])
  27085. .controller('ExampleController', ['$scope', function($scope) {
  27086. $scope.list = [['a', 'b'], ['c', 'd']];
  27087. }]);
  27088. </script>
  27089. <div ng-controller="ExampleController">
  27090. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  27091. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  27092. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  27093. </div>
  27094. </div>
  27095. </div>
  27096. </file>
  27097. <file name="protractor.js" type="protractor">
  27098. it('should alias index positions', function() {
  27099. var elements = element.all(by.css('.example-init'));
  27100. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  27101. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  27102. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  27103. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  27104. });
  27105. </file>
  27106. </example>
  27107. */
  27108. var ngInitDirective = ngDirective({
  27109. priority: 450,
  27110. compile: function() {
  27111. return {
  27112. pre: function(scope, element, attrs) {
  27113. scope.$eval(attrs.ngInit);
  27114. }
  27115. };
  27116. }
  27117. });
  27118. /**
  27119. * @ngdoc directive
  27120. * @name ngList
  27121. * @restrict A
  27122. * @priority 100
  27123. *
  27124. * @param {string=} ngList optional delimiter that should be used to split the value.
  27125. *
  27126. * @description
  27127. * Text input that converts between a delimited string and an array of strings. The default
  27128. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  27129. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  27130. *
  27131. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  27132. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  27133. * list item is respected. This implies that the user of the directive is responsible for
  27134. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  27135. * tab or newline character.
  27136. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  27137. * when joining the list items back together) and whitespace around each list item is stripped
  27138. * before it is added to the model.
  27139. *
  27140. * @example
  27141. * ### Validation
  27142. *
  27143. * <example name="ngList-directive" module="listExample">
  27144. * <file name="app.js">
  27145. * angular.module('listExample', [])
  27146. * .controller('ExampleController', ['$scope', function($scope) {
  27147. * $scope.names = ['morpheus', 'neo', 'trinity'];
  27148. * }]);
  27149. * </file>
  27150. * <file name="index.html">
  27151. * <form name="myForm" ng-controller="ExampleController">
  27152. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  27153. * <span role="alert">
  27154. * <span class="error" ng-show="myForm.namesInput.$error.required">
  27155. * Required!</span>
  27156. * </span>
  27157. * <br>
  27158. * <tt>names = {{names}}</tt><br/>
  27159. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  27160. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  27161. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  27162. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  27163. * </form>
  27164. * </file>
  27165. * <file name="protractor.js" type="protractor">
  27166. * var listInput = element(by.model('names'));
  27167. * var names = element(by.exactBinding('names'));
  27168. * var valid = element(by.binding('myForm.namesInput.$valid'));
  27169. * var error = element(by.css('span.error'));
  27170. *
  27171. * it('should initialize to model', function() {
  27172. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  27173. * expect(valid.getText()).toContain('true');
  27174. * expect(error.getCssValue('display')).toBe('none');
  27175. * });
  27176. *
  27177. * it('should be invalid if empty', function() {
  27178. * listInput.clear();
  27179. * listInput.sendKeys('');
  27180. *
  27181. * expect(names.getText()).toContain('');
  27182. * expect(valid.getText()).toContain('false');
  27183. * expect(error.getCssValue('display')).not.toBe('none');
  27184. * });
  27185. * </file>
  27186. * </example>
  27187. *
  27188. * @example
  27189. * ### Splitting on newline
  27190. *
  27191. * <example name="ngList-directive-newlines">
  27192. * <file name="index.html">
  27193. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  27194. * <pre>{{ list | json }}</pre>
  27195. * </file>
  27196. * <file name="protractor.js" type="protractor">
  27197. * it("should split the text by newlines", function() {
  27198. * var listInput = element(by.model('list'));
  27199. * var output = element(by.binding('list | json'));
  27200. * listInput.sendKeys('abc\ndef\nghi');
  27201. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  27202. * });
  27203. * </file>
  27204. * </example>
  27205. *
  27206. */
  27207. var ngListDirective = function() {
  27208. return {
  27209. restrict: 'A',
  27210. priority: 100,
  27211. require: 'ngModel',
  27212. link: function(scope, element, attr, ctrl) {
  27213. var ngList = attr.ngList || ', ';
  27214. var trimValues = attr.ngTrim !== 'false';
  27215. var separator = trimValues ? trim(ngList) : ngList;
  27216. var parse = function(viewValue) {
  27217. // If the viewValue is invalid (say required but empty) it will be `undefined`
  27218. if (isUndefined(viewValue)) return;
  27219. var list = [];
  27220. if (viewValue) {
  27221. forEach(viewValue.split(separator), function(value) {
  27222. if (value) list.push(trimValues ? trim(value) : value);
  27223. });
  27224. }
  27225. return list;
  27226. };
  27227. ctrl.$parsers.push(parse);
  27228. ctrl.$formatters.push(function(value) {
  27229. if (isArray(value)) {
  27230. return value.join(ngList);
  27231. }
  27232. return undefined;
  27233. });
  27234. // Override the standard $isEmpty because an empty array means the input is empty.
  27235. ctrl.$isEmpty = function(value) {
  27236. return !value || !value.length;
  27237. };
  27238. }
  27239. };
  27240. };
  27241. /* global VALID_CLASS: true,
  27242. INVALID_CLASS: true,
  27243. PRISTINE_CLASS: true,
  27244. DIRTY_CLASS: true,
  27245. UNTOUCHED_CLASS: true,
  27246. TOUCHED_CLASS: true,
  27247. PENDING_CLASS: true,
  27248. addSetValidityMethod: true,
  27249. setupValidity: true,
  27250. defaultModelOptions: false
  27251. */
  27252. var VALID_CLASS = 'ng-valid',
  27253. INVALID_CLASS = 'ng-invalid',
  27254. PRISTINE_CLASS = 'ng-pristine',
  27255. DIRTY_CLASS = 'ng-dirty',
  27256. UNTOUCHED_CLASS = 'ng-untouched',
  27257. TOUCHED_CLASS = 'ng-touched',
  27258. EMPTY_CLASS = 'ng-empty',
  27259. NOT_EMPTY_CLASS = 'ng-not-empty';
  27260. var ngModelMinErr = minErr('ngModel');
  27261. /**
  27262. * @ngdoc type
  27263. * @name ngModel.NgModelController
  27264. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  27265. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  27266. * is set.
  27267. *
  27268. * @property {*} $modelValue The value in the model that the control is bound to.
  27269. *
  27270. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  27271. * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue
  27272. `$viewValue`} from the DOM, usually via user input.
  27273. See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation.
  27274. Note that the `$parsers` are not called when the bound ngModel expression changes programmatically.
  27275. The functions are called in array order, each passing
  27276. its return value through to the next. The last return value is forwarded to the
  27277. {@link ngModel.NgModelController#$validators `$validators`} collection.
  27278. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  27279. `$viewValue`}.
  27280. Returning `undefined` from a parser means a parse error occurred. In that case,
  27281. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  27282. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  27283. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  27284. This simple example shows a parser that would convert text input value to lowercase:
  27285. * ```js
  27286. * function parse(value) {
  27287. * if (value) {
  27288. * return value.toLowerCase();
  27289. * }
  27290. * }
  27291. * ngModelController.$parsers.push(parse);
  27292. * ```
  27293. *
  27294. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  27295. the bound ngModel expression changes programmatically. The `$formatters` are not called when the
  27296. value of the control is changed by user interaction.
  27297. Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue
  27298. `$modelValue`} for display in the control.
  27299. The functions are called in reverse array order, each passing the value through to the
  27300. next. The last return value is used as the actual DOM value.
  27301. This simple example shows a formatter that would convert the model value to uppercase:
  27302. * ```js
  27303. * function format(value) {
  27304. * if (value) {
  27305. * return value.toUpperCase();
  27306. * }
  27307. * }
  27308. * ngModel.$formatters.push(format);
  27309. * ```
  27310. *
  27311. * @property {Object.<string, function>} $validators A collection of validators that are applied
  27312. * whenever the model value changes. The key value within the object refers to the name of the
  27313. * validator while the function refers to the validation operation. The validation operation is
  27314. * provided with the model value as an argument and must return a true or false value depending
  27315. * on the response of that validation.
  27316. *
  27317. * ```js
  27318. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  27319. * var value = modelValue || viewValue;
  27320. * return /[0-9]+/.test(value) &&
  27321. * /[a-z]+/.test(value) &&
  27322. * /[A-Z]+/.test(value) &&
  27323. * /\W+/.test(value);
  27324. * };
  27325. * ```
  27326. *
  27327. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  27328. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  27329. * is expected to return a promise when it is run during the model validation process. Once the promise
  27330. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  27331. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  27332. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  27333. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  27334. * will only run once all synchronous validators have passed.
  27335. *
  27336. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  27337. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  27338. *
  27339. * ```js
  27340. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  27341. * var value = modelValue || viewValue;
  27342. *
  27343. * // Lookup user by username
  27344. * return $http.get('/api/users/' + value).
  27345. * then(function resolved() {
  27346. * //username exists, this means validation fails
  27347. * return $q.reject('exists');
  27348. * }, function rejected() {
  27349. * //username does not exist, therefore this validation passes
  27350. * return true;
  27351. * });
  27352. * };
  27353. * ```
  27354. *
  27355. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever
  27356. * a change to {@link ngModel.NgModelController#$viewValue `$viewValue`} has caused a change
  27357. * to {@link ngModel.NgModelController#$modelValue `$modelValue`}.
  27358. * It is called with no arguments, and its return value is ignored.
  27359. * This can be used in place of additional $watches against the model value.
  27360. *
  27361. * @property {Object} $error An object hash with all failing validator ids as keys.
  27362. * @property {Object} $pending An object hash with all pending validator ids as keys.
  27363. *
  27364. * @property {boolean} $untouched True if control has not lost focus yet.
  27365. * @property {boolean} $touched True if control has lost focus.
  27366. * @property {boolean} $pristine True if user has not interacted with the control yet.
  27367. * @property {boolean} $dirty True if user has already interacted with the control.
  27368. * @property {boolean} $valid True if there is no error.
  27369. * @property {boolean} $invalid True if at least one error on the control.
  27370. * @property {string} $name The name attribute of the control.
  27371. *
  27372. * @description
  27373. *
  27374. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  27375. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  27376. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  27377. * listening to DOM events.
  27378. * Such DOM related logic should be provided by other directives which make use of
  27379. * `NgModelController` for data-binding to control elements.
  27380. * AngularJS provides this DOM logic for most {@link input `input`} elements.
  27381. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  27382. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  27383. *
  27384. * @example
  27385. * ### Custom Control Example
  27386. * This example shows how to use `NgModelController` with a custom control to achieve
  27387. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  27388. * collaborate together to achieve the desired result.
  27389. *
  27390. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  27391. * contents be edited in place by the user.
  27392. *
  27393. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  27394. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  27395. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  27396. * that content using the `$sce` service.
  27397. *
  27398. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  27399. <file name="style.css">
  27400. [contenteditable] {
  27401. border: 1px solid black;
  27402. background-color: white;
  27403. min-height: 20px;
  27404. }
  27405. .ng-invalid {
  27406. border: 1px solid red;
  27407. }
  27408. </file>
  27409. <file name="script.js">
  27410. angular.module('customControl', ['ngSanitize']).
  27411. directive('contenteditable', ['$sce', function($sce) {
  27412. return {
  27413. restrict: 'A', // only activate on element attribute
  27414. require: '?ngModel', // get a hold of NgModelController
  27415. link: function(scope, element, attrs, ngModel) {
  27416. if (!ngModel) return; // do nothing if no ng-model
  27417. // Specify how UI should be updated
  27418. ngModel.$render = function() {
  27419. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  27420. };
  27421. // Listen for change events to enable binding
  27422. element.on('blur keyup change', function() {
  27423. scope.$evalAsync(read);
  27424. });
  27425. read(); // initialize
  27426. // Write data to the model
  27427. function read() {
  27428. var html = element.html();
  27429. // When we clear the content editable the browser leaves a <br> behind
  27430. // If strip-br attribute is provided then we strip this out
  27431. if (attrs.stripBr && html === '<br>') {
  27432. html = '';
  27433. }
  27434. ngModel.$setViewValue(html);
  27435. }
  27436. }
  27437. };
  27438. }]);
  27439. </file>
  27440. <file name="index.html">
  27441. <form name="myForm">
  27442. <div contenteditable
  27443. name="myWidget" ng-model="userContent"
  27444. strip-br="true"
  27445. required>Change me!</div>
  27446. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  27447. <hr>
  27448. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  27449. </form>
  27450. </file>
  27451. <file name="protractor.js" type="protractor">
  27452. it('should data-bind and become invalid', function() {
  27453. if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
  27454. // SafariDriver can't handle contenteditable
  27455. // and Firefox driver can't clear contenteditables very well
  27456. return;
  27457. }
  27458. var contentEditable = element(by.css('[contenteditable]'));
  27459. var content = 'Change me!';
  27460. expect(contentEditable.getText()).toEqual(content);
  27461. contentEditable.clear();
  27462. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  27463. expect(contentEditable.getText()).toEqual('');
  27464. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  27465. });
  27466. </file>
  27467. * </example>
  27468. *
  27469. *
  27470. */
  27471. NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];
  27472. function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {
  27473. this.$viewValue = Number.NaN;
  27474. this.$modelValue = Number.NaN;
  27475. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  27476. this.$validators = {};
  27477. this.$asyncValidators = {};
  27478. this.$parsers = [];
  27479. this.$formatters = [];
  27480. this.$viewChangeListeners = [];
  27481. this.$untouched = true;
  27482. this.$touched = false;
  27483. this.$pristine = true;
  27484. this.$dirty = false;
  27485. this.$valid = true;
  27486. this.$invalid = false;
  27487. this.$error = {}; // keep invalid keys here
  27488. this.$$success = {}; // keep valid keys here
  27489. this.$pending = undefined; // keep pending keys here
  27490. this.$name = $interpolate($attr.name || '', false)($scope);
  27491. this.$$parentForm = nullFormCtrl;
  27492. this.$options = defaultModelOptions;
  27493. this.$$updateEvents = '';
  27494. // Attach the correct context to the event handler function for updateOn
  27495. this.$$updateEventHandler = this.$$updateEventHandler.bind(this);
  27496. this.$$parsedNgModel = $parse($attr.ngModel);
  27497. this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;
  27498. this.$$ngModelGet = this.$$parsedNgModel;
  27499. this.$$ngModelSet = this.$$parsedNgModelAssign;
  27500. this.$$pendingDebounce = null;
  27501. this.$$parserValid = undefined;
  27502. this.$$parserName = 'parse';
  27503. this.$$currentValidationRunId = 0;
  27504. this.$$scope = $scope;
  27505. this.$$rootScope = $scope.$root;
  27506. this.$$attr = $attr;
  27507. this.$$element = $element;
  27508. this.$$animate = $animate;
  27509. this.$$timeout = $timeout;
  27510. this.$$parse = $parse;
  27511. this.$$q = $q;
  27512. this.$$exceptionHandler = $exceptionHandler;
  27513. setupValidity(this);
  27514. setupModelWatcher(this);
  27515. }
  27516. NgModelController.prototype = {
  27517. $$initGetterSetters: function() {
  27518. if (this.$options.getOption('getterSetter')) {
  27519. var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),
  27520. invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');
  27521. this.$$ngModelGet = function($scope) {
  27522. var modelValue = this.$$parsedNgModel($scope);
  27523. if (isFunction(modelValue)) {
  27524. modelValue = invokeModelGetter($scope);
  27525. }
  27526. return modelValue;
  27527. };
  27528. this.$$ngModelSet = function($scope, newValue) {
  27529. if (isFunction(this.$$parsedNgModel($scope))) {
  27530. invokeModelSetter($scope, {$$$p: newValue});
  27531. } else {
  27532. this.$$parsedNgModelAssign($scope, newValue);
  27533. }
  27534. };
  27535. } else if (!this.$$parsedNgModel.assign) {
  27536. throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
  27537. this.$$attr.ngModel, startingTag(this.$$element));
  27538. }
  27539. },
  27540. /**
  27541. * @ngdoc method
  27542. * @name ngModel.NgModelController#$render
  27543. *
  27544. * @description
  27545. * Called when the view needs to be updated. It is expected that the user of the ng-model
  27546. * directive will implement this method.
  27547. *
  27548. * The `$render()` method is invoked in the following situations:
  27549. *
  27550. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  27551. * committed value then `$render()` is called to update the input control.
  27552. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  27553. * the `$viewValue` are different from last time.
  27554. *
  27555. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  27556. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  27557. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  27558. * invoked if you only change a property on the objects.
  27559. */
  27560. $render: noop,
  27561. /**
  27562. * @ngdoc method
  27563. * @name ngModel.NgModelController#$isEmpty
  27564. *
  27565. * @description
  27566. * This is called when we need to determine if the value of an input is empty.
  27567. *
  27568. * For instance, the required directive does this to work out if the input has data or not.
  27569. *
  27570. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  27571. *
  27572. * You can override this for input directives whose concept of being empty is different from the
  27573. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  27574. * implies empty.
  27575. *
  27576. * @param {*} value The value of the input to check for emptiness.
  27577. * @returns {boolean} True if `value` is "empty".
  27578. */
  27579. $isEmpty: function(value) {
  27580. // eslint-disable-next-line no-self-compare
  27581. return isUndefined(value) || value === '' || value === null || value !== value;
  27582. },
  27583. $$updateEmptyClasses: function(value) {
  27584. if (this.$isEmpty(value)) {
  27585. this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);
  27586. this.$$animate.addClass(this.$$element, EMPTY_CLASS);
  27587. } else {
  27588. this.$$animate.removeClass(this.$$element, EMPTY_CLASS);
  27589. this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);
  27590. }
  27591. },
  27592. /**
  27593. * @ngdoc method
  27594. * @name ngModel.NgModelController#$setPristine
  27595. *
  27596. * @description
  27597. * Sets the control to its pristine state.
  27598. *
  27599. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  27600. * state (`ng-pristine` class). A model is considered to be pristine when the control
  27601. * has not been changed from when first compiled.
  27602. */
  27603. $setPristine: function() {
  27604. this.$dirty = false;
  27605. this.$pristine = true;
  27606. this.$$animate.removeClass(this.$$element, DIRTY_CLASS);
  27607. this.$$animate.addClass(this.$$element, PRISTINE_CLASS);
  27608. },
  27609. /**
  27610. * @ngdoc method
  27611. * @name ngModel.NgModelController#$setDirty
  27612. *
  27613. * @description
  27614. * Sets the control to its dirty state.
  27615. *
  27616. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  27617. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  27618. * from when first compiled.
  27619. */
  27620. $setDirty: function() {
  27621. this.$dirty = true;
  27622. this.$pristine = false;
  27623. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  27624. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  27625. this.$$parentForm.$setDirty();
  27626. },
  27627. /**
  27628. * @ngdoc method
  27629. * @name ngModel.NgModelController#$setUntouched
  27630. *
  27631. * @description
  27632. * Sets the control to its untouched state.
  27633. *
  27634. * This method can be called to remove the `ng-touched` class and set the control to its
  27635. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  27636. * by default, however this function can be used to restore that state if the model has
  27637. * already been touched by the user.
  27638. */
  27639. $setUntouched: function() {
  27640. this.$touched = false;
  27641. this.$untouched = true;
  27642. this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  27643. },
  27644. /**
  27645. * @ngdoc method
  27646. * @name ngModel.NgModelController#$setTouched
  27647. *
  27648. * @description
  27649. * Sets the control to its touched state.
  27650. *
  27651. * This method can be called to remove the `ng-untouched` class and set the control to its
  27652. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  27653. * first focused the control element and then shifted focus away from the control (blur event).
  27654. */
  27655. $setTouched: function() {
  27656. this.$touched = true;
  27657. this.$untouched = false;
  27658. this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  27659. },
  27660. /**
  27661. * @ngdoc method
  27662. * @name ngModel.NgModelController#$rollbackViewValue
  27663. *
  27664. * @description
  27665. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  27666. * which may be caused by a pending debounced event or because the input is waiting for some
  27667. * future event.
  27668. *
  27669. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  27670. * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of
  27671. * sync with the ngModel's `$modelValue`.
  27672. *
  27673. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  27674. * and reset the input to the last committed view value.
  27675. *
  27676. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  27677. * programmatically before these debounced/future events have resolved/occurred, because AngularJS's
  27678. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  27679. *
  27680. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  27681. * input which may have such events pending. This is important in order to make sure that the
  27682. * input field will be updated with the new model value and any pending operations are cancelled.
  27683. *
  27684. * @example
  27685. * <example name="ng-model-cancel-update" module="cancel-update-example">
  27686. * <file name="app.js">
  27687. * angular.module('cancel-update-example', [])
  27688. *
  27689. * .controller('CancelUpdateController', ['$scope', function($scope) {
  27690. * $scope.model = {value1: '', value2: ''};
  27691. *
  27692. * $scope.setEmpty = function(e, value, rollback) {
  27693. * if (e.keyCode === 27) {
  27694. * e.preventDefault();
  27695. * if (rollback) {
  27696. * $scope.myForm[value].$rollbackViewValue();
  27697. * }
  27698. * $scope.model[value] = '';
  27699. * }
  27700. * };
  27701. * }]);
  27702. * </file>
  27703. * <file name="index.html">
  27704. * <div ng-controller="CancelUpdateController">
  27705. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  27706. * empty them. Follow these steps and observe the difference:</p>
  27707. * <ol>
  27708. * <li>Type something in the input. You will see that the model is not yet updated</li>
  27709. * <li>Press the Escape key.
  27710. * <ol>
  27711. * <li> In the first example, nothing happens, because the model is already '', and no
  27712. * update is detected. If you blur the input, the model will be set to the current view.
  27713. * </li>
  27714. * <li> In the second example, the pending update is cancelled, and the input is set back
  27715. * to the last committed view value (''). Blurring the input does nothing.
  27716. * </li>
  27717. * </ol>
  27718. * </li>
  27719. * </ol>
  27720. *
  27721. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  27722. * <div>
  27723. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  27724. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  27725. * ng-keydown="setEmpty($event, 'value1')">
  27726. * value1: "{{ model.value1 }}"
  27727. * </div>
  27728. *
  27729. * <div>
  27730. * <p id="inputDescription2">With $rollbackViewValue():</p>
  27731. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  27732. * ng-keydown="setEmpty($event, 'value2', true)">
  27733. * value2: "{{ model.value2 }}"
  27734. * </div>
  27735. * </form>
  27736. * </div>
  27737. * </file>
  27738. <file name="style.css">
  27739. div {
  27740. display: table-cell;
  27741. }
  27742. div:nth-child(1) {
  27743. padding-right: 30px;
  27744. }
  27745. </file>
  27746. * </example>
  27747. */
  27748. $rollbackViewValue: function() {
  27749. this.$$timeout.cancel(this.$$pendingDebounce);
  27750. this.$viewValue = this.$$lastCommittedViewValue;
  27751. this.$render();
  27752. },
  27753. /**
  27754. * @ngdoc method
  27755. * @name ngModel.NgModelController#$validate
  27756. *
  27757. * @description
  27758. * Runs each of the registered validators (first synchronous validators and then
  27759. * asynchronous validators).
  27760. * If the validity changes to invalid, the model will be set to `undefined`,
  27761. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  27762. * If the validity changes to valid, it will set the model to the last available valid
  27763. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  27764. */
  27765. $validate: function() {
  27766. // ignore $validate before model is initialized
  27767. if (isNumberNaN(this.$modelValue)) {
  27768. return;
  27769. }
  27770. var viewValue = this.$$lastCommittedViewValue;
  27771. // Note: we use the $$rawModelValue as $modelValue might have been
  27772. // set to undefined during a view -> model update that found validation
  27773. // errors. We can't parse the view here, since that could change
  27774. // the model although neither viewValue nor the model on the scope changed
  27775. var modelValue = this.$$rawModelValue;
  27776. var prevValid = this.$valid;
  27777. var prevModelValue = this.$modelValue;
  27778. var allowInvalid = this.$options.getOption('allowInvalid');
  27779. var that = this;
  27780. this.$$runValidators(modelValue, viewValue, function(allValid) {
  27781. // If there was no change in validity, don't update the model
  27782. // This prevents changing an invalid modelValue to undefined
  27783. if (!allowInvalid && prevValid !== allValid) {
  27784. // Note: Don't check this.$valid here, as we could have
  27785. // external validators (e.g. calculated on the server),
  27786. // that just call $setValidity and need the model value
  27787. // to calculate their validity.
  27788. that.$modelValue = allValid ? modelValue : undefined;
  27789. if (that.$modelValue !== prevModelValue) {
  27790. that.$$writeModelToScope();
  27791. }
  27792. }
  27793. });
  27794. },
  27795. $$runValidators: function(modelValue, viewValue, doneCallback) {
  27796. this.$$currentValidationRunId++;
  27797. var localValidationRunId = this.$$currentValidationRunId;
  27798. var that = this;
  27799. // check parser error
  27800. if (!processParseErrors()) {
  27801. validationDone(false);
  27802. return;
  27803. }
  27804. if (!processSyncValidators()) {
  27805. validationDone(false);
  27806. return;
  27807. }
  27808. processAsyncValidators();
  27809. function processParseErrors() {
  27810. var errorKey = that.$$parserName;
  27811. if (isUndefined(that.$$parserValid)) {
  27812. setValidity(errorKey, null);
  27813. } else {
  27814. if (!that.$$parserValid) {
  27815. forEach(that.$validators, function(v, name) {
  27816. setValidity(name, null);
  27817. });
  27818. forEach(that.$asyncValidators, function(v, name) {
  27819. setValidity(name, null);
  27820. });
  27821. }
  27822. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  27823. setValidity(errorKey, that.$$parserValid);
  27824. return that.$$parserValid;
  27825. }
  27826. return true;
  27827. }
  27828. function processSyncValidators() {
  27829. var syncValidatorsValid = true;
  27830. forEach(that.$validators, function(validator, name) {
  27831. var result = Boolean(validator(modelValue, viewValue));
  27832. syncValidatorsValid = syncValidatorsValid && result;
  27833. setValidity(name, result);
  27834. });
  27835. if (!syncValidatorsValid) {
  27836. forEach(that.$asyncValidators, function(v, name) {
  27837. setValidity(name, null);
  27838. });
  27839. return false;
  27840. }
  27841. return true;
  27842. }
  27843. function processAsyncValidators() {
  27844. var validatorPromises = [];
  27845. var allValid = true;
  27846. forEach(that.$asyncValidators, function(validator, name) {
  27847. var promise = validator(modelValue, viewValue);
  27848. if (!isPromiseLike(promise)) {
  27849. throw ngModelMinErr('nopromise',
  27850. 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
  27851. }
  27852. setValidity(name, undefined);
  27853. validatorPromises.push(promise.then(function() {
  27854. setValidity(name, true);
  27855. }, function() {
  27856. allValid = false;
  27857. setValidity(name, false);
  27858. }));
  27859. });
  27860. if (!validatorPromises.length) {
  27861. validationDone(true);
  27862. } else {
  27863. that.$$q.all(validatorPromises).then(function() {
  27864. validationDone(allValid);
  27865. }, noop);
  27866. }
  27867. }
  27868. function setValidity(name, isValid) {
  27869. if (localValidationRunId === that.$$currentValidationRunId) {
  27870. that.$setValidity(name, isValid);
  27871. }
  27872. }
  27873. function validationDone(allValid) {
  27874. if (localValidationRunId === that.$$currentValidationRunId) {
  27875. doneCallback(allValid);
  27876. }
  27877. }
  27878. },
  27879. /**
  27880. * @ngdoc method
  27881. * @name ngModel.NgModelController#$commitViewValue
  27882. *
  27883. * @description
  27884. * Commit a pending update to the `$modelValue`.
  27885. *
  27886. * Updates may be pending by a debounced event or because the input is waiting for a some future
  27887. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  27888. * usually handles calling this in response to input events.
  27889. */
  27890. $commitViewValue: function() {
  27891. var viewValue = this.$viewValue;
  27892. this.$$timeout.cancel(this.$$pendingDebounce);
  27893. // If the view value has not changed then we should just exit, except in the case where there is
  27894. // a native validator on the element. In this case the validation state may have changed even though
  27895. // the viewValue has stayed empty.
  27896. if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {
  27897. return;
  27898. }
  27899. this.$$updateEmptyClasses(viewValue);
  27900. this.$$lastCommittedViewValue = viewValue;
  27901. // change to dirty
  27902. if (this.$pristine) {
  27903. this.$setDirty();
  27904. }
  27905. this.$$parseAndValidate();
  27906. },
  27907. $$parseAndValidate: function() {
  27908. var viewValue = this.$$lastCommittedViewValue;
  27909. var modelValue = viewValue;
  27910. var that = this;
  27911. this.$$parserValid = isUndefined(modelValue) ? undefined : true;
  27912. // Reset any previous parse error
  27913. this.$setValidity(this.$$parserName, null);
  27914. this.$$parserName = 'parse';
  27915. if (this.$$parserValid) {
  27916. for (var i = 0; i < this.$parsers.length; i++) {
  27917. modelValue = this.$parsers[i](modelValue);
  27918. if (isUndefined(modelValue)) {
  27919. this.$$parserValid = false;
  27920. break;
  27921. }
  27922. }
  27923. }
  27924. if (isNumberNaN(this.$modelValue)) {
  27925. // this.$modelValue has not been touched yet...
  27926. this.$modelValue = this.$$ngModelGet(this.$$scope);
  27927. }
  27928. var prevModelValue = this.$modelValue;
  27929. var allowInvalid = this.$options.getOption('allowInvalid');
  27930. this.$$rawModelValue = modelValue;
  27931. if (allowInvalid) {
  27932. this.$modelValue = modelValue;
  27933. writeToModelIfNeeded();
  27934. }
  27935. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  27936. // This can happen if e.g. $setViewValue is called from inside a parser
  27937. this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {
  27938. if (!allowInvalid) {
  27939. // Note: Don't check this.$valid here, as we could have
  27940. // external validators (e.g. calculated on the server),
  27941. // that just call $setValidity and need the model value
  27942. // to calculate their validity.
  27943. that.$modelValue = allValid ? modelValue : undefined;
  27944. writeToModelIfNeeded();
  27945. }
  27946. });
  27947. function writeToModelIfNeeded() {
  27948. if (that.$modelValue !== prevModelValue) {
  27949. that.$$writeModelToScope();
  27950. }
  27951. }
  27952. },
  27953. $$writeModelToScope: function() {
  27954. this.$$ngModelSet(this.$$scope, this.$modelValue);
  27955. forEach(this.$viewChangeListeners, function(listener) {
  27956. try {
  27957. listener();
  27958. } catch (e) {
  27959. // eslint-disable-next-line no-invalid-this
  27960. this.$$exceptionHandler(e);
  27961. }
  27962. }, this);
  27963. },
  27964. /**
  27965. * @ngdoc method
  27966. * @name ngModel.NgModelController#$setViewValue
  27967. *
  27968. * @description
  27969. * Update the view value.
  27970. *
  27971. * This method should be called when a control wants to change the view value; typically,
  27972. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  27973. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  27974. * calls it when an option is selected.
  27975. *
  27976. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  27977. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  27978. * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and
  27979. * `$asyncValidators` are called and the value is applied to `$modelValue`.
  27980. * Finally, the value is set to the **expression** specified in the `ng-model` attribute and
  27981. * all the registered change listeners, in the `$viewChangeListeners` list are called.
  27982. *
  27983. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  27984. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  27985. * `updateOn` events is triggered on the DOM element.
  27986. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  27987. * directive is used with a custom debounce for this particular event.
  27988. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  27989. * is specified, once the timer runs out.
  27990. *
  27991. * When used with standard inputs, the view value will always be a string (which is in some cases
  27992. * parsed into another type, such as a `Date` object for `input[date]`.)
  27993. * However, custom controls might also pass objects to this method. In this case, we should make
  27994. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  27995. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  27996. * the property of the object then ngModel will not realize that the object has changed and
  27997. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  27998. * not change properties of the copy once it has been passed to `$setViewValue`.
  27999. * Otherwise you may cause the model value on the scope to change incorrectly.
  28000. *
  28001. * <div class="alert alert-info">
  28002. * In any case, the value passed to the method should always reflect the current value
  28003. * of the control. For example, if you are calling `$setViewValue` for an input element,
  28004. * you should pass the input DOM value. Otherwise, the control and the scope model become
  28005. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  28006. * the control's DOM value in any way. If we want to change the control's DOM value
  28007. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  28008. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  28009. * to update the DOM, and finally call `$validate` on it.
  28010. * </div>
  28011. *
  28012. * @param {*} value value from the view.
  28013. * @param {string} trigger Event that triggered the update.
  28014. */
  28015. $setViewValue: function(value, trigger) {
  28016. this.$viewValue = value;
  28017. if (this.$options.getOption('updateOnDefault')) {
  28018. this.$$debounceViewValueCommit(trigger);
  28019. }
  28020. },
  28021. $$debounceViewValueCommit: function(trigger) {
  28022. var debounceDelay = this.$options.getOption('debounce');
  28023. if (isNumber(debounceDelay[trigger])) {
  28024. debounceDelay = debounceDelay[trigger];
  28025. } else if (isNumber(debounceDelay['default']) &&
  28026. this.$options.getOption('updateOn').indexOf(trigger) === -1
  28027. ) {
  28028. debounceDelay = debounceDelay['default'];
  28029. } else if (isNumber(debounceDelay['*'])) {
  28030. debounceDelay = debounceDelay['*'];
  28031. }
  28032. this.$$timeout.cancel(this.$$pendingDebounce);
  28033. var that = this;
  28034. if (debounceDelay > 0) { // this fails if debounceDelay is an object
  28035. this.$$pendingDebounce = this.$$timeout(function() {
  28036. that.$commitViewValue();
  28037. }, debounceDelay);
  28038. } else if (this.$$rootScope.$$phase) {
  28039. this.$commitViewValue();
  28040. } else {
  28041. this.$$scope.$apply(function() {
  28042. that.$commitViewValue();
  28043. });
  28044. }
  28045. },
  28046. /**
  28047. * @ngdoc method
  28048. *
  28049. * @name ngModel.NgModelController#$overrideModelOptions
  28050. *
  28051. * @description
  28052. *
  28053. * Override the current model options settings programmatically.
  28054. *
  28055. * The previous `ModelOptions` value will not be modified. Instead, a
  28056. * new `ModelOptions` object will inherit from the previous one overriding
  28057. * or inheriting settings that are defined in the given parameter.
  28058. *
  28059. * See {@link ngModelOptions} for information about what options can be specified
  28060. * and how model option inheritance works.
  28061. *
  28062. * <div class="alert alert-warning">
  28063. * **Note:** this function only affects the options set on the `ngModelController`,
  28064. * and not the options on the {@link ngModelOptions} directive from which they might have been
  28065. * obtained initially.
  28066. * </div>
  28067. *
  28068. * <div class="alert alert-danger">
  28069. * **Note:** it is not possible to override the `getterSetter` option.
  28070. * </div>
  28071. *
  28072. * @param {Object} options a hash of settings to override the previous options
  28073. *
  28074. */
  28075. $overrideModelOptions: function(options) {
  28076. this.$options = this.$options.createChild(options);
  28077. this.$$setUpdateOnEvents();
  28078. },
  28079. /**
  28080. * @ngdoc method
  28081. *
  28082. * @name ngModel.NgModelController#$processModelValue
  28083. * @description
  28084. *
  28085. * Runs the model -> view pipeline on the current
  28086. * {@link ngModel.NgModelController#$modelValue $modelValue}.
  28087. *
  28088. * The following actions are performed by this method:
  28089. *
  28090. * - the `$modelValue` is run through the {@link ngModel.NgModelController#$formatters $formatters}
  28091. * and the result is set to the {@link ngModel.NgModelController#$viewValue $viewValue}
  28092. * - the `ng-empty` or `ng-not-empty` class is set on the element
  28093. * - if the `$viewValue` has changed:
  28094. * - {@link ngModel.NgModelController#$render $render} is called on the control
  28095. * - the {@link ngModel.NgModelController#$validators $validators} are run and
  28096. * the validation status is set.
  28097. *
  28098. * This method is called by ngModel internally when the bound scope value changes.
  28099. * Application developers usually do not have to call this function themselves.
  28100. *
  28101. * This function can be used when the `$viewValue` or the rendered DOM value are not correctly
  28102. * formatted and the `$modelValue` must be run through the `$formatters` again.
  28103. *
  28104. * @example
  28105. * Consider a text input with an autocomplete list (for fruit), where the items are
  28106. * objects with a name and an id.
  28107. * A user enters `ap` and then selects `Apricot` from the list.
  28108. * Based on this, the autocomplete widget will call `$setViewValue({name: 'Apricot', id: 443})`,
  28109. * but the rendered value will still be `ap`.
  28110. * The widget can then call `ctrl.$processModelValue()` to run the model -> view
  28111. * pipeline again, which formats the object to the string `Apricot`,
  28112. * then updates the `$viewValue`, and finally renders it in the DOM.
  28113. *
  28114. * <example module="inputExample" name="ng-model-process">
  28115. <file name="index.html">
  28116. <div ng-controller="inputController" style="display: flex;">
  28117. <div style="margin-right: 30px;">
  28118. Search Fruit:
  28119. <basic-autocomplete items="items" on-select="selectedFruit = item"></basic-autocomplete>
  28120. </div>
  28121. <div>
  28122. Model:<br>
  28123. <pre>{{selectedFruit | json}}</pre>
  28124. </div>
  28125. </div>
  28126. </file>
  28127. <file name="app.js">
  28128. angular.module('inputExample', [])
  28129. .controller('inputController', function($scope) {
  28130. $scope.items = [
  28131. {name: 'Apricot', id: 443},
  28132. {name: 'Clementine', id: 972},
  28133. {name: 'Durian', id: 169},
  28134. {name: 'Jackfruit', id: 982},
  28135. {name: 'Strawberry', id: 863}
  28136. ];
  28137. })
  28138. .component('basicAutocomplete', {
  28139. bindings: {
  28140. items: '<',
  28141. onSelect: '&'
  28142. },
  28143. templateUrl: 'autocomplete.html',
  28144. controller: function($element, $scope) {
  28145. var that = this;
  28146. var ngModel;
  28147. that.$postLink = function() {
  28148. ngModel = $element.find('input').controller('ngModel');
  28149. ngModel.$formatters.push(function(value) {
  28150. return (value && value.name) || value;
  28151. });
  28152. ngModel.$parsers.push(function(value) {
  28153. var match = value;
  28154. for (var i = 0; i < that.items.length; i++) {
  28155. if (that.items[i].name === value) {
  28156. match = that.items[i];
  28157. break;
  28158. }
  28159. }
  28160. return match;
  28161. });
  28162. };
  28163. that.selectItem = function(item) {
  28164. ngModel.$setViewValue(item);
  28165. ngModel.$processModelValue();
  28166. that.onSelect({item: item});
  28167. };
  28168. }
  28169. });
  28170. </file>
  28171. <file name="autocomplete.html">
  28172. <div>
  28173. <input type="search" ng-model="$ctrl.searchTerm" />
  28174. <ul>
  28175. <li ng-repeat="item in $ctrl.items | filter:$ctrl.searchTerm">
  28176. <button ng-click="$ctrl.selectItem(item)">{{ item.name }}</button>
  28177. </li>
  28178. </ul>
  28179. </div>
  28180. </file>
  28181. * </example>
  28182. *
  28183. */
  28184. $processModelValue: function() {
  28185. var viewValue = this.$$format();
  28186. if (this.$viewValue !== viewValue) {
  28187. this.$$updateEmptyClasses(viewValue);
  28188. this.$viewValue = this.$$lastCommittedViewValue = viewValue;
  28189. this.$render();
  28190. // It is possible that model and view value have been updated during render
  28191. this.$$runValidators(this.$modelValue, this.$viewValue, noop);
  28192. }
  28193. },
  28194. /**
  28195. * This method is called internally to run the $formatters on the $modelValue
  28196. */
  28197. $$format: function() {
  28198. var formatters = this.$formatters,
  28199. idx = formatters.length;
  28200. var viewValue = this.$modelValue;
  28201. while (idx--) {
  28202. viewValue = formatters[idx](viewValue);
  28203. }
  28204. return viewValue;
  28205. },
  28206. /**
  28207. * This method is called internally when the bound scope value changes.
  28208. */
  28209. $$setModelValue: function(modelValue) {
  28210. this.$modelValue = this.$$rawModelValue = modelValue;
  28211. this.$$parserValid = undefined;
  28212. this.$processModelValue();
  28213. },
  28214. $$setUpdateOnEvents: function() {
  28215. if (this.$$updateEvents) {
  28216. this.$$element.off(this.$$updateEvents, this.$$updateEventHandler);
  28217. }
  28218. this.$$updateEvents = this.$options.getOption('updateOn');
  28219. if (this.$$updateEvents) {
  28220. this.$$element.on(this.$$updateEvents, this.$$updateEventHandler);
  28221. }
  28222. },
  28223. $$updateEventHandler: function(ev) {
  28224. this.$$debounceViewValueCommit(ev && ev.type);
  28225. }
  28226. };
  28227. function setupModelWatcher(ctrl) {
  28228. // model -> value
  28229. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  28230. // 1. scope value is 'a'
  28231. // 2. user enters 'b'
  28232. // 3. ng-change kicks in and reverts scope value to 'a'
  28233. // -> scope value did not change since the last digest as
  28234. // ng-change executes in apply phase
  28235. // 4. view should be changed back to 'a'
  28236. ctrl.$$scope.$watch(function ngModelWatch(scope) {
  28237. var modelValue = ctrl.$$ngModelGet(scope);
  28238. // if scope model value and ngModel value are out of sync
  28239. // This cannot be moved to the action function, because it would not catch the
  28240. // case where the model is changed in the ngChange function or the model setter
  28241. if (modelValue !== ctrl.$modelValue &&
  28242. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  28243. // eslint-disable-next-line no-self-compare
  28244. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  28245. ) {
  28246. ctrl.$$setModelValue(modelValue);
  28247. }
  28248. return modelValue;
  28249. });
  28250. }
  28251. /**
  28252. * @ngdoc method
  28253. * @name ngModel.NgModelController#$setValidity
  28254. *
  28255. * @description
  28256. * Change the validity state, and notify the form.
  28257. *
  28258. * This method can be called within $parsers/$formatters or a custom validation implementation.
  28259. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  28260. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  28261. *
  28262. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  28263. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  28264. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  28265. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  28266. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  28267. * classes and can be bound to as `{{ someForm.someControl.$error.myError }}`.
  28268. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  28269. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  28270. * Skipped is used by AngularJS when validators do not run because of parse errors and
  28271. * when `$asyncValidators` do not run because any of the `$validators` failed.
  28272. */
  28273. addSetValidityMethod({
  28274. clazz: NgModelController,
  28275. set: function(object, property) {
  28276. object[property] = true;
  28277. },
  28278. unset: function(object, property) {
  28279. delete object[property];
  28280. }
  28281. });
  28282. /**
  28283. * @ngdoc directive
  28284. * @name ngModel
  28285. * @restrict A
  28286. * @priority 1
  28287. * @param {expression} ngModel assignable {@link guide/expression Expression} to bind to.
  28288. *
  28289. * @description
  28290. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  28291. * property on the scope using {@link ngModel.NgModelController NgModelController},
  28292. * which is created and exposed by this directive.
  28293. *
  28294. * `ngModel` is responsible for:
  28295. *
  28296. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  28297. * require.
  28298. * - Providing validation behavior (i.e. required, number, email, url).
  28299. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  28300. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  28301. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  28302. * - Registering the control with its parent {@link ng.directive:form form}.
  28303. *
  28304. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  28305. * current scope. If the property doesn't already exist on this scope, it will be created
  28306. * implicitly and added to the scope.
  28307. *
  28308. * For best practices on using `ngModel`, see:
  28309. *
  28310. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  28311. *
  28312. * For basic examples, how to use `ngModel`, see:
  28313. *
  28314. * - {@link ng.directive:input input}
  28315. * - {@link input[text] text}
  28316. * - {@link input[checkbox] checkbox}
  28317. * - {@link input[radio] radio}
  28318. * - {@link input[number] number}
  28319. * - {@link input[email] email}
  28320. * - {@link input[url] url}
  28321. * - {@link input[date] date}
  28322. * - {@link input[datetime-local] datetime-local}
  28323. * - {@link input[time] time}
  28324. * - {@link input[month] month}
  28325. * - {@link input[week] week}
  28326. * - {@link ng.directive:select select}
  28327. * - {@link ng.directive:textarea textarea}
  28328. *
  28329. * ## Complex Models (objects or collections)
  28330. *
  28331. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  28332. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  28333. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  28334. *
  28335. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  28336. *
  28337. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  28338. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  28339. * if the select is given the `multiple` attribute.
  28340. *
  28341. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  28342. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  28343. * not trigger a re-rendering of the model.
  28344. *
  28345. * ## CSS classes
  28346. * The following CSS classes are added and removed on the associated input/select/textarea element
  28347. * depending on the validity of the model.
  28348. *
  28349. * - `ng-valid`: the model is valid
  28350. * - `ng-invalid`: the model is invalid
  28351. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  28352. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  28353. * - `ng-pristine`: the control hasn't been interacted with yet
  28354. * - `ng-dirty`: the control has been interacted with
  28355. * - `ng-touched`: the control has been blurred
  28356. * - `ng-untouched`: the control hasn't been blurred
  28357. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  28358. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  28359. * by the {@link ngModel.NgModelController#$isEmpty} method
  28360. * - `ng-not-empty`: the view contains a non-empty value
  28361. *
  28362. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  28363. *
  28364. * @animations
  28365. * Animations within models are triggered when any of the associated CSS classes are added and removed
  28366. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  28367. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  28368. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  28369. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  28370. *
  28371. * The following example shows a simple way to utilize CSS transitions to style an input element
  28372. * that has been rendered as invalid after it has been validated:
  28373. *
  28374. * <pre>
  28375. * //be sure to include ngAnimate as a module to hook into more
  28376. * //advanced animations
  28377. * .my-input {
  28378. * transition:0.5s linear all;
  28379. * background: white;
  28380. * }
  28381. * .my-input.ng-invalid {
  28382. * background: red;
  28383. * color:white;
  28384. * }
  28385. * </pre>
  28386. *
  28387. * @example
  28388. * ### Basic Usage
  28389. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
  28390. <file name="index.html">
  28391. <script>
  28392. angular.module('inputExample', [])
  28393. .controller('ExampleController', ['$scope', function($scope) {
  28394. $scope.val = '1';
  28395. }]);
  28396. </script>
  28397. <style>
  28398. .my-input {
  28399. transition:all linear 0.5s;
  28400. background: transparent;
  28401. }
  28402. .my-input.ng-invalid {
  28403. color:white;
  28404. background: red;
  28405. }
  28406. </style>
  28407. <p id="inputDescription">
  28408. Update input to see transitions when valid/invalid.
  28409. Integer is a valid value.
  28410. </p>
  28411. <form name="testForm" ng-controller="ExampleController">
  28412. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  28413. aria-describedby="inputDescription" />
  28414. </form>
  28415. </file>
  28416. * </example>
  28417. *
  28418. * @example
  28419. * ### Binding to a getter/setter
  28420. *
  28421. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  28422. * function that returns a representation of the model when called with zero arguments, and sets
  28423. * the internal state of a model when called with an argument. It's sometimes useful to use this
  28424. * for models that have an internal representation that's different from what the model exposes
  28425. * to the view.
  28426. *
  28427. * <div class="alert alert-success">
  28428. * **Best Practice:** It's best to keep getters fast because AngularJS is likely to call them more
  28429. * frequently than other parts of your code.
  28430. * </div>
  28431. *
  28432. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  28433. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  28434. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  28435. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  28436. *
  28437. * The following example shows how to use `ngModel` with a getter/setter:
  28438. *
  28439. * @example
  28440. * <example name="ngModel-getter-setter" module="getterSetterExample">
  28441. <file name="index.html">
  28442. <div ng-controller="ExampleController">
  28443. <form name="userForm">
  28444. <label>Name:
  28445. <input type="text" name="userName"
  28446. ng-model="user.name"
  28447. ng-model-options="{ getterSetter: true }" />
  28448. </label>
  28449. </form>
  28450. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  28451. </div>
  28452. </file>
  28453. <file name="app.js">
  28454. angular.module('getterSetterExample', [])
  28455. .controller('ExampleController', ['$scope', function($scope) {
  28456. var _name = 'Brian';
  28457. $scope.user = {
  28458. name: function(newName) {
  28459. // Note that newName can be undefined for two reasons:
  28460. // 1. Because it is called as a getter and thus called with no arguments
  28461. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  28462. // input is invalid
  28463. return arguments.length ? (_name = newName) : _name;
  28464. }
  28465. };
  28466. }]);
  28467. </file>
  28468. * </example>
  28469. */
  28470. var ngModelDirective = ['$rootScope', function($rootScope) {
  28471. return {
  28472. restrict: 'A',
  28473. require: ['ngModel', '^?form', '^?ngModelOptions'],
  28474. controller: NgModelController,
  28475. // Prelink needs to run before any input directive
  28476. // so that we can set the NgModelOptions in NgModelController
  28477. // before anyone else uses it.
  28478. priority: 1,
  28479. compile: function ngModelCompile(element) {
  28480. // Setup initial state of the control
  28481. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  28482. return {
  28483. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  28484. var modelCtrl = ctrls[0],
  28485. formCtrl = ctrls[1] || modelCtrl.$$parentForm,
  28486. optionsCtrl = ctrls[2];
  28487. if (optionsCtrl) {
  28488. modelCtrl.$options = optionsCtrl.$options;
  28489. }
  28490. modelCtrl.$$initGetterSetters();
  28491. // notify others, especially parent forms
  28492. formCtrl.$addControl(modelCtrl);
  28493. attr.$observe('name', function(newValue) {
  28494. if (modelCtrl.$name !== newValue) {
  28495. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  28496. }
  28497. });
  28498. scope.$on('$destroy', function() {
  28499. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  28500. });
  28501. },
  28502. post: function ngModelPostLink(scope, element, attr, ctrls) {
  28503. var modelCtrl = ctrls[0];
  28504. modelCtrl.$$setUpdateOnEvents();
  28505. function setTouched() {
  28506. modelCtrl.$setTouched();
  28507. }
  28508. element.on('blur', function() {
  28509. if (modelCtrl.$touched) return;
  28510. if ($rootScope.$$phase) {
  28511. scope.$evalAsync(setTouched);
  28512. } else {
  28513. scope.$apply(setTouched);
  28514. }
  28515. });
  28516. }
  28517. };
  28518. }
  28519. };
  28520. }];
  28521. /* exported defaultModelOptions */
  28522. var defaultModelOptions;
  28523. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  28524. /**
  28525. * @ngdoc type
  28526. * @name ModelOptions
  28527. * @description
  28528. * A container for the options set by the {@link ngModelOptions} directive
  28529. */
  28530. function ModelOptions(options) {
  28531. this.$$options = options;
  28532. }
  28533. ModelOptions.prototype = {
  28534. /**
  28535. * @ngdoc method
  28536. * @name ModelOptions#getOption
  28537. * @param {string} name the name of the option to retrieve
  28538. * @returns {*} the value of the option
  28539. * @description
  28540. * Returns the value of the given option
  28541. */
  28542. getOption: function(name) {
  28543. return this.$$options[name];
  28544. },
  28545. /**
  28546. * @ngdoc method
  28547. * @name ModelOptions#createChild
  28548. * @param {Object} options a hash of options for the new child that will override the parent's options
  28549. * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
  28550. */
  28551. createChild: function(options) {
  28552. var inheritAll = false;
  28553. // make a shallow copy
  28554. options = extend({}, options);
  28555. // Inherit options from the parent if specified by the value `"$inherit"`
  28556. forEach(options, /** @this */ function(option, key) {
  28557. if (option === '$inherit') {
  28558. if (key === '*') {
  28559. inheritAll = true;
  28560. } else {
  28561. options[key] = this.$$options[key];
  28562. // `updateOn` is special so we must also inherit the `updateOnDefault` option
  28563. if (key === 'updateOn') {
  28564. options.updateOnDefault = this.$$options.updateOnDefault;
  28565. }
  28566. }
  28567. } else {
  28568. if (key === 'updateOn') {
  28569. // If the `updateOn` property contains the `default` event then we have to remove
  28570. // it from the event list and set the `updateOnDefault` flag.
  28571. options.updateOnDefault = false;
  28572. options[key] = trim(option.replace(DEFAULT_REGEXP, function() {
  28573. options.updateOnDefault = true;
  28574. return ' ';
  28575. }));
  28576. }
  28577. }
  28578. }, this);
  28579. if (inheritAll) {
  28580. // We have a property of the form: `"*": "$inherit"`
  28581. delete options['*'];
  28582. defaults(options, this.$$options);
  28583. }
  28584. // Finally add in any missing defaults
  28585. defaults(options, defaultModelOptions.$$options);
  28586. return new ModelOptions(options);
  28587. }
  28588. };
  28589. defaultModelOptions = new ModelOptions({
  28590. updateOn: '',
  28591. updateOnDefault: true,
  28592. debounce: 0,
  28593. getterSetter: false,
  28594. allowInvalid: false,
  28595. timezone: null
  28596. });
  28597. /**
  28598. * @ngdoc directive
  28599. * @name ngModelOptions
  28600. * @restrict A
  28601. * @priority 10
  28602. *
  28603. * @description
  28604. * This directive allows you to modify the behaviour of {@link ngModel} directives within your
  28605. * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}
  28606. * directives will use the options of their nearest `ngModelOptions` ancestor.
  28607. *
  28608. * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as
  28609. * an AngularJS expression. This expression should evaluate to an object, whose properties contain
  28610. * the settings. For example: `<div ng-model-options="{ debounce: 100 }"`.
  28611. *
  28612. * ## Inheriting Options
  28613. *
  28614. * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions`
  28615. * directive by giving it the value of `"$inherit"`.
  28616. * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the
  28617. * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings
  28618. * will be used.
  28619. *
  28620. * For example given the following fragment of HTML
  28621. *
  28622. *
  28623. * ```html
  28624. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  28625. * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }">
  28626. * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" />
  28627. * </form>
  28628. * </div>
  28629. * ```
  28630. *
  28631. * the `input` element will have the following settings
  28632. *
  28633. * ```js
  28634. * { allowInvalid: true, updateOn: 'default', debounce: 0 }
  28635. * ```
  28636. *
  28637. * Notice that the `debounce` setting was not inherited and used the default value instead.
  28638. *
  28639. * You can specify that all undefined settings are automatically inherited from an ancestor by
  28640. * including a property with key of `"*"` and value of `"$inherit"`.
  28641. *
  28642. * For example given the following fragment of HTML
  28643. *
  28644. *
  28645. * ```html
  28646. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  28647. * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }">
  28648. * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" />
  28649. * </form>
  28650. * </div>
  28651. * ```
  28652. *
  28653. * the `input` element will have the following settings
  28654. *
  28655. * ```js
  28656. * { allowInvalid: true, updateOn: 'default', debounce: 200 }
  28657. * ```
  28658. *
  28659. * Notice that the `debounce` setting now inherits the value from the outer `<div>` element.
  28660. *
  28661. * If you are creating a reusable component then you should be careful when using `"*": "$inherit"`
  28662. * since you may inadvertently inherit a setting in the future that changes the behavior of your component.
  28663. *
  28664. *
  28665. * ## Triggering and debouncing model updates
  28666. *
  28667. * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
  28668. * trigger a model update and/or a debouncing delay so that the actual update only takes place when
  28669. * a timer expires; this timer will be reset after another change takes place.
  28670. *
  28671. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  28672. * be different from the value in the actual model. This means that if you update the model you
  28673. * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in
  28674. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  28675. *
  28676. * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}
  28677. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  28678. * important because `form` controllers are published to the related scope under the name in their
  28679. * `name` attribute.
  28680. *
  28681. * Any pending changes will take place immediately when an enclosing form is submitted via the
  28682. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  28683. * to have access to the updated model.
  28684. *
  28685. * ### Overriding immediate updates
  28686. *
  28687. * The following example shows how to override immediate updates. Changes on the inputs within the
  28688. * form will update the model only when the control loses focus (blur event). If `escape` key is
  28689. * pressed while the input field is focused, the value is reset to the value in the current model.
  28690. *
  28691. * <example name="ngModelOptions-directive-blur" module="optionsExample">
  28692. * <file name="index.html">
  28693. * <div ng-controller="ExampleController">
  28694. * <form name="userForm">
  28695. * <label>
  28696. * Name:
  28697. * <input type="text" name="userName"
  28698. * ng-model="user.name"
  28699. * ng-model-options="{ updateOn: 'blur' }"
  28700. * ng-keyup="cancel($event)" />
  28701. * </label><br />
  28702. * <label>
  28703. * Other data:
  28704. * <input type="text" ng-model="user.data" />
  28705. * </label><br />
  28706. * </form>
  28707. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  28708. * </div>
  28709. * </file>
  28710. * <file name="app.js">
  28711. * angular.module('optionsExample', [])
  28712. * .controller('ExampleController', ['$scope', function($scope) {
  28713. * $scope.user = { name: 'say', data: '' };
  28714. *
  28715. * $scope.cancel = function(e) {
  28716. * if (e.keyCode === 27) {
  28717. * $scope.userForm.userName.$rollbackViewValue();
  28718. * }
  28719. * };
  28720. * }]);
  28721. * </file>
  28722. * <file name="protractor.js" type="protractor">
  28723. * var model = element(by.binding('user.name'));
  28724. * var input = element(by.model('user.name'));
  28725. * var other = element(by.model('user.data'));
  28726. *
  28727. * it('should allow custom events', function() {
  28728. * input.sendKeys(' hello');
  28729. * input.click();
  28730. * expect(model.getText()).toEqual('say');
  28731. * other.click();
  28732. * expect(model.getText()).toEqual('say hello');
  28733. * });
  28734. *
  28735. * it('should $rollbackViewValue when model changes', function() {
  28736. * input.sendKeys(' hello');
  28737. * expect(input.getAttribute('value')).toEqual('say hello');
  28738. * input.sendKeys(protractor.Key.ESCAPE);
  28739. * expect(input.getAttribute('value')).toEqual('say');
  28740. * other.click();
  28741. * expect(model.getText()).toEqual('say');
  28742. * });
  28743. * </file>
  28744. * </example>
  28745. *
  28746. * ### Debouncing updates
  28747. *
  28748. * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
  28749. * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  28750. *
  28751. * <example name="ngModelOptions-directive-debounce" module="optionsExample">
  28752. * <file name="index.html">
  28753. * <div ng-controller="ExampleController">
  28754. * <form name="userForm">
  28755. * Name:
  28756. * <input type="text" name="userName"
  28757. * ng-model="user.name"
  28758. * ng-model-options="{ debounce: 1000 }" />
  28759. * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  28760. * </form>
  28761. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  28762. * </div>
  28763. * </file>
  28764. * <file name="app.js">
  28765. * angular.module('optionsExample', [])
  28766. * .controller('ExampleController', ['$scope', function($scope) {
  28767. * $scope.user = { name: 'say' };
  28768. * }]);
  28769. * </file>
  28770. * </example>
  28771. *
  28772. * ### Default events, extra triggers, and catch-all debounce values
  28773. *
  28774. * This example shows the relationship between "default" update events and
  28775. * additional `updateOn` triggers.
  28776. *
  28777. * `default` events are those that are bound to the control, and when fired, update the `$viewValue`
  28778. * via {@link ngModel.NgModelController#$setViewValue $setViewValue}. Every event that is not listed
  28779. * in `updateOn` is considered a "default" event, since different control types have different
  28780. * default events.
  28781. *
  28782. * The control in this example updates by "default", "click", and "blur", with different `debounce`
  28783. * values. You can see that "click" doesn't have an individual `debounce` value -
  28784. * therefore it uses the `*` debounce value.
  28785. *
  28786. * There is also a button that calls {@link ngModel.NgModelController#$setViewValue $setViewValue}
  28787. * directly with a "custom" event. Since "custom" is not defined in the `updateOn` list,
  28788. * it is considered a "default" event and will update the
  28789. * control if "default" is defined in `updateOn`, and will receive the "default" debounce value.
  28790. * Note that this is just to illustrate how custom controls would possibly call `$setViewValue`.
  28791. *
  28792. * You can change the `updateOn` and `debounce` configuration to test different scenarios. This
  28793. * is done with {@link ngModel.NgModelController#$overrideModelOptions $overrideModelOptions}.
  28794. *
  28795. <example name="ngModelOptions-advanced" module="optionsExample">
  28796. <file name="index.html">
  28797. <model-update-demo></model-update-demo>
  28798. </file>
  28799. <file name="app.js">
  28800. angular.module('optionsExample', [])
  28801. .component('modelUpdateDemo', {
  28802. templateUrl: 'template.html',
  28803. controller: function() {
  28804. this.name = 'Chinua';
  28805. this.options = {
  28806. updateOn: 'default blur click',
  28807. debounce: {
  28808. default: 2000,
  28809. blur: 0,
  28810. '*': 1000
  28811. }
  28812. };
  28813. this.updateEvents = function() {
  28814. var eventList = this.options.updateOn.split(' ');
  28815. eventList.push('*');
  28816. var events = {};
  28817. for (var i = 0; i < eventList.length; i++) {
  28818. events[eventList[i]] = this.options.debounce[eventList[i]];
  28819. }
  28820. this.events = events;
  28821. };
  28822. this.updateOptions = function() {
  28823. var options = angular.extend(this.options, {
  28824. updateOn: Object.keys(this.events).join(' ').replace('*', ''),
  28825. debounce: this.events
  28826. });
  28827. this.form.input.$overrideModelOptions(options);
  28828. };
  28829. // Initialize the event form
  28830. this.updateEvents();
  28831. }
  28832. });
  28833. </file>
  28834. <file name="template.html">
  28835. <form name="$ctrl.form">
  28836. Input: <input type="text" name="input" ng-model="$ctrl.name" ng-model-options="$ctrl.options" />
  28837. </form>
  28838. Model: <tt>{{$ctrl.name}}</tt>
  28839. <hr>
  28840. <button ng-click="$ctrl.form.input.$setViewValue('some value', 'custom')">Trigger setViewValue with 'some value' and 'custom' event</button>
  28841. <hr>
  28842. <form ng-submit="$ctrl.updateOptions()">
  28843. <b>updateOn</b><br>
  28844. <input type="text" ng-model="$ctrl.options.updateOn" ng-change="$ctrl.updateEvents()" ng-model-options="{debounce: 500}">
  28845. <table>
  28846. <tr>
  28847. <th>Option</th>
  28848. <th>Debounce value</th>
  28849. </tr>
  28850. <tr ng-repeat="(key, value) in $ctrl.events">
  28851. <td>{{key}}</td>
  28852. <td><input type="number" ng-model="$ctrl.events[key]" /></td>
  28853. </tr>
  28854. </table>
  28855. <br>
  28856. <input type="submit" value="Update options">
  28857. </form>
  28858. </file>
  28859. </example>
  28860. *
  28861. *
  28862. * ## Model updates and validation
  28863. *
  28864. * The default behaviour in `ngModel` is that the model value is set to `undefined` when the
  28865. * validation determines that the value is invalid. By setting the `allowInvalid` property to true,
  28866. * the model will still be updated even if the value is invalid.
  28867. *
  28868. *
  28869. * ## Connecting to the scope
  28870. *
  28871. * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
  28872. * on the scope refers to a "getter/setter" function rather than the value itself.
  28873. *
  28874. * The following example shows how to bind to getter/setters:
  28875. *
  28876. * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  28877. * <file name="index.html">
  28878. * <div ng-controller="ExampleController">
  28879. * <form name="userForm">
  28880. * <label>
  28881. * Name:
  28882. * <input type="text" name="userName"
  28883. * ng-model="user.name"
  28884. * ng-model-options="{ getterSetter: true }" />
  28885. * </label>
  28886. * </form>
  28887. * <pre>user.name = <span ng-bind="user.name()"></span></pre>
  28888. * </div>
  28889. * </file>
  28890. * <file name="app.js">
  28891. * angular.module('getterSetterExample', [])
  28892. * .controller('ExampleController', ['$scope', function($scope) {
  28893. * var _name = 'Brian';
  28894. * $scope.user = {
  28895. * name: function(newName) {
  28896. * return angular.isDefined(newName) ? (_name = newName) : _name;
  28897. * }
  28898. * };
  28899. * }]);
  28900. * </file>
  28901. * </example>
  28902. *
  28903. *
  28904. * ## Programmatically changing options
  28905. *
  28906. * The `ngModelOptions` expression is only evaluated once when the directive is linked; it is not
  28907. * watched for changes. However, it is possible to override the options on a single
  28908. * {@link ngModel.NgModelController} instance with
  28909. * {@link ngModel.NgModelController#$overrideModelOptions `NgModelController#$overrideModelOptions()`}.
  28910. * See also the example for
  28911. * {@link ngModelOptions#default-events-extra-triggers-and-catch-all-debounce-values
  28912. * Default events, extra triggers, and catch-all debounce values}.
  28913. *
  28914. *
  28915. * ## Specifying timezones
  28916. *
  28917. * You can specify the timezone that date/time input directives expect by providing its name in the
  28918. * `timezone` property.
  28919. *
  28920. *
  28921. * ## Formatting the value of `time` and `datetime-local`
  28922. *
  28923. * With the options `timeSecondsFormat` and `timeStripZeroSeconds` it is possible to adjust the value
  28924. * that is displayed in the control. Note that browsers may apply their own formatting
  28925. * in the user interface.
  28926. *
  28927. <example name="ngModelOptions-time-format" module="timeExample">
  28928. <file name="index.html">
  28929. <time-example></time-example>
  28930. </file>
  28931. <file name="script.js">
  28932. angular.module('timeExample', [])
  28933. .component('timeExample', {
  28934. templateUrl: 'timeExample.html',
  28935. controller: function() {
  28936. this.time = new Date(1970, 0, 1, 14, 57, 0);
  28937. this.options = {
  28938. timeSecondsFormat: 'ss',
  28939. timeStripZeroSeconds: true
  28940. };
  28941. this.optionChange = function() {
  28942. this.timeForm.timeFormatted.$overrideModelOptions(this.options);
  28943. this.time = new Date(this.time);
  28944. };
  28945. }
  28946. });
  28947. </file>
  28948. <file name="timeExample.html">
  28949. <form name="$ctrl.timeForm">
  28950. <strong>Default</strong>:
  28951. <input type="time" ng-model="$ctrl.time" step="any" /><br>
  28952. <strong>With options</strong>:
  28953. <input type="time" name="timeFormatted" ng-model="$ctrl.time" step="any" ng-model-options="$ctrl.options" />
  28954. <br>
  28955. Options:<br>
  28956. <code>timeSecondsFormat</code>:
  28957. <input
  28958. type="text"
  28959. ng-model="$ctrl.options.timeSecondsFormat"
  28960. ng-change="$ctrl.optionChange()">
  28961. <br>
  28962. <code>timeStripZeroSeconds</code>:
  28963. <input
  28964. type="checkbox"
  28965. ng-model="$ctrl.options.timeStripZeroSeconds"
  28966. ng-change="$ctrl.optionChange()">
  28967. </form>
  28968. </file>
  28969. * </example>
  28970. *
  28971. * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and
  28972. * and its descendents.
  28973. *
  28974. * **General options**:
  28975. *
  28976. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  28977. * events using an space delimited list. There is a special event called `default` that
  28978. * matches the default events belonging to the control. These are the events that are bound to
  28979. * the control, and when fired, update the `$viewValue` via `$setViewValue`.
  28980. *
  28981. * `ngModelOptions` considers every event that is not listed in `updateOn` a "default" event,
  28982. * since different control types use different default events.
  28983. *
  28984. * See also the section {@link ngModelOptions#triggering-and-debouncing-model-updates
  28985. * Triggering and debouncing model updates}.
  28986. *
  28987. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  28988. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  28989. * custom value for each event. For example:
  28990. * ```
  28991. * ng-model-options="{
  28992. * updateOn: 'default blur',
  28993. * debounce: { 'default': 500, 'blur': 0 }
  28994. * }"
  28995. * ```
  28996. * You can use the `*` key to specify a debounce value that applies to all events that are not
  28997. * specifically listed. In the following example, `mouseup` would have a debounce delay of 1000:
  28998. * ```
  28999. * ng-model-options="{
  29000. * updateOn: 'default blur mouseup',
  29001. * debounce: { 'default': 500, 'blur': 0, '*': 1000 }
  29002. * }"
  29003. * ```
  29004. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  29005. * not validate correctly instead of the default behavior of setting the model to undefined.
  29006. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  29007. * `ngModel` as getters/setters.
  29008. *
  29009. *
  29010. * **Input-type specific options**:
  29011. *
  29012. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  29013. * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the
  29014. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  29015. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  29016. * If not specified, the timezone of the browser will be used.
  29017. * Note that changing the timezone will have no effect on the current date, and is only applied after
  29018. * the next input / model change.
  29019. *
  29020. * - `timeSecondsFormat`: Defines if the `time` and `datetime-local` types should show seconds and
  29021. * milliseconds. The option follows the format string of {@link date date filter}.
  29022. * By default, the options is `undefined` which is equal to `'ss.sss'` (seconds and milliseconds).
  29023. * The other options are `'ss'` (strips milliseconds), and `''` (empty string), which strips both
  29024. * seconds and milliseconds.
  29025. * Note that browsers that support `time` and `datetime-local` require the hour and minutes
  29026. * part of the time string, and may show the value differently in the user interface.
  29027. * {@link ngModelOptions#formatting-the-value-of-time-and-datetime-local- See the example}.
  29028. *
  29029. * - `timeStripZeroSeconds`: Defines if the `time` and `datetime-local` types should strip the
  29030. * seconds and milliseconds from the formatted value if they are zero. This option is applied
  29031. * after `timeSecondsFormat`.
  29032. * This option can be used to make the formatting consistent over different browsers, as some
  29033. * browsers with support for `time` will natively hide the milliseconds and
  29034. * seconds if they are zero, but others won't, and browsers that don't implement these input
  29035. * types will always show the full string.
  29036. * {@link ngModelOptions#formatting-the-value-of-time-and-datetime-local- See the example}.
  29037. *
  29038. */
  29039. var ngModelOptionsDirective = function() {
  29040. NgModelOptionsController.$inject = ['$attrs', '$scope'];
  29041. function NgModelOptionsController($attrs, $scope) {
  29042. this.$$attrs = $attrs;
  29043. this.$$scope = $scope;
  29044. }
  29045. NgModelOptionsController.prototype = {
  29046. $onInit: function() {
  29047. var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions;
  29048. var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions);
  29049. this.$options = parentOptions.createChild(modelOptionsDefinition);
  29050. }
  29051. };
  29052. return {
  29053. restrict: 'A',
  29054. // ngModelOptions needs to run before ngModel and input directives
  29055. priority: 10,
  29056. require: {parentCtrl: '?^^ngModelOptions'},
  29057. bindToController: true,
  29058. controller: NgModelOptionsController
  29059. };
  29060. };
  29061. // shallow copy over values from `src` that are not already specified on `dst`
  29062. function defaults(dst, src) {
  29063. forEach(src, function(value, key) {
  29064. if (!isDefined(dst[key])) {
  29065. dst[key] = value;
  29066. }
  29067. });
  29068. }
  29069. /**
  29070. * @ngdoc directive
  29071. * @name ngNonBindable
  29072. * @restrict AC
  29073. * @priority 1000
  29074. * @element ANY
  29075. *
  29076. * @description
  29077. * The `ngNonBindable` directive tells AngularJS not to compile or bind the contents of the current
  29078. * DOM element, including directives on the element itself that have a lower priority than
  29079. * `ngNonBindable`. This is useful if the element contains what appears to be AngularJS directives
  29080. * and bindings but which should be ignored by AngularJS. This could be the case if you have a site
  29081. * that displays snippets of code, for instance.
  29082. *
  29083. * @example
  29084. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  29085. * but the one wrapped in `ngNonBindable` is left alone.
  29086. *
  29087. <example name="ng-non-bindable">
  29088. <file name="index.html">
  29089. <div>Normal: {{1 + 2}}</div>
  29090. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  29091. </file>
  29092. <file name="protractor.js" type="protractor">
  29093. it('should check ng-non-bindable', function() {
  29094. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  29095. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  29096. });
  29097. </file>
  29098. </example>
  29099. */
  29100. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  29101. /* exported ngOptionsDirective */
  29102. /* global jqLiteRemove */
  29103. var ngOptionsMinErr = minErr('ngOptions');
  29104. /**
  29105. * @ngdoc directive
  29106. * @name ngOptions
  29107. * @restrict A
  29108. *
  29109. * @description
  29110. *
  29111. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  29112. * elements for the `<select>` element using the array or object obtained by evaluating the
  29113. * `ngOptions` comprehension expression.
  29114. *
  29115. * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of
  29116. * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits:
  29117. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  29118. * comprehension expression
  29119. * - reduced memory consumption by not creating a new scope for each repeated instance
  29120. * - increased render speed by creating the options in a documentFragment instead of individually
  29121. *
  29122. * When an item in the `<select>` menu is selected, the array element or object property
  29123. * represented by the selected option will be bound to the model identified by the `ngModel`
  29124. * directive.
  29125. *
  29126. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  29127. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  29128. * option. See example below for demonstration.
  29129. *
  29130. * ## Complex Models (objects or collections)
  29131. *
  29132. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  29133. * binding the select to a model that is an object or a collection.
  29134. *
  29135. * One issue occurs if you want to preselect an option. For example, if you set
  29136. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  29137. * because the objects are not identical. So by default, you should always reference the item in your collection
  29138. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  29139. *
  29140. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  29141. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  29142. * collection items have an id property, you would `track by item.id`.
  29143. *
  29144. * A different issue with objects or collections is that ngModel won't detect if an object property or
  29145. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  29146. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  29147. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  29148. * has not changed identity, but only a property on the object or an item in the collection changes.
  29149. *
  29150. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  29151. * if the model is an array). This means that changing a property deeper than the first level inside the
  29152. * object/collection will not trigger a re-rendering.
  29153. *
  29154. * ## `select` **`as`**
  29155. *
  29156. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  29157. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  29158. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  29159. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  29160. *
  29161. *
  29162. * ### `select` **`as`** and **`track by`**
  29163. *
  29164. * <div class="alert alert-warning">
  29165. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  29166. * </div>
  29167. *
  29168. * Given this array of items on the $scope:
  29169. *
  29170. * ```js
  29171. * $scope.items = [{
  29172. * id: 1,
  29173. * label: 'aLabel',
  29174. * subItem: { name: 'aSubItem' }
  29175. * }, {
  29176. * id: 2,
  29177. * label: 'bLabel',
  29178. * subItem: { name: 'bSubItem' }
  29179. * }];
  29180. * ```
  29181. *
  29182. * This will work:
  29183. *
  29184. * ```html
  29185. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  29186. * ```
  29187. * ```js
  29188. * $scope.selected = $scope.items[0];
  29189. * ```
  29190. *
  29191. * but this will not work:
  29192. *
  29193. * ```html
  29194. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  29195. * ```
  29196. * ```js
  29197. * $scope.selected = $scope.items[0].subItem;
  29198. * ```
  29199. *
  29200. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  29201. * `items` array. Because the selected option has been set programmatically in the controller, the
  29202. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  29203. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  29204. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  29205. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  29206. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  29207. *
  29208. *
  29209. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  29210. * @param {comprehension_expression} ngOptions in one of the following forms:
  29211. *
  29212. * * for array data sources:
  29213. * * `label` **`for`** `value` **`in`** `array`
  29214. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  29215. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  29216. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  29217. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  29218. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  29219. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  29220. * (for including a filter with `track by`)
  29221. * * for object data sources:
  29222. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  29223. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  29224. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  29225. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  29226. * * `select` **`as`** `label` **`group by`** `group`
  29227. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  29228. * * `select` **`as`** `label` **`disable when`** `disable`
  29229. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  29230. *
  29231. * Where:
  29232. *
  29233. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  29234. * * `value`: local variable which will refer to each item in the `array` or each property value
  29235. * of `object` during iteration.
  29236. * * `key`: local variable which will refer to a property name in `object` during iteration.
  29237. * * `label`: The result of this expression will be the label for `<option>` element. The
  29238. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  29239. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  29240. * element. If not specified, `select` expression will default to `value`.
  29241. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  29242. * DOM element.
  29243. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  29244. * element. Return `true` to disable.
  29245. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  29246. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  29247. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  29248. * even when the options are recreated (e.g. reloaded from the server).
  29249. * @param {string=} name Property name of the form under which the control is published.
  29250. * @param {string=} required The control is considered valid only if value is entered.
  29251. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  29252. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  29253. * `required` when you want to data-bind to the `required` attribute.
  29254. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  29255. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  29256. *
  29257. * @example
  29258. <example module="selectExample" name="select">
  29259. <file name="index.html">
  29260. <script>
  29261. angular.module('selectExample', [])
  29262. .controller('ExampleController', ['$scope', function($scope) {
  29263. $scope.colors = [
  29264. {name:'black', shade:'dark'},
  29265. {name:'white', shade:'light', notAnOption: true},
  29266. {name:'red', shade:'dark'},
  29267. {name:'blue', shade:'dark', notAnOption: true},
  29268. {name:'yellow', shade:'light', notAnOption: false}
  29269. ];
  29270. $scope.myColor = $scope.colors[2]; // red
  29271. }]);
  29272. </script>
  29273. <div ng-controller="ExampleController">
  29274. <ul>
  29275. <li ng-repeat="color in colors">
  29276. <label>Name: <input ng-model="color.name"></label>
  29277. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  29278. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  29279. </li>
  29280. <li>
  29281. <button ng-click="colors.push({})">add</button>
  29282. </li>
  29283. </ul>
  29284. <hr/>
  29285. <label>Color (null not allowed):
  29286. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  29287. </label><br/>
  29288. <label>Color (null allowed):
  29289. <span class="nullable">
  29290. <select ng-model="myColor" ng-options="color.name for color in colors">
  29291. <option value="">-- choose color --</option>
  29292. </select>
  29293. </span></label><br/>
  29294. <label>Color grouped by shade:
  29295. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  29296. </select>
  29297. </label><br/>
  29298. <label>Color grouped by shade, with some disabled:
  29299. <select ng-model="myColor"
  29300. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  29301. </select>
  29302. </label><br/>
  29303. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  29304. <br/>
  29305. <hr/>
  29306. Currently selected: {{ {selected_color:myColor} }}
  29307. <div style="border:solid 1px black; height:20px"
  29308. ng-style="{'background-color':myColor.name}">
  29309. </div>
  29310. </div>
  29311. </file>
  29312. <file name="protractor.js" type="protractor">
  29313. it('should check ng-options', function() {
  29314. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  29315. element.all(by.model('myColor')).first().click();
  29316. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  29317. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  29318. element(by.css('.nullable select[ng-model="myColor"]')).click();
  29319. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  29320. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  29321. });
  29322. </file>
  29323. </example>
  29324. */
  29325. /* eslint-disable max-len */
  29326. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999
  29327. 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]+?))?$/;
  29328. // 1: value expression (valueFn)
  29329. // 2: label expression (displayFn)
  29330. // 3: group by expression (groupByFn)
  29331. // 4: disable when expression (disableWhenFn)
  29332. // 5: array item variable name
  29333. // 6: object item key variable name
  29334. // 7: object item value variable name
  29335. // 8: collection expression
  29336. // 9: track by expression
  29337. /* eslint-enable */
  29338. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  29339. function parseOptionsExpression(optionsExp, selectElement, scope) {
  29340. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  29341. if (!(match)) {
  29342. throw ngOptionsMinErr('iexp',
  29343. 'Expected expression in form of ' +
  29344. '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
  29345. ' but got \'{0}\'. Element: {1}',
  29346. optionsExp, startingTag(selectElement));
  29347. }
  29348. // Extract the parts from the ngOptions expression
  29349. // The variable name for the value of the item in the collection
  29350. var valueName = match[5] || match[7];
  29351. // The variable name for the key of the item in the collection
  29352. var keyName = match[6];
  29353. // An expression that generates the viewValue for an option if there is a label expression
  29354. var selectAs = / as /.test(match[0]) && match[1];
  29355. // An expression that is used to track the id of each object in the options collection
  29356. var trackBy = match[9];
  29357. // An expression that generates the viewValue for an option if there is no label expression
  29358. var valueFn = $parse(match[2] ? match[1] : valueName);
  29359. var selectAsFn = selectAs && $parse(selectAs);
  29360. var viewValueFn = selectAsFn || valueFn;
  29361. var trackByFn = trackBy && $parse(trackBy);
  29362. // Get the value by which we are going to track the option
  29363. // if we have a trackFn then use that (passing scope and locals)
  29364. // otherwise just hash the given viewValue
  29365. var getTrackByValueFn = trackBy ?
  29366. function(value, locals) { return trackByFn(scope, locals); } :
  29367. function getHashOfValue(value) { return hashKey(value); };
  29368. var getTrackByValue = function(value, key) {
  29369. return getTrackByValueFn(value, getLocals(value, key));
  29370. };
  29371. var displayFn = $parse(match[2] || match[1]);
  29372. var groupByFn = $parse(match[3] || '');
  29373. var disableWhenFn = $parse(match[4] || '');
  29374. var valuesFn = $parse(match[8]);
  29375. var locals = {};
  29376. var getLocals = keyName ? function(value, key) {
  29377. locals[keyName] = key;
  29378. locals[valueName] = value;
  29379. return locals;
  29380. } : function(value) {
  29381. locals[valueName] = value;
  29382. return locals;
  29383. };
  29384. function Option(selectValue, viewValue, label, group, disabled) {
  29385. this.selectValue = selectValue;
  29386. this.viewValue = viewValue;
  29387. this.label = label;
  29388. this.group = group;
  29389. this.disabled = disabled;
  29390. }
  29391. function getOptionValuesKeys(optionValues) {
  29392. var optionValuesKeys;
  29393. if (!keyName && isArrayLike(optionValues)) {
  29394. optionValuesKeys = optionValues;
  29395. } else {
  29396. // if object, extract keys, in enumeration order, unsorted
  29397. optionValuesKeys = [];
  29398. for (var itemKey in optionValues) {
  29399. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  29400. optionValuesKeys.push(itemKey);
  29401. }
  29402. }
  29403. }
  29404. return optionValuesKeys;
  29405. }
  29406. return {
  29407. trackBy: trackBy,
  29408. getTrackByValue: getTrackByValue,
  29409. getWatchables: $parse(valuesFn, function(optionValues) {
  29410. // Create a collection of things that we would like to watch (watchedArray)
  29411. // so that they can all be watched using a single $watchCollection
  29412. // that only runs the handler once if anything changes
  29413. var watchedArray = [];
  29414. optionValues = optionValues || [];
  29415. var optionValuesKeys = getOptionValuesKeys(optionValues);
  29416. var optionValuesLength = optionValuesKeys.length;
  29417. for (var index = 0; index < optionValuesLength; index++) {
  29418. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  29419. var value = optionValues[key];
  29420. var locals = getLocals(value, key);
  29421. var selectValue = getTrackByValueFn(value, locals);
  29422. watchedArray.push(selectValue);
  29423. // Only need to watch the displayFn if there is a specific label expression
  29424. if (match[2] || match[1]) {
  29425. var label = displayFn(scope, locals);
  29426. watchedArray.push(label);
  29427. }
  29428. // Only need to watch the disableWhenFn if there is a specific disable expression
  29429. if (match[4]) {
  29430. var disableWhen = disableWhenFn(scope, locals);
  29431. watchedArray.push(disableWhen);
  29432. }
  29433. }
  29434. return watchedArray;
  29435. }),
  29436. getOptions: function() {
  29437. var optionItems = [];
  29438. var selectValueMap = {};
  29439. // The option values were already computed in the `getWatchables` fn,
  29440. // which must have been called to trigger `getOptions`
  29441. var optionValues = valuesFn(scope) || [];
  29442. var optionValuesKeys = getOptionValuesKeys(optionValues);
  29443. var optionValuesLength = optionValuesKeys.length;
  29444. for (var index = 0; index < optionValuesLength; index++) {
  29445. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  29446. var value = optionValues[key];
  29447. var locals = getLocals(value, key);
  29448. var viewValue = viewValueFn(scope, locals);
  29449. var selectValue = getTrackByValueFn(viewValue, locals);
  29450. var label = displayFn(scope, locals);
  29451. var group = groupByFn(scope, locals);
  29452. var disabled = disableWhenFn(scope, locals);
  29453. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  29454. optionItems.push(optionItem);
  29455. selectValueMap[selectValue] = optionItem;
  29456. }
  29457. return {
  29458. items: optionItems,
  29459. selectValueMap: selectValueMap,
  29460. getOptionFromViewValue: function(value) {
  29461. return selectValueMap[getTrackByValue(value)];
  29462. },
  29463. getViewValueFromOption: function(option) {
  29464. // If the viewValue could be an object that may be mutated by the application,
  29465. // we need to make a copy and not return the reference to the value on the option.
  29466. return trackBy ? copy(option.viewValue) : option.viewValue;
  29467. }
  29468. };
  29469. }
  29470. };
  29471. }
  29472. // Support: IE 9 only
  29473. // We can't just jqLite('<option>') since jqLite is not smart enough
  29474. // to create it in <select> and IE barfs otherwise.
  29475. var optionTemplate = window.document.createElement('option'),
  29476. optGroupTemplate = window.document.createElement('optgroup');
  29477. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  29478. var selectCtrl = ctrls[0];
  29479. var ngModelCtrl = ctrls[1];
  29480. var multiple = attr.multiple;
  29481. // The emptyOption allows the application developer to provide their own custom "empty"
  29482. // option when the viewValue does not match any of the option values.
  29483. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  29484. if (children[i].value === '') {
  29485. selectCtrl.hasEmptyOption = true;
  29486. selectCtrl.emptyOption = children.eq(i);
  29487. break;
  29488. }
  29489. }
  29490. // The empty option will be compiled and rendered before we first generate the options
  29491. selectElement.empty();
  29492. var providedEmptyOption = !!selectCtrl.emptyOption;
  29493. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  29494. unknownOption.val('?');
  29495. var options;
  29496. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  29497. // This stores the newly created options before they are appended to the select.
  29498. // Since the contents are removed from the fragment when it is appended,
  29499. // we only need to create it once.
  29500. var listFragment = $document[0].createDocumentFragment();
  29501. // Overwrite the implementation. ngOptions doesn't use hashes
  29502. selectCtrl.generateUnknownOptionValue = function(val) {
  29503. return '?';
  29504. };
  29505. // Update the controller methods for multiple selectable options
  29506. if (!multiple) {
  29507. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  29508. // The options might not be defined yet when ngModel tries to render
  29509. if (!options) return;
  29510. var selectedOption = selectElement[0].options[selectElement[0].selectedIndex];
  29511. var option = options.getOptionFromViewValue(value);
  29512. // Make sure to remove the selected attribute from the previously selected option
  29513. // Otherwise, screen readers might get confused
  29514. if (selectedOption) selectedOption.removeAttribute('selected');
  29515. if (option) {
  29516. // Don't update the option when it is already selected.
  29517. // For example, the browser will select the first option by default. In that case,
  29518. // most properties are set automatically - except the `selected` attribute, which we
  29519. // set always
  29520. if (selectElement[0].value !== option.selectValue) {
  29521. selectCtrl.removeUnknownOption();
  29522. selectElement[0].value = option.selectValue;
  29523. option.element.selected = true;
  29524. }
  29525. option.element.setAttribute('selected', 'selected');
  29526. } else {
  29527. selectCtrl.selectUnknownOrEmptyOption(value);
  29528. }
  29529. };
  29530. selectCtrl.readValue = function readNgOptionsValue() {
  29531. var selectedOption = options.selectValueMap[selectElement.val()];
  29532. if (selectedOption && !selectedOption.disabled) {
  29533. selectCtrl.unselectEmptyOption();
  29534. selectCtrl.removeUnknownOption();
  29535. return options.getViewValueFromOption(selectedOption);
  29536. }
  29537. return null;
  29538. };
  29539. // If we are using `track by` then we must watch the tracked value on the model
  29540. // since ngModel only watches for object identity change
  29541. // FIXME: When a user selects an option, this watch will fire needlessly
  29542. if (ngOptions.trackBy) {
  29543. scope.$watch(
  29544. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  29545. function() { ngModelCtrl.$render(); }
  29546. );
  29547. }
  29548. } else {
  29549. selectCtrl.writeValue = function writeNgOptionsMultiple(values) {
  29550. // The options might not be defined yet when ngModel tries to render
  29551. if (!options) return;
  29552. // Only set `<option>.selected` if necessary, in order to prevent some browsers from
  29553. // scrolling to `<option>` elements that are outside the `<select>` element's viewport.
  29554. var selectedOptions = values && values.map(getAndUpdateSelectedOption) || [];
  29555. options.items.forEach(function(option) {
  29556. if (option.element.selected && !includes(selectedOptions, option)) {
  29557. option.element.selected = false;
  29558. }
  29559. });
  29560. };
  29561. selectCtrl.readValue = function readNgOptionsMultiple() {
  29562. var selectedValues = selectElement.val() || [],
  29563. selections = [];
  29564. forEach(selectedValues, function(value) {
  29565. var option = options.selectValueMap[value];
  29566. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  29567. });
  29568. return selections;
  29569. };
  29570. // If we are using `track by` then we must watch these tracked values on the model
  29571. // since ngModel only watches for object identity change
  29572. if (ngOptions.trackBy) {
  29573. scope.$watchCollection(function() {
  29574. if (isArray(ngModelCtrl.$viewValue)) {
  29575. return ngModelCtrl.$viewValue.map(function(value) {
  29576. return ngOptions.getTrackByValue(value);
  29577. });
  29578. }
  29579. }, function() {
  29580. ngModelCtrl.$render();
  29581. });
  29582. }
  29583. }
  29584. if (providedEmptyOption) {
  29585. // compile the element since there might be bindings in it
  29586. $compile(selectCtrl.emptyOption)(scope);
  29587. selectElement.prepend(selectCtrl.emptyOption);
  29588. if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) {
  29589. // This means the empty option has currently no actual DOM node, probably because
  29590. // it has been modified by a transclusion directive.
  29591. selectCtrl.hasEmptyOption = false;
  29592. // Redefine the registerOption function, which will catch
  29593. // options that are added by ngIf etc. (rendering of the node is async because of
  29594. // lazy transclusion)
  29595. selectCtrl.registerOption = function(optionScope, optionEl) {
  29596. if (optionEl.val() === '') {
  29597. selectCtrl.hasEmptyOption = true;
  29598. selectCtrl.emptyOption = optionEl;
  29599. selectCtrl.emptyOption.removeClass('ng-scope');
  29600. // This ensures the new empty option is selected if previously no option was selected
  29601. ngModelCtrl.$render();
  29602. optionEl.on('$destroy', function() {
  29603. var needsRerender = selectCtrl.$isEmptyOptionSelected();
  29604. selectCtrl.hasEmptyOption = false;
  29605. selectCtrl.emptyOption = undefined;
  29606. if (needsRerender) ngModelCtrl.$render();
  29607. });
  29608. }
  29609. };
  29610. } else {
  29611. // remove the class, which is added automatically because we recompile the element and it
  29612. // becomes the compilation root
  29613. selectCtrl.emptyOption.removeClass('ng-scope');
  29614. }
  29615. }
  29616. // We will re-render the option elements if the option values or labels change
  29617. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  29618. // ------------------------------------------------------------------ //
  29619. function addOptionElement(option, parent) {
  29620. var optionElement = optionTemplate.cloneNode(false);
  29621. parent.appendChild(optionElement);
  29622. updateOptionElement(option, optionElement);
  29623. }
  29624. function getAndUpdateSelectedOption(viewValue) {
  29625. var option = options.getOptionFromViewValue(viewValue);
  29626. var element = option && option.element;
  29627. if (element && !element.selected) element.selected = true;
  29628. return option;
  29629. }
  29630. function updateOptionElement(option, element) {
  29631. option.element = element;
  29632. element.disabled = option.disabled;
  29633. // Support: IE 11 only, Edge 12-13 only
  29634. // NOTE: The label must be set before the value, otherwise IE 11 & Edge create unresponsive
  29635. // selects in certain circumstances when multiple selects are next to each other and display
  29636. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  29637. // See https://github.com/angular/angular.js/issues/11314 for more info.
  29638. // This is unfortunately untestable with unit / e2e tests
  29639. if (option.label !== element.label) {
  29640. element.label = option.label;
  29641. element.textContent = option.label;
  29642. }
  29643. element.value = option.selectValue;
  29644. }
  29645. function updateOptions() {
  29646. var previousValue = options && selectCtrl.readValue();
  29647. // We must remove all current options, but cannot simply set innerHTML = null
  29648. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  29649. // must preserve.
  29650. // Instead, iterate over the current option elements and remove them or their optgroup
  29651. // parents
  29652. if (options) {
  29653. for (var i = options.items.length - 1; i >= 0; i--) {
  29654. var option = options.items[i];
  29655. if (isDefined(option.group)) {
  29656. jqLiteRemove(option.element.parentNode);
  29657. } else {
  29658. jqLiteRemove(option.element);
  29659. }
  29660. }
  29661. }
  29662. options = ngOptions.getOptions();
  29663. var groupElementMap = {};
  29664. options.items.forEach(function addOption(option) {
  29665. var groupElement;
  29666. if (isDefined(option.group)) {
  29667. // This option is to live in a group
  29668. // See if we have already created this group
  29669. groupElement = groupElementMap[option.group];
  29670. if (!groupElement) {
  29671. groupElement = optGroupTemplate.cloneNode(false);
  29672. listFragment.appendChild(groupElement);
  29673. // Update the label on the group element
  29674. // "null" is special cased because of Safari
  29675. groupElement.label = option.group === null ? 'null' : option.group;
  29676. // Store it for use later
  29677. groupElementMap[option.group] = groupElement;
  29678. }
  29679. addOptionElement(option, groupElement);
  29680. } else {
  29681. // This option is not in a group
  29682. addOptionElement(option, listFragment);
  29683. }
  29684. });
  29685. selectElement[0].appendChild(listFragment);
  29686. ngModelCtrl.$render();
  29687. // Check to see if the value has changed due to the update to the options
  29688. if (!ngModelCtrl.$isEmpty(previousValue)) {
  29689. var nextValue = selectCtrl.readValue();
  29690. var isNotPrimitive = ngOptions.trackBy || multiple;
  29691. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  29692. ngModelCtrl.$setViewValue(nextValue);
  29693. ngModelCtrl.$render();
  29694. }
  29695. }
  29696. }
  29697. }
  29698. return {
  29699. restrict: 'A',
  29700. terminal: true,
  29701. require: ['select', 'ngModel'],
  29702. link: {
  29703. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  29704. // Deactivate the SelectController.register method to prevent
  29705. // option directives from accidentally registering themselves
  29706. // (and unwanted $destroy handlers etc.)
  29707. ctrls[0].registerOption = noop;
  29708. },
  29709. post: ngOptionsPostLink
  29710. }
  29711. };
  29712. }];
  29713. /**
  29714. * @ngdoc directive
  29715. * @name ngPluralize
  29716. * @restrict EA
  29717. *
  29718. * @description
  29719. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  29720. * These rules are bundled with angular.js, but can be overridden
  29721. * (see {@link guide/i18n AngularJS i18n} dev guide). You configure ngPluralize directive
  29722. * by specifying the mappings between
  29723. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  29724. * and the strings to be displayed.
  29725. *
  29726. * ## Plural categories and explicit number rules
  29727. * There are two
  29728. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  29729. * in AngularJS's default en-US locale: "one" and "other".
  29730. *
  29731. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  29732. * any number that is not 1), an explicit number rule can only match one number. For example, the
  29733. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  29734. * and explicit number rules throughout the rest of this documentation.
  29735. *
  29736. * ## Configuring ngPluralize
  29737. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  29738. * You can also provide an optional attribute, `offset`.
  29739. *
  29740. * The value of the `count` attribute can be either a string or an {@link guide/expression
  29741. * AngularJS expression}; these are evaluated on the current scope for its bound value.
  29742. *
  29743. * The `when` attribute specifies the mappings between plural categories and the actual
  29744. * string to be displayed. The value of the attribute should be a JSON object.
  29745. *
  29746. * The following example shows how to configure ngPluralize:
  29747. *
  29748. * ```html
  29749. * <ng-pluralize count="personCount"
  29750. when="{'0': 'Nobody is viewing.',
  29751. * 'one': '1 person is viewing.',
  29752. * 'other': '{} people are viewing.'}">
  29753. * </ng-pluralize>
  29754. *```
  29755. *
  29756. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  29757. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  29758. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  29759. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  29760. * show "a dozen people are viewing".
  29761. *
  29762. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  29763. * into pluralized strings. In the previous example, AngularJS will replace `{}` with
  29764. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  29765. * for <span ng-non-bindable>{{numberExpression}}</span>.
  29766. *
  29767. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  29768. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  29769. *
  29770. * ## Configuring ngPluralize with offset
  29771. * The `offset` attribute allows further customization of pluralized text, which can result in
  29772. * a better user experience. For example, instead of the message "4 people are viewing this document",
  29773. * you might display "John, Kate and 2 others are viewing this document".
  29774. * The offset attribute allows you to offset a number by any desired value.
  29775. * Let's take a look at an example:
  29776. *
  29777. * ```html
  29778. * <ng-pluralize count="personCount" offset=2
  29779. * when="{'0': 'Nobody is viewing.',
  29780. * '1': '{{person1}} is viewing.',
  29781. * '2': '{{person1}} and {{person2}} are viewing.',
  29782. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  29783. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  29784. * </ng-pluralize>
  29785. * ```
  29786. *
  29787. * Notice that we are still using two plural categories(one, other), but we added
  29788. * three explicit number rules 0, 1 and 2.
  29789. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  29790. * When three people view the document, no explicit number rule is found, so
  29791. * an offset of 2 is taken off 3, and AngularJS uses 1 to decide the plural category.
  29792. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  29793. * is shown.
  29794. *
  29795. * Note that when you specify offsets, you must provide explicit number rules for
  29796. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  29797. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  29798. * plural categories "one" and "other".
  29799. *
  29800. * @param {string|expression} count The variable to be bound to.
  29801. * @param {string} when The mapping between plural category to its corresponding strings.
  29802. * @param {number=} offset Offset to deduct from the total number.
  29803. *
  29804. * @example
  29805. <example module="pluralizeExample" name="ng-pluralize">
  29806. <file name="index.html">
  29807. <script>
  29808. angular.module('pluralizeExample', [])
  29809. .controller('ExampleController', ['$scope', function($scope) {
  29810. $scope.person1 = 'Igor';
  29811. $scope.person2 = 'Misko';
  29812. $scope.personCount = 1;
  29813. }]);
  29814. </script>
  29815. <div ng-controller="ExampleController">
  29816. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  29817. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  29818. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  29819. <!--- Example with simple pluralization rules for en locale --->
  29820. Without Offset:
  29821. <ng-pluralize count="personCount"
  29822. when="{'0': 'Nobody is viewing.',
  29823. 'one': '1 person is viewing.',
  29824. 'other': '{} people are viewing.'}">
  29825. </ng-pluralize><br>
  29826. <!--- Example with offset --->
  29827. With Offset(2):
  29828. <ng-pluralize count="personCount" offset=2
  29829. when="{'0': 'Nobody is viewing.',
  29830. '1': '{{person1}} is viewing.',
  29831. '2': '{{person1}} and {{person2}} are viewing.',
  29832. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  29833. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  29834. </ng-pluralize>
  29835. </div>
  29836. </file>
  29837. <file name="protractor.js" type="protractor">
  29838. it('should show correct pluralized string', function() {
  29839. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  29840. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  29841. var countInput = element(by.model('personCount'));
  29842. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  29843. expect(withOffset.getText()).toEqual('Igor is viewing.');
  29844. countInput.clear();
  29845. countInput.sendKeys('0');
  29846. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  29847. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  29848. countInput.clear();
  29849. countInput.sendKeys('2');
  29850. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  29851. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  29852. countInput.clear();
  29853. countInput.sendKeys('3');
  29854. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  29855. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  29856. countInput.clear();
  29857. countInput.sendKeys('4');
  29858. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  29859. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  29860. });
  29861. it('should show data-bound names', function() {
  29862. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  29863. var personCount = element(by.model('personCount'));
  29864. var person1 = element(by.model('person1'));
  29865. var person2 = element(by.model('person2'));
  29866. personCount.clear();
  29867. personCount.sendKeys('4');
  29868. person1.clear();
  29869. person1.sendKeys('Di');
  29870. person2.clear();
  29871. person2.sendKeys('Vojta');
  29872. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  29873. });
  29874. </file>
  29875. </example>
  29876. */
  29877. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  29878. var BRACE = /{}/g,
  29879. IS_WHEN = /^when(Minus)?(.+)$/;
  29880. return {
  29881. link: function(scope, element, attr) {
  29882. var numberExp = attr.count,
  29883. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  29884. offset = attr.offset || 0,
  29885. whens = scope.$eval(whenExp) || {},
  29886. whensExpFns = {},
  29887. startSymbol = $interpolate.startSymbol(),
  29888. endSymbol = $interpolate.endSymbol(),
  29889. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  29890. watchRemover = angular.noop,
  29891. lastCount;
  29892. forEach(attr, function(expression, attributeName) {
  29893. var tmpMatch = IS_WHEN.exec(attributeName);
  29894. if (tmpMatch) {
  29895. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  29896. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  29897. }
  29898. });
  29899. forEach(whens, function(expression, key) {
  29900. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  29901. });
  29902. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  29903. var count = parseFloat(newVal);
  29904. var countIsNaN = isNumberNaN(count);
  29905. if (!countIsNaN && !(count in whens)) {
  29906. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  29907. // Otherwise, check it against pluralization rules in $locale service.
  29908. count = $locale.pluralCat(count - offset);
  29909. }
  29910. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  29911. // In JS `NaN !== NaN`, so we have to explicitly check.
  29912. if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
  29913. watchRemover();
  29914. var whenExpFn = whensExpFns[count];
  29915. if (isUndefined(whenExpFn)) {
  29916. if (newVal != null) {
  29917. $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
  29918. }
  29919. watchRemover = noop;
  29920. updateElementText();
  29921. } else {
  29922. watchRemover = scope.$watch(whenExpFn, updateElementText);
  29923. }
  29924. lastCount = count;
  29925. }
  29926. });
  29927. function updateElementText(newText) {
  29928. element.text(newText || '');
  29929. }
  29930. }
  29931. };
  29932. }];
  29933. /**
  29934. * @ngdoc directive
  29935. * @name ngRef
  29936. * @restrict A
  29937. *
  29938. * @description
  29939. * The `ngRef` attribute tells AngularJS to assign the controller of a component (or a directive)
  29940. * to the given property in the current scope. It is also possible to add the jqlite-wrapped DOM
  29941. * element to the scope.
  29942. *
  29943. * If the element with `ngRef` is destroyed `null` is assigned to the property.
  29944. *
  29945. * Note that if you want to assign from a child into the parent scope, you must initialize the
  29946. * target property on the parent scope, otherwise `ngRef` will assign on the child scope.
  29947. * This commonly happens when assigning elements or components wrapped in {@link ngIf} or
  29948. * {@link ngRepeat}. See the second example below.
  29949. *
  29950. *
  29951. * @element ANY
  29952. * @param {string} ngRef property name - A valid AngularJS expression identifier to which the
  29953. * controller or jqlite-wrapped DOM element will be bound.
  29954. * @param {string=} ngRefRead read value - The name of a directive (or component) on this element,
  29955. * or the special string `$element`. If a name is provided, `ngRef` will
  29956. * assign the matching controller. If `$element` is provided, the element
  29957. * itself is assigned (even if a controller is available).
  29958. *
  29959. *
  29960. * @example
  29961. * ### Simple toggle
  29962. * This example shows how the controller of the component toggle
  29963. * is reused in the template through the scope to use its logic.
  29964. * <example name="ng-ref-component" module="myApp">
  29965. * <file name="index.html">
  29966. * <my-toggle ng-ref="myToggle"></my-toggle>
  29967. * <button ng-click="myToggle.toggle()">Toggle</button>
  29968. * <div ng-show="myToggle.isOpen()">
  29969. * You are using a component in the same template to show it.
  29970. * </div>
  29971. * </file>
  29972. * <file name="index.js">
  29973. * angular.module('myApp', [])
  29974. * .component('myToggle', {
  29975. * controller: function ToggleController() {
  29976. * var opened = false;
  29977. * this.isOpen = function() { return opened; };
  29978. * this.toggle = function() { opened = !opened; };
  29979. * }
  29980. * });
  29981. * </file>
  29982. * <file name="protractor.js" type="protractor">
  29983. * it('should publish the toggle into the scope', function() {
  29984. * var toggle = element(by.buttonText('Toggle'));
  29985. * expect(toggle.evaluate('myToggle.isOpen()')).toEqual(false);
  29986. * toggle.click();
  29987. * expect(toggle.evaluate('myToggle.isOpen()')).toEqual(true);
  29988. * });
  29989. * </file>
  29990. * </example>
  29991. *
  29992. * @example
  29993. * ### ngRef inside scopes
  29994. * This example shows how `ngRef` works with child scopes. The `ngRepeat`-ed `myWrapper` components
  29995. * are assigned to the scope of `myRoot`, because the `toggles` property has been initialized.
  29996. * The repeated `myToggle` components are published to the child scopes created by `ngRepeat`.
  29997. * `ngIf` behaves similarly - the assignment of `myToggle` happens in the `ngIf` child scope,
  29998. * because the target property has not been initialized on the `myRoot` component controller.
  29999. *
  30000. * <example name="ng-ref-scopes" module="myApp">
  30001. * <file name="index.html">
  30002. * <my-root></my-root>
  30003. * </file>
  30004. * <file name="index.js">
  30005. * angular.module('myApp', [])
  30006. * .component('myRoot', {
  30007. * templateUrl: 'root.html',
  30008. * controller: function() {
  30009. * this.wrappers = []; // initialize the array so that the wrappers are assigned into the parent scope
  30010. * }
  30011. * })
  30012. * .component('myToggle', {
  30013. * template: '<strong>myToggle</strong><button ng-click="$ctrl.toggle()" ng-transclude></button>',
  30014. * transclude: true,
  30015. * controller: function ToggleController() {
  30016. * var opened = false;
  30017. * this.isOpen = function() { return opened; };
  30018. * this.toggle = function() { opened = !opened; };
  30019. * }
  30020. * })
  30021. * .component('myWrapper', {
  30022. * transclude: true,
  30023. * template: '<strong>myWrapper</strong>' +
  30024. * '<div>ngRepeatToggle.isOpen(): {{$ctrl.ngRepeatToggle.isOpen() | json}}</div>' +
  30025. * '<my-toggle ng-ref="$ctrl.ngRepeatToggle"><ng-transclude></ng-transclude></my-toggle>'
  30026. * });
  30027. * </file>
  30028. * <file name="root.html">
  30029. * <strong>myRoot</strong>
  30030. * <my-toggle ng-ref="$ctrl.outerToggle">Outer Toggle</my-toggle>
  30031. * <div>outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}</div>
  30032. * <div><em>wrappers assigned to root</em><br>
  30033. * <div ng-repeat="wrapper in $ctrl.wrappers">
  30034. * wrapper.ngRepeatToggle.isOpen(): {{wrapper.ngRepeatToggle.isOpen() | json}}
  30035. * </div>
  30036. *
  30037. * <ul>
  30038. * <li ng-repeat="(index, value) in [1,2,3]">
  30039. * <strong>ngRepeat</strong>
  30040. * <div>outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}</div>
  30041. * <my-wrapper ng-ref="$ctrl.wrappers[index]">ngRepeat Toggle {{$index + 1}}</my-wrapper>
  30042. * </li>
  30043. * </ul>
  30044. *
  30045. * <div>ngIfToggle.isOpen(): {{ngIfToggle.isOpen()}} // This is always undefined because it's
  30046. * assigned to the child scope created by ngIf.
  30047. * </div>
  30048. * <div ng-if="true">
  30049. <strong>ngIf</strong>
  30050. * <my-toggle ng-ref="ngIfToggle">ngIf Toggle</my-toggle>
  30051. * <div>ngIfToggle.isOpen(): {{ngIfToggle.isOpen() | json}}</div>
  30052. * <div>outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}</div>
  30053. * </div>
  30054. * </file>
  30055. * <file name="styles.css">
  30056. * ul {
  30057. * list-style: none;
  30058. * padding-left: 0;
  30059. * }
  30060. *
  30061. * li[ng-repeat] {
  30062. * background: lightgreen;
  30063. * padding: 8px;
  30064. * margin: 8px;
  30065. * }
  30066. *
  30067. * [ng-if] {
  30068. * background: lightgrey;
  30069. * padding: 8px;
  30070. * }
  30071. *
  30072. * my-root {
  30073. * background: lightgoldenrodyellow;
  30074. * padding: 8px;
  30075. * display: block;
  30076. * }
  30077. *
  30078. * my-wrapper {
  30079. * background: lightsalmon;
  30080. * padding: 8px;
  30081. * display: block;
  30082. * }
  30083. *
  30084. * my-toggle {
  30085. * background: lightblue;
  30086. * padding: 8px;
  30087. * display: block;
  30088. * }
  30089. * </file>
  30090. * <file name="protractor.js" type="protractor">
  30091. * var OuterToggle = function() {
  30092. * this.toggle = function() {
  30093. * element(by.buttonText('Outer Toggle')).click();
  30094. * };
  30095. * this.isOpen = function() {
  30096. * return element.all(by.binding('outerToggle.isOpen()')).first().getText();
  30097. * };
  30098. * };
  30099. * var NgRepeatToggle = function(i) {
  30100. * var parent = element.all(by.repeater('(index, value) in [1,2,3]')).get(i - 1);
  30101. * this.toggle = function() {
  30102. * element(by.buttonText('ngRepeat Toggle ' + i)).click();
  30103. * };
  30104. * this.isOpen = function() {
  30105. * return parent.element(by.binding('ngRepeatToggle.isOpen() | json')).getText();
  30106. * };
  30107. * this.isOuterOpen = function() {
  30108. * return parent.element(by.binding('outerToggle.isOpen() | json')).getText();
  30109. * };
  30110. * };
  30111. * var NgRepeatToggles = function() {
  30112. * var toggles = [1,2,3].map(function(i) { return new NgRepeatToggle(i); });
  30113. * this.forEach = function(fn) {
  30114. * toggles.forEach(fn);
  30115. * };
  30116. * this.isOuterOpen = function(i) {
  30117. * return toggles[i - 1].isOuterOpen();
  30118. * };
  30119. * };
  30120. * var NgIfToggle = function() {
  30121. * var parent = element(by.css('[ng-if]'));
  30122. * this.toggle = function() {
  30123. * element(by.buttonText('ngIf Toggle')).click();
  30124. * };
  30125. * this.isOpen = function() {
  30126. * return by.binding('ngIfToggle.isOpen() | json').getText();
  30127. * };
  30128. * this.isOuterOpen = function() {
  30129. * return parent.element(by.binding('outerToggle.isOpen() | json')).getText();
  30130. * };
  30131. * };
  30132. *
  30133. * it('should toggle the outer toggle', function() {
  30134. * var outerToggle = new OuterToggle();
  30135. * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): false');
  30136. * outerToggle.toggle();
  30137. * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): true');
  30138. * });
  30139. *
  30140. * it('should toggle all outer toggles', function() {
  30141. * var outerToggle = new OuterToggle();
  30142. * var repeatToggles = new NgRepeatToggles();
  30143. * var ifToggle = new NgIfToggle();
  30144. * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): false');
  30145. * expect(repeatToggles.isOuterOpen(1)).toEqual('outerToggle.isOpen(): false');
  30146. * expect(repeatToggles.isOuterOpen(2)).toEqual('outerToggle.isOpen(): false');
  30147. * expect(repeatToggles.isOuterOpen(3)).toEqual('outerToggle.isOpen(): false');
  30148. * expect(ifToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false');
  30149. * outerToggle.toggle();
  30150. * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): true');
  30151. * expect(repeatToggles.isOuterOpen(1)).toEqual('outerToggle.isOpen(): true');
  30152. * expect(repeatToggles.isOuterOpen(2)).toEqual('outerToggle.isOpen(): true');
  30153. * expect(repeatToggles.isOuterOpen(3)).toEqual('outerToggle.isOpen(): true');
  30154. * expect(ifToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): true');
  30155. * });
  30156. *
  30157. * it('should toggle each repeat iteration separately', function() {
  30158. * var repeatToggles = new NgRepeatToggles();
  30159. *
  30160. * repeatToggles.forEach(function(repeatToggle) {
  30161. * expect(repeatToggle.isOpen()).toEqual('ngRepeatToggle.isOpen(): false');
  30162. * expect(repeatToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false');
  30163. * repeatToggle.toggle();
  30164. * expect(repeatToggle.isOpen()).toEqual('ngRepeatToggle.isOpen(): true');
  30165. * expect(repeatToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false');
  30166. * });
  30167. * });
  30168. * </file>
  30169. * </example>
  30170. *
  30171. */
  30172. var ngRefMinErr = minErr('ngRef');
  30173. var ngRefDirective = ['$parse', function($parse) {
  30174. return {
  30175. priority: -1, // Needed for compatibility with element transclusion on the same element
  30176. restrict: 'A',
  30177. compile: function(tElement, tAttrs) {
  30178. // Get the expected controller name, converts <data-some-thing> into "someThing"
  30179. var controllerName = directiveNormalize(nodeName_(tElement));
  30180. // Get the expression for value binding
  30181. var getter = $parse(tAttrs.ngRef);
  30182. var setter = getter.assign || function() {
  30183. throw ngRefMinErr('nonassign', 'Expression in ngRef="{0}" is non-assignable!', tAttrs.ngRef);
  30184. };
  30185. return function(scope, element, attrs) {
  30186. var refValue;
  30187. if (attrs.hasOwnProperty('ngRefRead')) {
  30188. if (attrs.ngRefRead === '$element') {
  30189. refValue = element;
  30190. } else {
  30191. refValue = element.data('$' + attrs.ngRefRead + 'Controller');
  30192. if (!refValue) {
  30193. throw ngRefMinErr(
  30194. 'noctrl',
  30195. 'The controller for ngRefRead="{0}" could not be found on ngRef="{1}"',
  30196. attrs.ngRefRead,
  30197. tAttrs.ngRef
  30198. );
  30199. }
  30200. }
  30201. } else {
  30202. refValue = element.data('$' + controllerName + 'Controller');
  30203. }
  30204. refValue = refValue || element;
  30205. setter(scope, refValue);
  30206. // when the element is removed, remove it (nullify it)
  30207. element.on('$destroy', function() {
  30208. // only remove it if value has not changed,
  30209. // because animations (and other procedures) may duplicate elements
  30210. if (getter(scope) === refValue) {
  30211. setter(scope, null);
  30212. }
  30213. });
  30214. };
  30215. }
  30216. };
  30217. }];
  30218. /* exported ngRepeatDirective */
  30219. /**
  30220. * @ngdoc directive
  30221. * @name ngRepeat
  30222. * @multiElement
  30223. * @restrict A
  30224. *
  30225. * @description
  30226. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  30227. * instance gets its own scope, where the given loop variable is set to the current collection item,
  30228. * and `$index` is set to the item index or key.
  30229. *
  30230. * Special properties are exposed on the local scope of each template instance, including:
  30231. *
  30232. * | Variable | Type | Details |
  30233. * |-----------|-----------------|-----------------------------------------------------------------------------|
  30234. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  30235. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  30236. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  30237. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  30238. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  30239. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  30240. *
  30241. * <div class="alert alert-info">
  30242. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  30243. * This may be useful when, for instance, nesting ngRepeats.
  30244. * </div>
  30245. *
  30246. *
  30247. * ## Iterating over object properties
  30248. *
  30249. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  30250. * syntax:
  30251. *
  30252. * ```js
  30253. * <div ng-repeat="(key, value) in myObj"> ... </div>
  30254. * ```
  30255. *
  30256. * However, there are a few limitations compared to array iteration:
  30257. *
  30258. * - The JavaScript specification does not define the order of keys
  30259. * returned for an object, so AngularJS relies on the order returned by the browser
  30260. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  30261. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  30262. * and reinstated. See the
  30263. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  30264. *
  30265. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  30266. * it's a prefix used by AngularJS for public (`$`) and private (`$$`) properties.
  30267. *
  30268. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  30269. * objects, and will throw an error if used with one.
  30270. *
  30271. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  30272. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  30273. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  30274. * or implement a `$watch` on the object yourself.
  30275. *
  30276. *
  30277. * ## Tracking and Duplicates
  30278. *
  30279. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  30280. * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:
  30281. *
  30282. * * When an item is added, a new instance of the template is added to the DOM.
  30283. * * When an item is removed, its template instance is removed from the DOM.
  30284. * * When items are reordered, their respective templates are reordered in the DOM.
  30285. *
  30286. * To minimize creation of DOM elements, `ngRepeat` uses a function
  30287. * to "keep track" of all items in the collection and their corresponding DOM elements.
  30288. * For example, if an item is added to the collection, `ngRepeat` will know that all other items
  30289. * already have DOM elements, and will not re-render them.
  30290. *
  30291. * All different types of tracking functions, their syntax, and their support for duplicate
  30292. * items in collections can be found in the
  30293. * {@link ngRepeat#ngRepeat-arguments ngRepeat expression description}.
  30294. *
  30295. * <div class="alert alert-success">
  30296. * **Best Practice:** If you are working with objects that have a unique identifier property, you
  30297. * should track by this identifier instead of the object instance,
  30298. * e.g. `item in items track by item.id`.
  30299. * Should you reload your data later, `ngRepeat` will not have to rebuild the DOM elements for items
  30300. * it has already rendered, even if the JavaScript objects in the collection have been substituted
  30301. * for new ones. For large collections, this significantly improves rendering performance.
  30302. * </div>
  30303. *
  30304. * ### Effects of DOM Element re-use
  30305. *
  30306. * When DOM elements are re-used, ngRepeat updates the scope for the element, which will
  30307. * automatically update any active bindings on the template. However, other
  30308. * functionality will not be updated, because the element is not re-created:
  30309. *
  30310. * - Directives are not re-compiled
  30311. * - {@link guide/expression#one-time-binding one-time expressions} on the repeated template are not
  30312. * updated if they have stabilized.
  30313. *
  30314. * The above affects all kinds of element re-use due to tracking, but may be especially visible
  30315. * when tracking by `$index` due to the way ngRepeat re-uses elements.
  30316. *
  30317. * The following example shows the effects of different actions with tracking:
  30318. <example module="ngRepeat" name="ngRepeat-tracking" deps="angular-animate.js" animations="true">
  30319. <file name="script.js">
  30320. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  30321. var friends = [
  30322. {name:'John', age:25},
  30323. {name:'Mary', age:40},
  30324. {name:'Peter', age:85}
  30325. ];
  30326. $scope.removeFirst = function() {
  30327. $scope.friends.shift();
  30328. };
  30329. $scope.updateAge = function() {
  30330. $scope.friends.forEach(function(el) {
  30331. el.age = el.age + 5;
  30332. });
  30333. };
  30334. $scope.copy = function() {
  30335. $scope.friends = angular.copy($scope.friends);
  30336. };
  30337. $scope.reset = function() {
  30338. $scope.friends = angular.copy(friends);
  30339. };
  30340. $scope.reset();
  30341. });
  30342. </file>
  30343. <file name="index.html">
  30344. <div ng-controller="repeatController">
  30345. <ol>
  30346. <li>When you click "Update Age", only the first list updates the age, because all others have
  30347. a one-time binding on the age property. If you then click "Copy", the current friend list
  30348. is copied, and now the second list updates the age, because the identity of the collection items
  30349. has changed and the list must be re-rendered. The 3rd and 4th list stay the same, because all the
  30350. items are already known according to their tracking functions.
  30351. </li>
  30352. <li>When you click "Remove First", the 4th list has the wrong age on both remaining items. This is
  30353. due to tracking by $index: when the first collection item is removed, ngRepeat reuses the first
  30354. DOM element for the new first collection item, and so on. Since the age property is one-time
  30355. bound, the value remains from the collection item which was previously at this index.
  30356. </li>
  30357. </ol>
  30358. <button ng-click="removeFirst()">Remove First</button>
  30359. <button ng-click="updateAge()">Update Age</button>
  30360. <button ng-click="copy()">Copy</button>
  30361. <br><button ng-click="reset()">Reset List</button>
  30362. <br>
  30363. <code>track by $id(friend)</code> (default):
  30364. <ul class="example-animate-container">
  30365. <li class="animate-repeat" ng-repeat="friend in friends">
  30366. {{friend.name}} is {{friend.age}} years old.
  30367. </li>
  30368. </ul>
  30369. <code>track by $id(friend)</code> (default), with age one-time binding:
  30370. <ul class="example-animate-container">
  30371. <li class="animate-repeat" ng-repeat="friend in friends">
  30372. {{friend.name}} is {{::friend.age}} years old.
  30373. </li>
  30374. </ul>
  30375. <code>track by friend.name</code>, with age one-time binding:
  30376. <ul class="example-animate-container">
  30377. <li class="animate-repeat" ng-repeat="friend in friends track by friend.name">
  30378. {{friend.name}} is {{::friend.age}} years old.
  30379. </li>
  30380. </ul>
  30381. <code>track by $index</code>, with age one-time binding:
  30382. <ul class="example-animate-container">
  30383. <li class="animate-repeat" ng-repeat="friend in friends track by $index">
  30384. {{friend.name}} is {{::friend.age}} years old.
  30385. </li>
  30386. </ul>
  30387. </div>
  30388. </file>
  30389. <file name="animations.css">
  30390. .example-animate-container {
  30391. background:white;
  30392. border:1px solid black;
  30393. list-style:none;
  30394. margin:0;
  30395. padding:0 10px;
  30396. }
  30397. .animate-repeat {
  30398. line-height:30px;
  30399. list-style:none;
  30400. box-sizing:border-box;
  30401. }
  30402. .animate-repeat.ng-move,
  30403. .animate-repeat.ng-enter,
  30404. .animate-repeat.ng-leave {
  30405. transition:all linear 0.5s;
  30406. }
  30407. .animate-repeat.ng-leave.ng-leave-active,
  30408. .animate-repeat.ng-move,
  30409. .animate-repeat.ng-enter {
  30410. opacity:0;
  30411. max-height:0;
  30412. }
  30413. .animate-repeat.ng-leave,
  30414. .animate-repeat.ng-move.ng-move-active,
  30415. .animate-repeat.ng-enter.ng-enter-active {
  30416. opacity:1;
  30417. max-height:30px;
  30418. }
  30419. </file>
  30420. </example>
  30421. *
  30422. * ## Special repeat start and end points
  30423. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  30424. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  30425. * 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)
  30426. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  30427. *
  30428. * The example below makes use of this feature:
  30429. * ```html
  30430. * <header ng-repeat-start="item in items">
  30431. * Header {{ item }}
  30432. * </header>
  30433. * <div class="body">
  30434. * Body {{ item }}
  30435. * </div>
  30436. * <footer ng-repeat-end>
  30437. * Footer {{ item }}
  30438. * </footer>
  30439. * ```
  30440. *
  30441. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  30442. * ```html
  30443. * <header>
  30444. * Header A
  30445. * </header>
  30446. * <div class="body">
  30447. * Body A
  30448. * </div>
  30449. * <footer>
  30450. * Footer A
  30451. * </footer>
  30452. * <header>
  30453. * Header B
  30454. * </header>
  30455. * <div class="body">
  30456. * Body B
  30457. * </div>
  30458. * <footer>
  30459. * Footer B
  30460. * </footer>
  30461. * ```
  30462. *
  30463. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  30464. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  30465. *
  30466. * @animations
  30467. * | Animation | Occurs |
  30468. * |----------------------------------|-------------------------------------|
  30469. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  30470. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  30471. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  30472. *
  30473. * See the example below for defining CSS animations with ngRepeat.
  30474. *
  30475. * @element ANY
  30476. * @scope
  30477. * @priority 1000
  30478. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  30479. * formats are currently supported:
  30480. *
  30481. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  30482. * is a scope expression giving the collection to enumerate.
  30483. *
  30484. * For example: `album in artist.albums`.
  30485. *
  30486. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  30487. * and `expression` is the scope expression giving the collection to enumerate.
  30488. *
  30489. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  30490. *
  30491. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  30492. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  30493. * is specified, ng-repeat associates elements by identity. It is an error to have
  30494. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  30495. * mapped to the same DOM element, which is not possible.)
  30496. *
  30497. * *Default tracking: $id()*: `item in items` is equivalent to `item in items track by $id(item)`.
  30498. * This implies that the DOM elements will be associated by item identity in the collection.
  30499. *
  30500. * The built-in `$id()` function can be used to assign a unique
  30501. * `$$hashKey` property to each item in the collection. This property is then used as a key to associated DOM elements
  30502. * with the corresponding item in the collection by identity. Moving the same object would move
  30503. * the DOM element in the same way in the DOM.
  30504. * Note that the default id function does not support duplicate primitive values (`number`, `string`),
  30505. * but supports duplictae non-primitive values (`object`) that are *equal* in shape.
  30506. *
  30507. * *Custom Expression*: It is possible to use any AngularJS expression to compute the tracking
  30508. * id, for example with a function, or using a property on the collection items.
  30509. * `item in items track by item.id` is a typical pattern when the items have a unique identifier,
  30510. * e.g. database id. In this case the object identity does not matter. Two objects are considered
  30511. * equivalent as long as their `id` property is same.
  30512. * Tracking by unique identifier is the most performant way and should be used whenever possible.
  30513. *
  30514. * *$index*: This special property tracks the collection items by their index, and
  30515. * re-uses the DOM elements that match that index, e.g. `item in items track by $index`. This can
  30516. * be used for a performance improvement if no unique identfier is available and the identity of
  30517. * the collection items cannot be easily computed. It also allows duplicates.
  30518. *
  30519. * <div class="alert alert-warning">
  30520. * <strong>Note:</strong> Re-using DOM elements can have unforeseen effects. Read the
  30521. * {@link ngRepeat#tracking-and-duplicates section on tracking and duplicates} for
  30522. * more info.
  30523. * </div>
  30524. *
  30525. * <div class="alert alert-warning">
  30526. * <strong>Note:</strong> the `track by` expression must come last - after any filters, and the alias expression:
  30527. * `item in items | filter:searchText as results track by item.id`
  30528. * </div>
  30529. *
  30530. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  30531. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  30532. * when a filter is active on the repeater, but the filtered result set is empty.
  30533. *
  30534. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  30535. * the items have been processed through the filter.
  30536. *
  30537. * Please note that `as [variable name] is not an operator but rather a part of ngRepeat
  30538. * micro-syntax so it can be used only after all filters (and not as operator, inside an expression).
  30539. *
  30540. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results track by item.id` .
  30541. *
  30542. * @example
  30543. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  30544. * results by name or by age. New (entering) and removed (leaving) items are animated.
  30545. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
  30546. <file name="index.html">
  30547. <div ng-controller="repeatController">
  30548. I have {{friends.length}} friends. They are:
  30549. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  30550. <ul class="example-animate-container">
  30551. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results track by friend.name">
  30552. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  30553. </li>
  30554. <li class="animate-repeat" ng-if="results.length === 0">
  30555. <strong>No results found...</strong>
  30556. </li>
  30557. </ul>
  30558. </div>
  30559. </file>
  30560. <file name="script.js">
  30561. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  30562. $scope.friends = [
  30563. {name:'John', age:25, gender:'boy'},
  30564. {name:'Jessie', age:30, gender:'girl'},
  30565. {name:'Johanna', age:28, gender:'girl'},
  30566. {name:'Joy', age:15, gender:'girl'},
  30567. {name:'Mary', age:28, gender:'girl'},
  30568. {name:'Peter', age:95, gender:'boy'},
  30569. {name:'Sebastian', age:50, gender:'boy'},
  30570. {name:'Erika', age:27, gender:'girl'},
  30571. {name:'Patrick', age:40, gender:'boy'},
  30572. {name:'Samantha', age:60, gender:'girl'}
  30573. ];
  30574. });
  30575. </file>
  30576. <file name="animations.css">
  30577. .example-animate-container {
  30578. background:white;
  30579. border:1px solid black;
  30580. list-style:none;
  30581. margin:0;
  30582. padding:0 10px;
  30583. }
  30584. .animate-repeat {
  30585. line-height:30px;
  30586. list-style:none;
  30587. box-sizing:border-box;
  30588. }
  30589. .animate-repeat.ng-move,
  30590. .animate-repeat.ng-enter,
  30591. .animate-repeat.ng-leave {
  30592. transition:all linear 0.5s;
  30593. }
  30594. .animate-repeat.ng-leave.ng-leave-active,
  30595. .animate-repeat.ng-move,
  30596. .animate-repeat.ng-enter {
  30597. opacity:0;
  30598. max-height:0;
  30599. }
  30600. .animate-repeat.ng-leave,
  30601. .animate-repeat.ng-move.ng-move-active,
  30602. .animate-repeat.ng-enter.ng-enter-active {
  30603. opacity:1;
  30604. max-height:30px;
  30605. }
  30606. </file>
  30607. <file name="protractor.js" type="protractor">
  30608. var friends = element.all(by.repeater('friend in friends'));
  30609. it('should render initial data set', function() {
  30610. expect(friends.count()).toBe(10);
  30611. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  30612. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  30613. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  30614. expect(element(by.binding('friends.length')).getText())
  30615. .toMatch("I have 10 friends. They are:");
  30616. });
  30617. it('should update repeater when filter predicate changes', function() {
  30618. expect(friends.count()).toBe(10);
  30619. element(by.model('q')).sendKeys('ma');
  30620. expect(friends.count()).toBe(2);
  30621. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  30622. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  30623. });
  30624. </file>
  30625. </example>
  30626. */
  30627. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  30628. var NG_REMOVED = '$$NG_REMOVED';
  30629. var ngRepeatMinErr = minErr('ngRepeat');
  30630. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  30631. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  30632. scope[valueIdentifier] = value;
  30633. if (keyIdentifier) scope[keyIdentifier] = key;
  30634. scope.$index = index;
  30635. scope.$first = (index === 0);
  30636. scope.$last = (index === (arrayLength - 1));
  30637. scope.$middle = !(scope.$first || scope.$last);
  30638. // eslint-disable-next-line no-bitwise
  30639. scope.$odd = !(scope.$even = (index & 1) === 0);
  30640. };
  30641. var getBlockStart = function(block) {
  30642. return block.clone[0];
  30643. };
  30644. var getBlockEnd = function(block) {
  30645. return block.clone[block.clone.length - 1];
  30646. };
  30647. return {
  30648. restrict: 'A',
  30649. multiElement: true,
  30650. transclude: 'element',
  30651. priority: 1000,
  30652. terminal: true,
  30653. $$tlb: true,
  30654. compile: function ngRepeatCompile($element, $attr) {
  30655. var expression = $attr.ngRepeat;
  30656. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  30657. 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*$/);
  30658. if (!match) {
  30659. throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
  30660. expression);
  30661. }
  30662. var lhs = match[1];
  30663. var rhs = match[2];
  30664. var aliasAs = match[3];
  30665. var trackByExp = match[4];
  30666. match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
  30667. if (!match) {
  30668. throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
  30669. lhs);
  30670. }
  30671. var valueIdentifier = match[3] || match[1];
  30672. var keyIdentifier = match[2];
  30673. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  30674. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  30675. throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
  30676. aliasAs);
  30677. }
  30678. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  30679. var hashFnLocals = {$id: hashKey};
  30680. if (trackByExp) {
  30681. trackByExpGetter = $parse(trackByExp);
  30682. } else {
  30683. trackByIdArrayFn = function(key, value) {
  30684. return hashKey(value);
  30685. };
  30686. trackByIdObjFn = function(key) {
  30687. return key;
  30688. };
  30689. }
  30690. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  30691. if (trackByExpGetter) {
  30692. trackByIdExpFn = function(key, value, index) {
  30693. // assign key, value, and $index to the locals so that they can be used in hash functions
  30694. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  30695. hashFnLocals[valueIdentifier] = value;
  30696. hashFnLocals.$index = index;
  30697. return trackByExpGetter($scope, hashFnLocals);
  30698. };
  30699. }
  30700. // Store a list of elements from previous run. This is a hash where key is the item from the
  30701. // iterator, and the value is objects with following properties.
  30702. // - scope: bound scope
  30703. // - clone: previous element.
  30704. // - index: position
  30705. //
  30706. // We are using no-proto object so that we don't need to guard against inherited props via
  30707. // hasOwnProperty.
  30708. var lastBlockMap = createMap();
  30709. //watch props
  30710. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  30711. var index, length,
  30712. previousNode = $element[0], // node that cloned nodes should be inserted after
  30713. // initialized to the comment node anchor
  30714. nextNode,
  30715. // Same as lastBlockMap but it has the current state. It will become the
  30716. // lastBlockMap on the next iteration.
  30717. nextBlockMap = createMap(),
  30718. collectionLength,
  30719. key, value, // key/value of iteration
  30720. trackById,
  30721. trackByIdFn,
  30722. collectionKeys,
  30723. block, // last object information {scope, element, id}
  30724. nextBlockOrder,
  30725. elementsToRemove;
  30726. if (aliasAs) {
  30727. $scope[aliasAs] = collection;
  30728. }
  30729. if (isArrayLike(collection)) {
  30730. collectionKeys = collection;
  30731. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  30732. } else {
  30733. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  30734. // if object, extract keys, in enumeration order, unsorted
  30735. collectionKeys = [];
  30736. for (var itemKey in collection) {
  30737. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  30738. collectionKeys.push(itemKey);
  30739. }
  30740. }
  30741. }
  30742. collectionLength = collectionKeys.length;
  30743. nextBlockOrder = new Array(collectionLength);
  30744. // locate existing items
  30745. for (index = 0; index < collectionLength; index++) {
  30746. key = (collection === collectionKeys) ? index : collectionKeys[index];
  30747. value = collection[key];
  30748. trackById = trackByIdFn(key, value, index);
  30749. if (lastBlockMap[trackById]) {
  30750. // found previously seen block
  30751. block = lastBlockMap[trackById];
  30752. delete lastBlockMap[trackById];
  30753. nextBlockMap[trackById] = block;
  30754. nextBlockOrder[index] = block;
  30755. } else if (nextBlockMap[trackById]) {
  30756. // if collision detected. restore lastBlockMap and throw an error
  30757. forEach(nextBlockOrder, function(block) {
  30758. if (block && block.scope) lastBlockMap[block.id] = block;
  30759. });
  30760. throw ngRepeatMinErr('dupes',
  30761. 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
  30762. expression, trackById, value);
  30763. } else {
  30764. // new never before seen block
  30765. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  30766. nextBlockMap[trackById] = true;
  30767. }
  30768. }
  30769. // remove leftover items
  30770. for (var blockKey in lastBlockMap) {
  30771. block = lastBlockMap[blockKey];
  30772. elementsToRemove = getBlockNodes(block.clone);
  30773. $animate.leave(elementsToRemove);
  30774. if (elementsToRemove[0].parentNode) {
  30775. // if the element was not removed yet because of pending animation, mark it as deleted
  30776. // so that we can ignore it later
  30777. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  30778. elementsToRemove[index][NG_REMOVED] = true;
  30779. }
  30780. }
  30781. block.scope.$destroy();
  30782. }
  30783. // we are not using forEach for perf reasons (trying to avoid #call)
  30784. for (index = 0; index < collectionLength; index++) {
  30785. key = (collection === collectionKeys) ? index : collectionKeys[index];
  30786. value = collection[key];
  30787. block = nextBlockOrder[index];
  30788. if (block.scope) {
  30789. // if we have already seen this object, then we need to reuse the
  30790. // associated scope/element
  30791. nextNode = previousNode;
  30792. // skip nodes that are already pending removal via leave animation
  30793. do {
  30794. nextNode = nextNode.nextSibling;
  30795. } while (nextNode && nextNode[NG_REMOVED]);
  30796. if (getBlockStart(block) !== nextNode) {
  30797. // existing item which got moved
  30798. $animate.move(getBlockNodes(block.clone), null, previousNode);
  30799. }
  30800. previousNode = getBlockEnd(block);
  30801. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  30802. } else {
  30803. // new item which we don't know about
  30804. $transclude(function ngRepeatTransclude(clone, scope) {
  30805. block.scope = scope;
  30806. // http://jsperf.com/clone-vs-createcomment
  30807. var endNode = ngRepeatEndComment.cloneNode(false);
  30808. clone[clone.length++] = endNode;
  30809. $animate.enter(clone, null, previousNode);
  30810. previousNode = endNode;
  30811. // Note: We only need the first/last node of the cloned nodes.
  30812. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  30813. // by a directive with templateUrl when its template arrives.
  30814. block.clone = clone;
  30815. nextBlockMap[block.id] = block;
  30816. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  30817. });
  30818. }
  30819. }
  30820. lastBlockMap = nextBlockMap;
  30821. });
  30822. };
  30823. }
  30824. };
  30825. }];
  30826. var NG_HIDE_CLASS = 'ng-hide';
  30827. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  30828. /**
  30829. * @ngdoc directive
  30830. * @name ngShow
  30831. * @multiElement
  30832. *
  30833. * @description
  30834. * The `ngShow` directive shows or hides the given HTML element based on the expression provided to
  30835. * the `ngShow` attribute.
  30836. *
  30837. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  30838. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  30839. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  30840. * {@link ng.directive:ngCsp ngCsp}).
  30841. *
  30842. * ```html
  30843. * <!-- when $scope.myValue is truthy (element is visible) -->
  30844. * <div ng-show="myValue"></div>
  30845. *
  30846. * <!-- when $scope.myValue is falsy (element is hidden) -->
  30847. * <div ng-show="myValue" class="ng-hide"></div>
  30848. * ```
  30849. *
  30850. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added
  30851. * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide`
  30852. * CSS class is removed from the element causing the element not to appear hidden.
  30853. *
  30854. * ## Why is `!important` used?
  30855. *
  30856. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  30857. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  30858. * simple as changing the display style on a HTML list item would make hidden elements appear
  30859. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  30860. *
  30861. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  30862. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  30863. * developer chooses to override the styling to change how to hide an element then it is just a
  30864. * matter of using `!important` in their own CSS code.
  30865. *
  30866. * ### Overriding `.ng-hide`
  30867. *
  30868. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  30869. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  30870. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  30871. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  30872. *
  30873. * ```css
  30874. * .ng-hide:not(.ng-hide-animate) {
  30875. * /&#42; These are just alternative ways of hiding an element &#42;/
  30876. * display: block!important;
  30877. * position: absolute;
  30878. * top: -9999px;
  30879. * left: -9999px;
  30880. * }
  30881. * ```
  30882. *
  30883. * By default you don't need to override anything in CSS and the animations will work around the
  30884. * display style.
  30885. *
  30886. * @animations
  30887. * | Animation | Occurs |
  30888. * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
  30889. * | {@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. |
  30890. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. |
  30891. *
  30892. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  30893. * directive expression is true and false. This system works like the animation system present with
  30894. * `ngClass` except that you must also include the `!important` flag to override the display
  30895. * property so that the elements are not actually hidden during the animation.
  30896. *
  30897. * ```css
  30898. * /&#42; A working example can be found at the bottom of this page. &#42;/
  30899. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  30900. * transition: all 0.5s linear;
  30901. * }
  30902. *
  30903. * .my-element.ng-hide-add { ... }
  30904. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  30905. * .my-element.ng-hide-remove { ... }
  30906. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  30907. * ```
  30908. *
  30909. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  30910. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  30911. *
  30912. * @element ANY
  30913. * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the
  30914. * element is shown/hidden respectively.
  30915. *
  30916. * @example
  30917. * A simple example, animating the element's opacity:
  30918. *
  30919. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-simple">
  30920. <file name="index.html">
  30921. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  30922. <div class="check-element animate-show-hide" ng-show="checked">
  30923. I show up when your checkbox is checked.
  30924. </div>
  30925. </file>
  30926. <file name="animations.css">
  30927. .animate-show-hide.ng-hide {
  30928. opacity: 0;
  30929. }
  30930. .animate-show-hide.ng-hide-add,
  30931. .animate-show-hide.ng-hide-remove {
  30932. transition: all linear 0.5s;
  30933. }
  30934. .check-element {
  30935. border: 1px solid black;
  30936. opacity: 1;
  30937. padding: 10px;
  30938. }
  30939. </file>
  30940. <file name="protractor.js" type="protractor">
  30941. it('should check ngShow', function() {
  30942. var checkbox = element(by.model('checked'));
  30943. var checkElem = element(by.css('.check-element'));
  30944. expect(checkElem.isDisplayed()).toBe(false);
  30945. checkbox.click();
  30946. expect(checkElem.isDisplayed()).toBe(true);
  30947. });
  30948. </file>
  30949. </example>
  30950. *
  30951. * <hr />
  30952. * @example
  30953. * A more complex example, featuring different show/hide animations:
  30954. *
  30955. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-complex">
  30956. <file name="index.html">
  30957. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  30958. <div class="check-element funky-show-hide" ng-show="checked">
  30959. I show up when your checkbox is checked.
  30960. </div>
  30961. </file>
  30962. <file name="animations.css">
  30963. body {
  30964. overflow: hidden;
  30965. perspective: 1000px;
  30966. }
  30967. .funky-show-hide.ng-hide-add {
  30968. transform: rotateZ(0);
  30969. transform-origin: right;
  30970. transition: all 0.5s ease-in-out;
  30971. }
  30972. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  30973. transform: rotateZ(-135deg);
  30974. }
  30975. .funky-show-hide.ng-hide-remove {
  30976. transform: rotateY(90deg);
  30977. transform-origin: left;
  30978. transition: all 0.5s ease;
  30979. }
  30980. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  30981. transform: rotateY(0);
  30982. }
  30983. .check-element {
  30984. border: 1px solid black;
  30985. opacity: 1;
  30986. padding: 10px;
  30987. }
  30988. </file>
  30989. <file name="protractor.js" type="protractor">
  30990. it('should check ngShow', function() {
  30991. var checkbox = element(by.model('checked'));
  30992. var checkElem = element(by.css('.check-element'));
  30993. expect(checkElem.isDisplayed()).toBe(false);
  30994. checkbox.click();
  30995. expect(checkElem.isDisplayed()).toBe(true);
  30996. });
  30997. </file>
  30998. </example>
  30999. *
  31000. * @knownIssue
  31001. *
  31002. * ### Flickering when using ngShow to toggle between elements
  31003. *
  31004. * When using {@link ngShow} and / or {@link ngHide} to toggle between elements, it can
  31005. * happen that both the element to show and the element to hide are visible for a very short time.
  31006. *
  31007. * This usually happens when the {@link ngAnimate ngAnimate module} is included, but no actual animations
  31008. * are defined for {@link ngShow} / {@link ngHide}. Internet Explorer is affected more often than
  31009. * other browsers.
  31010. *
  31011. * There are several way to mitigate this problem:
  31012. *
  31013. * - {@link guide/animations#how-to-selectively-enable-disable-and-skip-animations Disable animations on the affected elements}.
  31014. * - Use {@link ngIf} or {@link ngSwitch} instead of {@link ngShow} / {@link ngHide}.
  31015. * - Use the special CSS selector `ng-hide.ng-hide-animate` to set `{display: none}` or similar on the affected elements.
  31016. * - Use `ng-class="{'ng-hide': expression}` instead of instead of {@link ngShow} / {@link ngHide}.
  31017. * - Define an animation on the affected elements.
  31018. */
  31019. var ngShowDirective = ['$animate', function($animate) {
  31020. return {
  31021. restrict: 'A',
  31022. multiElement: true,
  31023. link: function(scope, element, attr) {
  31024. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  31025. // we're adding a temporary, animation-specific class for ng-hide since this way
  31026. // we can control when the element is actually displayed on screen without having
  31027. // to have a global/greedy CSS selector that breaks when other animations are run.
  31028. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  31029. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  31030. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  31031. });
  31032. });
  31033. }
  31034. };
  31035. }];
  31036. /**
  31037. * @ngdoc directive
  31038. * @name ngHide
  31039. * @multiElement
  31040. *
  31041. * @description
  31042. * The `ngHide` directive shows or hides the given HTML element based on the expression provided to
  31043. * the `ngHide` attribute.
  31044. *
  31045. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  31046. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  31047. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  31048. * {@link ng.directive:ngCsp ngCsp}).
  31049. *
  31050. * ```html
  31051. * <!-- when $scope.myValue is truthy (element is hidden) -->
  31052. * <div ng-hide="myValue" class="ng-hide"></div>
  31053. *
  31054. * <!-- when $scope.myValue is falsy (element is visible) -->
  31055. * <div ng-hide="myValue"></div>
  31056. * ```
  31057. *
  31058. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added
  31059. * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide`
  31060. * CSS class is removed from the element causing the element not to appear hidden.
  31061. *
  31062. * ## Why is `!important` used?
  31063. *
  31064. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  31065. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  31066. * simple as changing the display style on a HTML list item would make hidden elements appear
  31067. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  31068. *
  31069. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  31070. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  31071. * developer chooses to override the styling to change how to hide an element then it is just a
  31072. * matter of using `!important` in their own CSS code.
  31073. *
  31074. * ### Overriding `.ng-hide`
  31075. *
  31076. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  31077. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  31078. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  31079. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  31080. *
  31081. * ```css
  31082. * .ng-hide:not(.ng-hide-animate) {
  31083. * /&#42; These are just alternative ways of hiding an element &#42;/
  31084. * display: block!important;
  31085. * position: absolute;
  31086. * top: -9999px;
  31087. * left: -9999px;
  31088. * }
  31089. * ```
  31090. *
  31091. * By default you don't need to override in CSS anything and the animations will work around the
  31092. * display style.
  31093. *
  31094. * @animations
  31095. * | Animation | Occurs |
  31096. * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------|
  31097. * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. |
  31098. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. |
  31099. *
  31100. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  31101. * directive expression is true and false. This system works like the animation system present with
  31102. * `ngClass` except that you must also include the `!important` flag to override the display
  31103. * property so that the elements are not actually hidden during the animation.
  31104. *
  31105. * ```css
  31106. * /&#42; A working example can be found at the bottom of this page. &#42;/
  31107. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  31108. * transition: all 0.5s linear;
  31109. * }
  31110. *
  31111. * .my-element.ng-hide-add { ... }
  31112. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  31113. * .my-element.ng-hide-remove { ... }
  31114. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  31115. * ```
  31116. *
  31117. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  31118. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  31119. *
  31120. * @element ANY
  31121. * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the
  31122. * element is hidden/shown respectively.
  31123. *
  31124. * @example
  31125. * A simple example, animating the element's opacity:
  31126. *
  31127. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-simple">
  31128. <file name="index.html">
  31129. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  31130. <div class="check-element animate-show-hide" ng-hide="checked">
  31131. I hide when your checkbox is checked.
  31132. </div>
  31133. </file>
  31134. <file name="animations.css">
  31135. .animate-show-hide.ng-hide {
  31136. opacity: 0;
  31137. }
  31138. .animate-show-hide.ng-hide-add,
  31139. .animate-show-hide.ng-hide-remove {
  31140. transition: all linear 0.5s;
  31141. }
  31142. .check-element {
  31143. border: 1px solid black;
  31144. opacity: 1;
  31145. padding: 10px;
  31146. }
  31147. </file>
  31148. <file name="protractor.js" type="protractor">
  31149. it('should check ngHide', function() {
  31150. var checkbox = element(by.model('checked'));
  31151. var checkElem = element(by.css('.check-element'));
  31152. expect(checkElem.isDisplayed()).toBe(true);
  31153. checkbox.click();
  31154. expect(checkElem.isDisplayed()).toBe(false);
  31155. });
  31156. </file>
  31157. </example>
  31158. *
  31159. * <hr />
  31160. * @example
  31161. * A more complex example, featuring different show/hide animations:
  31162. *
  31163. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-complex">
  31164. <file name="index.html">
  31165. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  31166. <div class="check-element funky-show-hide" ng-hide="checked">
  31167. I hide when your checkbox is checked.
  31168. </div>
  31169. </file>
  31170. <file name="animations.css">
  31171. body {
  31172. overflow: hidden;
  31173. perspective: 1000px;
  31174. }
  31175. .funky-show-hide.ng-hide-add {
  31176. transform: rotateZ(0);
  31177. transform-origin: right;
  31178. transition: all 0.5s ease-in-out;
  31179. }
  31180. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  31181. transform: rotateZ(-135deg);
  31182. }
  31183. .funky-show-hide.ng-hide-remove {
  31184. transform: rotateY(90deg);
  31185. transform-origin: left;
  31186. transition: all 0.5s ease;
  31187. }
  31188. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  31189. transform: rotateY(0);
  31190. }
  31191. .check-element {
  31192. border: 1px solid black;
  31193. opacity: 1;
  31194. padding: 10px;
  31195. }
  31196. </file>
  31197. <file name="protractor.js" type="protractor">
  31198. it('should check ngHide', function() {
  31199. var checkbox = element(by.model('checked'));
  31200. var checkElem = element(by.css('.check-element'));
  31201. expect(checkElem.isDisplayed()).toBe(true);
  31202. checkbox.click();
  31203. expect(checkElem.isDisplayed()).toBe(false);
  31204. });
  31205. </file>
  31206. </example>
  31207. *
  31208. * @knownIssue
  31209. *
  31210. * ### Flickering when using ngHide to toggle between elements
  31211. *
  31212. * When using {@link ngShow} and / or {@link ngHide} to toggle between elements, it can
  31213. * happen that both the element to show and the element to hide are visible for a very short time.
  31214. *
  31215. * This usually happens when the {@link ngAnimate ngAnimate module} is included, but no actual animations
  31216. * are defined for {@link ngShow} / {@link ngHide}. Internet Explorer is affected more often than
  31217. * other browsers.
  31218. *
  31219. * There are several way to mitigate this problem:
  31220. *
  31221. * - {@link guide/animations#how-to-selectively-enable-disable-and-skip-animations Disable animations on the affected elements}.
  31222. * - Use {@link ngIf} or {@link ngSwitch} instead of {@link ngShow} / {@link ngHide}.
  31223. * - Use the special CSS selector `ng-hide.ng-hide-animate` to set `{display: none}` or similar on the affected elements.
  31224. * - Use `ng-class="{'ng-hide': expression}` instead of instead of {@link ngShow} / {@link ngHide}.
  31225. * - Define an animation on the affected elements.
  31226. */
  31227. var ngHideDirective = ['$animate', function($animate) {
  31228. return {
  31229. restrict: 'A',
  31230. multiElement: true,
  31231. link: function(scope, element, attr) {
  31232. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  31233. // The comment inside of the ngShowDirective explains why we add and
  31234. // remove a temporary class for the show/hide animation
  31235. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  31236. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  31237. });
  31238. });
  31239. }
  31240. };
  31241. }];
  31242. /**
  31243. * @ngdoc directive
  31244. * @name ngStyle
  31245. * @restrict AC
  31246. *
  31247. * @description
  31248. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  31249. *
  31250. * @knownIssue
  31251. * You should not use {@link guide/interpolation interpolation} in the value of the `style`
  31252. * attribute, when using the `ngStyle` directive on the same element.
  31253. * See {@link guide/interpolation#known-issues here} for more info.
  31254. *
  31255. * @element ANY
  31256. * @param {expression} ngStyle
  31257. *
  31258. * {@link guide/expression Expression} which evals to an
  31259. * object whose keys are CSS style names and values are corresponding values for those CSS
  31260. * keys.
  31261. *
  31262. * Since some CSS style names are not valid keys for an object, they must be quoted.
  31263. * See the 'background-color' style in the example below.
  31264. *
  31265. * @example
  31266. <example name="ng-style">
  31267. <file name="index.html">
  31268. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  31269. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  31270. <input type="button" value="clear" ng-click="myStyle={}">
  31271. <br/>
  31272. <span ng-style="myStyle">Sample Text</span>
  31273. <pre>myStyle={{myStyle}}</pre>
  31274. </file>
  31275. <file name="style.css">
  31276. span {
  31277. color: black;
  31278. }
  31279. </file>
  31280. <file name="protractor.js" type="protractor">
  31281. var colorSpan = element(by.css('span'));
  31282. it('should check ng-style', function() {
  31283. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  31284. element(by.css('input[value=\'set color\']')).click();
  31285. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  31286. element(by.css('input[value=clear]')).click();
  31287. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  31288. });
  31289. </file>
  31290. </example>
  31291. */
  31292. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  31293. scope.$watchCollection(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  31294. if (oldStyles && (newStyles !== oldStyles)) {
  31295. forEach(oldStyles, function(val, style) { element.css(style, '');});
  31296. }
  31297. if (newStyles) element.css(newStyles);
  31298. });
  31299. });
  31300. /**
  31301. * @ngdoc directive
  31302. * @name ngSwitch
  31303. * @restrict EA
  31304. *
  31305. * @description
  31306. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  31307. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  31308. * as specified in the template.
  31309. *
  31310. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  31311. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  31312. * matches the value obtained from the evaluated expression. In other words, you define a container element
  31313. * (where you place the directive), place an expression on the **`on="..."` attribute**
  31314. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  31315. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  31316. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  31317. * attribute is displayed.
  31318. *
  31319. * <div class="alert alert-info">
  31320. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  31321. * as literal string values to match against.
  31322. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  31323. * value of the expression `$scope.someVal`.
  31324. * </div>
  31325. * @animations
  31326. * | Animation | Occurs |
  31327. * |----------------------------------|-------------------------------------|
  31328. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  31329. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  31330. *
  31331. * @usage
  31332. *
  31333. * ```
  31334. * <ANY ng-switch="expression">
  31335. * <ANY ng-switch-when="matchValue1">...</ANY>
  31336. * <ANY ng-switch-when="matchValue2">...</ANY>
  31337. * <ANY ng-switch-default>...</ANY>
  31338. * </ANY>
  31339. * ```
  31340. *
  31341. *
  31342. * @scope
  31343. * @priority 1200
  31344. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  31345. * On child elements add:
  31346. *
  31347. * * `ngSwitchWhen`: the case statement to match against. If match then this
  31348. * case will be displayed. If the same match appears multiple times, all the
  31349. * elements will be displayed. It is possible to associate multiple values to
  31350. * the same `ngSwitchWhen` by defining the optional attribute
  31351. * `ngSwitchWhenSeparator`. The separator will be used to split the value of
  31352. * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
  31353. * if any of the `ngSwitch` evaluates to any of these tokens.
  31354. * * `ngSwitchDefault`: the default case when no other case match. If there
  31355. * are multiple default cases, all of them will be displayed when no other
  31356. * case match.
  31357. *
  31358. *
  31359. * @example
  31360. <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
  31361. <file name="index.html">
  31362. <div ng-controller="ExampleController">
  31363. <select ng-model="selection" ng-options="item for item in items">
  31364. </select>
  31365. <code>selection={{selection}}</code>
  31366. <hr/>
  31367. <div class="animate-switch-container"
  31368. ng-switch on="selection">
  31369. <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
  31370. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  31371. <div class="animate-switch" ng-switch-default>default</div>
  31372. </div>
  31373. </div>
  31374. </file>
  31375. <file name="script.js">
  31376. angular.module('switchExample', ['ngAnimate'])
  31377. .controller('ExampleController', ['$scope', function($scope) {
  31378. $scope.items = ['settings', 'home', 'options', 'other'];
  31379. $scope.selection = $scope.items[0];
  31380. }]);
  31381. </file>
  31382. <file name="animations.css">
  31383. .animate-switch-container {
  31384. position:relative;
  31385. background:white;
  31386. border:1px solid black;
  31387. height:40px;
  31388. overflow:hidden;
  31389. }
  31390. .animate-switch {
  31391. padding:10px;
  31392. }
  31393. .animate-switch.ng-animate {
  31394. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  31395. position:absolute;
  31396. top:0;
  31397. left:0;
  31398. right:0;
  31399. bottom:0;
  31400. }
  31401. .animate-switch.ng-leave.ng-leave-active,
  31402. .animate-switch.ng-enter {
  31403. top:-50px;
  31404. }
  31405. .animate-switch.ng-leave,
  31406. .animate-switch.ng-enter.ng-enter-active {
  31407. top:0;
  31408. }
  31409. </file>
  31410. <file name="protractor.js" type="protractor">
  31411. var switchElem = element(by.css('[ng-switch]'));
  31412. var select = element(by.model('selection'));
  31413. it('should start in settings', function() {
  31414. expect(switchElem.getText()).toMatch(/Settings Div/);
  31415. });
  31416. it('should change to home', function() {
  31417. select.all(by.css('option')).get(1).click();
  31418. expect(switchElem.getText()).toMatch(/Home Span/);
  31419. });
  31420. it('should change to settings via "options"', function() {
  31421. select.all(by.css('option')).get(2).click();
  31422. expect(switchElem.getText()).toMatch(/Settings Div/);
  31423. });
  31424. it('should select default', function() {
  31425. select.all(by.css('option')).get(3).click();
  31426. expect(switchElem.getText()).toMatch(/default/);
  31427. });
  31428. </file>
  31429. </example>
  31430. */
  31431. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  31432. return {
  31433. require: 'ngSwitch',
  31434. // asks for $scope to fool the BC controller module
  31435. controller: ['$scope', function NgSwitchController() {
  31436. this.cases = {};
  31437. }],
  31438. link: function(scope, element, attr, ngSwitchController) {
  31439. var watchExpr = attr.ngSwitch || attr.on,
  31440. selectedTranscludes = [],
  31441. selectedElements = [],
  31442. previousLeaveAnimations = [],
  31443. selectedScopes = [];
  31444. var spliceFactory = function(array, index) {
  31445. return function(response) {
  31446. if (response !== false) array.splice(index, 1);
  31447. };
  31448. };
  31449. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  31450. var i, ii;
  31451. // Start with the last, in case the array is modified during the loop
  31452. while (previousLeaveAnimations.length) {
  31453. $animate.cancel(previousLeaveAnimations.pop());
  31454. }
  31455. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  31456. var selected = getBlockNodes(selectedElements[i].clone);
  31457. selectedScopes[i].$destroy();
  31458. var runner = previousLeaveAnimations[i] = $animate.leave(selected);
  31459. runner.done(spliceFactory(previousLeaveAnimations, i));
  31460. }
  31461. selectedElements.length = 0;
  31462. selectedScopes.length = 0;
  31463. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  31464. forEach(selectedTranscludes, function(selectedTransclude) {
  31465. selectedTransclude.transclude(function(caseElement, selectedScope) {
  31466. selectedScopes.push(selectedScope);
  31467. var anchor = selectedTransclude.element;
  31468. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  31469. var block = { clone: caseElement };
  31470. selectedElements.push(block);
  31471. $animate.enter(caseElement, anchor.parent(), anchor);
  31472. });
  31473. });
  31474. }
  31475. });
  31476. }
  31477. };
  31478. }];
  31479. var ngSwitchWhenDirective = ngDirective({
  31480. transclude: 'element',
  31481. priority: 1200,
  31482. require: '^ngSwitch',
  31483. multiElement: true,
  31484. link: function(scope, element, attrs, ctrl, $transclude) {
  31485. var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
  31486. // Filter duplicate cases
  31487. function(element, index, array) { return array[index - 1] !== element; }
  31488. );
  31489. forEach(cases, function(whenCase) {
  31490. ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
  31491. ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
  31492. });
  31493. }
  31494. });
  31495. var ngSwitchDefaultDirective = ngDirective({
  31496. transclude: 'element',
  31497. priority: 1200,
  31498. require: '^ngSwitch',
  31499. multiElement: true,
  31500. link: function(scope, element, attr, ctrl, $transclude) {
  31501. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  31502. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  31503. }
  31504. });
  31505. /**
  31506. * @ngdoc directive
  31507. * @name ngTransclude
  31508. * @restrict EAC
  31509. *
  31510. * @description
  31511. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  31512. *
  31513. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  31514. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  31515. *
  31516. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  31517. * content of this element will be removed before the transcluded content is inserted.
  31518. * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback
  31519. * content in the case that no transcluded content is provided.
  31520. *
  31521. * @element ANY
  31522. *
  31523. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  31524. * or its value is the same as the name of the attribute then the default slot is used.
  31525. *
  31526. * @example
  31527. * ### Basic transclusion
  31528. * This example demonstrates basic transclusion of content into a component directive.
  31529. * <example name="simpleTranscludeExample" module="transcludeExample">
  31530. * <file name="index.html">
  31531. * <script>
  31532. * angular.module('transcludeExample', [])
  31533. * .directive('pane', function(){
  31534. * return {
  31535. * restrict: 'E',
  31536. * transclude: true,
  31537. * scope: { title:'@' },
  31538. * template: '<div style="border: 1px solid black;">' +
  31539. * '<div style="background-color: gray">{{title}}</div>' +
  31540. * '<ng-transclude></ng-transclude>' +
  31541. * '</div>'
  31542. * };
  31543. * })
  31544. * .controller('ExampleController', ['$scope', function($scope) {
  31545. * $scope.title = 'Lorem Ipsum';
  31546. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  31547. * }]);
  31548. * </script>
  31549. * <div ng-controller="ExampleController">
  31550. * <input ng-model="title" aria-label="title"> <br/>
  31551. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  31552. * <pane title="{{title}}"><span>{{text}}</span></pane>
  31553. * </div>
  31554. * </file>
  31555. * <file name="protractor.js" type="protractor">
  31556. * it('should have transcluded', function() {
  31557. * var titleElement = element(by.model('title'));
  31558. * titleElement.clear();
  31559. * titleElement.sendKeys('TITLE');
  31560. * var textElement = element(by.model('text'));
  31561. * textElement.clear();
  31562. * textElement.sendKeys('TEXT');
  31563. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  31564. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  31565. * });
  31566. * </file>
  31567. * </example>
  31568. *
  31569. * @example
  31570. * ### Transclude fallback content
  31571. * This example shows how to use `NgTransclude` with fallback content, that
  31572. * is displayed if no transcluded content is provided.
  31573. *
  31574. * <example module="transcludeFallbackContentExample" name="ng-transclude">
  31575. * <file name="index.html">
  31576. * <script>
  31577. * angular.module('transcludeFallbackContentExample', [])
  31578. * .directive('myButton', function(){
  31579. * return {
  31580. * restrict: 'E',
  31581. * transclude: true,
  31582. * scope: true,
  31583. * template: '<button style="cursor: pointer;">' +
  31584. * '<ng-transclude>' +
  31585. * '<b style="color: red;">Button1</b>' +
  31586. * '</ng-transclude>' +
  31587. * '</button>'
  31588. * };
  31589. * });
  31590. * </script>
  31591. * <!-- fallback button content -->
  31592. * <my-button id="fallback"></my-button>
  31593. * <!-- modified button content -->
  31594. * <my-button id="modified">
  31595. * <i style="color: green;">Button2</i>
  31596. * </my-button>
  31597. * </file>
  31598. * <file name="protractor.js" type="protractor">
  31599. * it('should have different transclude element content', function() {
  31600. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  31601. * expect(element(by.id('modified')).getText()).toBe('Button2');
  31602. * });
  31603. * </file>
  31604. * </example>
  31605. *
  31606. * @example
  31607. * ### Multi-slot transclusion
  31608. * This example demonstrates using multi-slot transclusion in a component directive.
  31609. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  31610. * <file name="index.html">
  31611. * <style>
  31612. * .title, .footer {
  31613. * background-color: gray
  31614. * }
  31615. * </style>
  31616. * <div ng-controller="ExampleController">
  31617. * <input ng-model="title" aria-label="title"> <br/>
  31618. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  31619. * <pane>
  31620. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  31621. * <pane-body><p>{{text}}</p></pane-body>
  31622. * </pane>
  31623. * </div>
  31624. * </file>
  31625. * <file name="app.js">
  31626. * angular.module('multiSlotTranscludeExample', [])
  31627. * .directive('pane', function() {
  31628. * return {
  31629. * restrict: 'E',
  31630. * transclude: {
  31631. * 'title': '?paneTitle',
  31632. * 'body': 'paneBody',
  31633. * 'footer': '?paneFooter'
  31634. * },
  31635. * template: '<div style="border: 1px solid black;">' +
  31636. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  31637. * '<div ng-transclude="body"></div>' +
  31638. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  31639. * '</div>'
  31640. * };
  31641. * })
  31642. * .controller('ExampleController', ['$scope', function($scope) {
  31643. * $scope.title = 'Lorem Ipsum';
  31644. * $scope.link = 'https://google.com';
  31645. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  31646. * }]);
  31647. * </file>
  31648. * <file name="protractor.js" type="protractor">
  31649. * it('should have transcluded the title and the body', function() {
  31650. * var titleElement = element(by.model('title'));
  31651. * titleElement.clear();
  31652. * titleElement.sendKeys('TITLE');
  31653. * var textElement = element(by.model('text'));
  31654. * textElement.clear();
  31655. * textElement.sendKeys('TEXT');
  31656. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  31657. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  31658. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  31659. * });
  31660. * </file>
  31661. * </example>
  31662. */
  31663. var ngTranscludeMinErr = minErr('ngTransclude');
  31664. var ngTranscludeDirective = ['$compile', function($compile) {
  31665. return {
  31666. restrict: 'EAC',
  31667. compile: function ngTranscludeCompile(tElement) {
  31668. // Remove and cache any original content to act as a fallback
  31669. var fallbackLinkFn = $compile(tElement.contents());
  31670. tElement.empty();
  31671. return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
  31672. if (!$transclude) {
  31673. throw ngTranscludeMinErr('orphan',
  31674. 'Illegal use of ngTransclude directive in the template! ' +
  31675. 'No parent directive that requires a transclusion found. ' +
  31676. 'Element: {0}',
  31677. startingTag($element));
  31678. }
  31679. // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
  31680. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  31681. $attrs.ngTransclude = '';
  31682. }
  31683. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  31684. // If the slot is required and no transclusion content is provided then this call will throw an error
  31685. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  31686. // If the slot is optional and no transclusion content is provided then use the fallback content
  31687. if (slotName && !$transclude.isSlotFilled(slotName)) {
  31688. useFallbackContent();
  31689. }
  31690. function ngTranscludeCloneAttachFn(clone, transcludedScope) {
  31691. if (clone.length && notWhitespace(clone)) {
  31692. $element.append(clone);
  31693. } else {
  31694. useFallbackContent();
  31695. // There is nothing linked against the transcluded scope since no content was available,
  31696. // so it should be safe to clean up the generated scope.
  31697. transcludedScope.$destroy();
  31698. }
  31699. }
  31700. function useFallbackContent() {
  31701. // Since this is the fallback content rather than the transcluded content,
  31702. // we link against the scope of this directive rather than the transcluded scope
  31703. fallbackLinkFn($scope, function(clone) {
  31704. $element.append(clone);
  31705. });
  31706. }
  31707. function notWhitespace(nodes) {
  31708. for (var i = 0, ii = nodes.length; i < ii; i++) {
  31709. var node = nodes[i];
  31710. if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) {
  31711. return true;
  31712. }
  31713. }
  31714. }
  31715. };
  31716. }
  31717. };
  31718. }];
  31719. /**
  31720. * @ngdoc directive
  31721. * @name script
  31722. * @restrict E
  31723. *
  31724. * @description
  31725. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  31726. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  31727. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  31728. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  31729. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  31730. *
  31731. * @param {string} type Must be set to `'text/ng-template'`.
  31732. * @param {string} id Cache name of the template.
  31733. *
  31734. * @example
  31735. <example name="script-tag">
  31736. <file name="index.html">
  31737. <script type="text/ng-template" id="/tpl.html">
  31738. Content of the template.
  31739. </script>
  31740. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  31741. <div id="tpl-content" ng-include src="currentTpl"></div>
  31742. </file>
  31743. <file name="protractor.js" type="protractor">
  31744. it('should load template defined inside script tag', function() {
  31745. element(by.css('#tpl-link')).click();
  31746. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  31747. });
  31748. </file>
  31749. </example>
  31750. */
  31751. var scriptDirective = ['$templateCache', function($templateCache) {
  31752. return {
  31753. restrict: 'E',
  31754. terminal: true,
  31755. compile: function(element, attr) {
  31756. if (attr.type === 'text/ng-template') {
  31757. var templateUrl = attr.id,
  31758. text = element[0].text;
  31759. $templateCache.put(templateUrl, text);
  31760. }
  31761. }
  31762. };
  31763. }];
  31764. /* exported selectDirective, optionDirective */
  31765. var noopNgModelController = { $setViewValue: noop, $render: noop };
  31766. function setOptionSelectedStatus(optionEl, value) {
  31767. optionEl.prop('selected', value);
  31768. /**
  31769. * When unselecting an option, setting the property to null / false should be enough
  31770. * However, screenreaders might react to the selected attribute instead, see
  31771. * https://github.com/angular/angular.js/issues/14419
  31772. * Note: "selected" is a boolean attr and will be removed when the "value" arg in attr() is false
  31773. * or null
  31774. */
  31775. optionEl.attr('selected', value);
  31776. }
  31777. /**
  31778. * @ngdoc type
  31779. * @name select.SelectController
  31780. *
  31781. * @description
  31782. * The controller for the {@link ng.select select} directive. The controller exposes
  31783. * a few utility methods that can be used to augment the behavior of a regular or an
  31784. * {@link ng.ngOptions ngOptions} select element.
  31785. *
  31786. * @example
  31787. * ### Set a custom error when the unknown option is selected
  31788. *
  31789. * This example sets a custom error "unknownValue" on the ngModelController
  31790. * when the select element's unknown option is selected, i.e. when the model is set to a value
  31791. * that is not matched by any option.
  31792. *
  31793. * <example name="select-unknown-value-error" module="staticSelect">
  31794. * <file name="index.html">
  31795. * <div ng-controller="ExampleController">
  31796. * <form name="myForm">
  31797. * <label for="testSelect"> Single select: </label><br>
  31798. * <select name="testSelect" ng-model="selected" unknown-value-error>
  31799. * <option value="option-1">Option 1</option>
  31800. * <option value="option-2">Option 2</option>
  31801. * </select><br>
  31802. * <span class="error" ng-if="myForm.testSelect.$error.unknownValue">
  31803. * Error: The current model doesn't match any option</span><br>
  31804. *
  31805. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  31806. * </form>
  31807. * </div>
  31808. * </file>
  31809. * <file name="app.js">
  31810. * angular.module('staticSelect', [])
  31811. * .controller('ExampleController', ['$scope', function($scope) {
  31812. * $scope.selected = null;
  31813. *
  31814. * $scope.forceUnknownOption = function() {
  31815. * $scope.selected = 'nonsense';
  31816. * };
  31817. * }])
  31818. * .directive('unknownValueError', function() {
  31819. * return {
  31820. * require: ['ngModel', 'select'],
  31821. * link: function(scope, element, attrs, ctrls) {
  31822. * var ngModelCtrl = ctrls[0];
  31823. * var selectCtrl = ctrls[1];
  31824. *
  31825. * ngModelCtrl.$validators.unknownValue = function(modelValue, viewValue) {
  31826. * if (selectCtrl.$isUnknownOptionSelected()) {
  31827. * return false;
  31828. * }
  31829. *
  31830. * return true;
  31831. * };
  31832. * }
  31833. *
  31834. * };
  31835. * });
  31836. * </file>
  31837. *</example>
  31838. *
  31839. *
  31840. * @example
  31841. * ### Set the "required" error when the unknown option is selected.
  31842. *
  31843. * By default, the "required" error on the ngModelController is only set on a required select
  31844. * when the empty option is selected. This example adds a custom directive that also sets the
  31845. * error when the unknown option is selected.
  31846. *
  31847. * <example name="select-unknown-value-required" module="staticSelect">
  31848. * <file name="index.html">
  31849. * <div ng-controller="ExampleController">
  31850. * <form name="myForm">
  31851. * <label for="testSelect"> Select: </label><br>
  31852. * <select name="testSelect" ng-model="selected" required unknown-value-required>
  31853. * <option value="option-1">Option 1</option>
  31854. * <option value="option-2">Option 2</option>
  31855. * </select><br>
  31856. * <span class="error" ng-if="myForm.testSelect.$error.required">Error: Please select a value</span><br>
  31857. *
  31858. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  31859. * </form>
  31860. * </div>
  31861. * </file>
  31862. * <file name="app.js">
  31863. * angular.module('staticSelect', [])
  31864. * .controller('ExampleController', ['$scope', function($scope) {
  31865. * $scope.selected = null;
  31866. *
  31867. * $scope.forceUnknownOption = function() {
  31868. * $scope.selected = 'nonsense';
  31869. * };
  31870. * }])
  31871. * .directive('unknownValueRequired', function() {
  31872. * return {
  31873. * priority: 1, // This directive must run after the required directive has added its validator
  31874. * require: ['ngModel', 'select'],
  31875. * link: function(scope, element, attrs, ctrls) {
  31876. * var ngModelCtrl = ctrls[0];
  31877. * var selectCtrl = ctrls[1];
  31878. *
  31879. * var originalRequiredValidator = ngModelCtrl.$validators.required;
  31880. *
  31881. * ngModelCtrl.$validators.required = function() {
  31882. * if (attrs.required && selectCtrl.$isUnknownOptionSelected()) {
  31883. * return false;
  31884. * }
  31885. *
  31886. * return originalRequiredValidator.apply(this, arguments);
  31887. * };
  31888. * }
  31889. * };
  31890. * });
  31891. * </file>
  31892. * <file name="protractor.js" type="protractor">
  31893. * it('should show the error message when the unknown option is selected', function() {
  31894. var error = element(by.className('error'));
  31895. expect(error.getText()).toBe('Error: Please select a value');
  31896. element(by.cssContainingText('option', 'Option 1')).click();
  31897. expect(error.isPresent()).toBe(false);
  31898. element(by.tagName('button')).click();
  31899. expect(error.getText()).toBe('Error: Please select a value');
  31900. });
  31901. * </file>
  31902. *</example>
  31903. *
  31904. *
  31905. */
  31906. var SelectController =
  31907. ['$element', '$scope', /** @this */ function($element, $scope) {
  31908. var self = this,
  31909. optionsMap = new NgMap();
  31910. self.selectValueMap = {}; // Keys are the hashed values, values the original values
  31911. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  31912. self.ngModelCtrl = noopNgModelController;
  31913. self.multiple = false;
  31914. // The "unknown" option is one that is prepended to the list if the viewValue
  31915. // does not match any of the options. When it is rendered the value of the unknown
  31916. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  31917. //
  31918. // Support: IE 9 only
  31919. // We can't just jqLite('<option>') since jqLite is not smart enough
  31920. // to create it in <select> and IE barfs otherwise.
  31921. self.unknownOption = jqLite(window.document.createElement('option'));
  31922. // The empty option is an option with the value '' that the application developer can
  31923. // provide inside the select. It is always selectable and indicates that a "null" selection has
  31924. // been made by the user.
  31925. // If the select has an empty option, and the model of the select is set to "undefined" or "null",
  31926. // the empty option is selected.
  31927. // If the model is set to a different unmatched value, the unknown option is rendered and
  31928. // selected, i.e both are present, because a "null" selection and an unknown value are different.
  31929. self.hasEmptyOption = false;
  31930. self.emptyOption = undefined;
  31931. self.renderUnknownOption = function(val) {
  31932. var unknownVal = self.generateUnknownOptionValue(val);
  31933. self.unknownOption.val(unknownVal);
  31934. $element.prepend(self.unknownOption);
  31935. setOptionSelectedStatus(self.unknownOption, true);
  31936. $element.val(unknownVal);
  31937. };
  31938. self.updateUnknownOption = function(val) {
  31939. var unknownVal = self.generateUnknownOptionValue(val);
  31940. self.unknownOption.val(unknownVal);
  31941. setOptionSelectedStatus(self.unknownOption, true);
  31942. $element.val(unknownVal);
  31943. };
  31944. self.generateUnknownOptionValue = function(val) {
  31945. return '? ' + hashKey(val) + ' ?';
  31946. };
  31947. self.removeUnknownOption = function() {
  31948. if (self.unknownOption.parent()) self.unknownOption.remove();
  31949. };
  31950. self.selectEmptyOption = function() {
  31951. if (self.emptyOption) {
  31952. $element.val('');
  31953. setOptionSelectedStatus(self.emptyOption, true);
  31954. }
  31955. };
  31956. self.unselectEmptyOption = function() {
  31957. if (self.hasEmptyOption) {
  31958. setOptionSelectedStatus(self.emptyOption, false);
  31959. }
  31960. };
  31961. $scope.$on('$destroy', function() {
  31962. // disable unknown option so that we don't do work when the whole select is being destroyed
  31963. self.renderUnknownOption = noop;
  31964. });
  31965. // Read the value of the select control, the implementation of this changes depending
  31966. // upon whether the select can have multiple values and whether ngOptions is at work.
  31967. self.readValue = function readSingleValue() {
  31968. var val = $element.val();
  31969. // ngValue added option values are stored in the selectValueMap, normal interpolations are not
  31970. var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;
  31971. if (self.hasOption(realVal)) {
  31972. return realVal;
  31973. }
  31974. return null;
  31975. };
  31976. // Write the value to the select control, the implementation of this changes depending
  31977. // upon whether the select can have multiple values and whether ngOptions is at work.
  31978. self.writeValue = function writeSingleValue(value) {
  31979. // Make sure to remove the selected attribute from the previously selected option
  31980. // Otherwise, screen readers might get confused
  31981. var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];
  31982. if (currentlySelectedOption) setOptionSelectedStatus(jqLite(currentlySelectedOption), false);
  31983. if (self.hasOption(value)) {
  31984. self.removeUnknownOption();
  31985. var hashedVal = hashKey(value);
  31986. $element.val(hashedVal in self.selectValueMap ? hashedVal : value);
  31987. // Set selected attribute and property on selected option for screen readers
  31988. var selectedOption = $element[0].options[$element[0].selectedIndex];
  31989. setOptionSelectedStatus(jqLite(selectedOption), true);
  31990. } else {
  31991. self.selectUnknownOrEmptyOption(value);
  31992. }
  31993. };
  31994. // Tell the select control that an option, with the given value, has been added
  31995. self.addOption = function(value, element) {
  31996. // Skip comment nodes, as they only pollute the `optionsMap`
  31997. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  31998. assertNotHasOwnProperty(value, '"option value"');
  31999. if (value === '') {
  32000. self.hasEmptyOption = true;
  32001. self.emptyOption = element;
  32002. }
  32003. var count = optionsMap.get(value) || 0;
  32004. optionsMap.set(value, count + 1);
  32005. // Only render at the end of a digest. This improves render performance when many options
  32006. // are added during a digest and ensures all relevant options are correctly marked as selected
  32007. scheduleRender();
  32008. };
  32009. // Tell the select control that an option, with the given value, has been removed
  32010. self.removeOption = function(value) {
  32011. var count = optionsMap.get(value);
  32012. if (count) {
  32013. if (count === 1) {
  32014. optionsMap.delete(value);
  32015. if (value === '') {
  32016. self.hasEmptyOption = false;
  32017. self.emptyOption = undefined;
  32018. }
  32019. } else {
  32020. optionsMap.set(value, count - 1);
  32021. }
  32022. }
  32023. };
  32024. // Check whether the select control has an option matching the given value
  32025. self.hasOption = function(value) {
  32026. return !!optionsMap.get(value);
  32027. };
  32028. /**
  32029. * @ngdoc method
  32030. * @name select.SelectController#$hasEmptyOption
  32031. *
  32032. * @description
  32033. *
  32034. * Returns `true` if the select element currently has an empty option
  32035. * element, i.e. an option that signifies that the select is empty / the selection is null.
  32036. *
  32037. */
  32038. self.$hasEmptyOption = function() {
  32039. return self.hasEmptyOption;
  32040. };
  32041. /**
  32042. * @ngdoc method
  32043. * @name select.SelectController#$isUnknownOptionSelected
  32044. *
  32045. * @description
  32046. *
  32047. * Returns `true` if the select element's unknown option is selected. The unknown option is added
  32048. * and automatically selected whenever the select model doesn't match any option.
  32049. *
  32050. */
  32051. self.$isUnknownOptionSelected = function() {
  32052. // Presence of the unknown option means it is selected
  32053. return $element[0].options[0] === self.unknownOption[0];
  32054. };
  32055. /**
  32056. * @ngdoc method
  32057. * @name select.SelectController#$isEmptyOptionSelected
  32058. *
  32059. * @description
  32060. *
  32061. * Returns `true` if the select element has an empty option and this empty option is currently
  32062. * selected. Returns `false` if the select element has no empty option or it is not selected.
  32063. *
  32064. */
  32065. self.$isEmptyOptionSelected = function() {
  32066. return self.hasEmptyOption && $element[0].options[$element[0].selectedIndex] === self.emptyOption[0];
  32067. };
  32068. self.selectUnknownOrEmptyOption = function(value) {
  32069. if (value == null && self.emptyOption) {
  32070. self.removeUnknownOption();
  32071. self.selectEmptyOption();
  32072. } else if (self.unknownOption.parent().length) {
  32073. self.updateUnknownOption(value);
  32074. } else {
  32075. self.renderUnknownOption(value);
  32076. }
  32077. };
  32078. var renderScheduled = false;
  32079. function scheduleRender() {
  32080. if (renderScheduled) return;
  32081. renderScheduled = true;
  32082. $scope.$$postDigest(function() {
  32083. renderScheduled = false;
  32084. self.ngModelCtrl.$render();
  32085. });
  32086. }
  32087. var updateScheduled = false;
  32088. function scheduleViewValueUpdate(renderAfter) {
  32089. if (updateScheduled) return;
  32090. updateScheduled = true;
  32091. $scope.$$postDigest(function() {
  32092. if ($scope.$$destroyed) return;
  32093. updateScheduled = false;
  32094. self.ngModelCtrl.$setViewValue(self.readValue());
  32095. if (renderAfter) self.ngModelCtrl.$render();
  32096. });
  32097. }
  32098. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  32099. if (optionAttrs.$attr.ngValue) {
  32100. // The value attribute is set by ngValue
  32101. var oldVal, hashedVal;
  32102. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  32103. var removal;
  32104. var previouslySelected = optionElement.prop('selected');
  32105. if (isDefined(hashedVal)) {
  32106. self.removeOption(oldVal);
  32107. delete self.selectValueMap[hashedVal];
  32108. removal = true;
  32109. }
  32110. hashedVal = hashKey(newVal);
  32111. oldVal = newVal;
  32112. self.selectValueMap[hashedVal] = newVal;
  32113. self.addOption(newVal, optionElement);
  32114. // Set the attribute directly instead of using optionAttrs.$set - this stops the observer
  32115. // from firing a second time. Other $observers on value will also get the result of the
  32116. // ngValue expression, not the hashed value
  32117. optionElement.attr('value', hashedVal);
  32118. if (removal && previouslySelected) {
  32119. scheduleViewValueUpdate();
  32120. }
  32121. });
  32122. } else if (interpolateValueFn) {
  32123. // The value attribute is interpolated
  32124. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  32125. // This method is overwritten in ngOptions and has side-effects!
  32126. self.readValue();
  32127. var removal;
  32128. var previouslySelected = optionElement.prop('selected');
  32129. if (isDefined(oldVal)) {
  32130. self.removeOption(oldVal);
  32131. removal = true;
  32132. }
  32133. oldVal = newVal;
  32134. self.addOption(newVal, optionElement);
  32135. if (removal && previouslySelected) {
  32136. scheduleViewValueUpdate();
  32137. }
  32138. });
  32139. } else if (interpolateTextFn) {
  32140. // The text content is interpolated
  32141. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  32142. optionAttrs.$set('value', newVal);
  32143. var previouslySelected = optionElement.prop('selected');
  32144. if (oldVal !== newVal) {
  32145. self.removeOption(oldVal);
  32146. }
  32147. self.addOption(newVal, optionElement);
  32148. if (oldVal && previouslySelected) {
  32149. scheduleViewValueUpdate();
  32150. }
  32151. });
  32152. } else {
  32153. // The value attribute is static
  32154. self.addOption(optionAttrs.value, optionElement);
  32155. }
  32156. optionAttrs.$observe('disabled', function(newVal) {
  32157. // Since model updates will also select disabled options (like ngOptions),
  32158. // we only have to handle options becoming disabled, not enabled
  32159. if (newVal === 'true' || newVal && optionElement.prop('selected')) {
  32160. if (self.multiple) {
  32161. scheduleViewValueUpdate(true);
  32162. } else {
  32163. self.ngModelCtrl.$setViewValue(null);
  32164. self.ngModelCtrl.$render();
  32165. }
  32166. }
  32167. });
  32168. optionElement.on('$destroy', function() {
  32169. var currentValue = self.readValue();
  32170. var removeValue = optionAttrs.value;
  32171. self.removeOption(removeValue);
  32172. scheduleRender();
  32173. if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
  32174. currentValue === removeValue
  32175. ) {
  32176. // When multiple (selected) options are destroyed at the same time, we don't want
  32177. // to run a model update for each of them. Instead, run a single update in the $$postDigest
  32178. scheduleViewValueUpdate(true);
  32179. }
  32180. });
  32181. };
  32182. }];
  32183. /**
  32184. * @ngdoc directive
  32185. * @name select
  32186. * @restrict E
  32187. *
  32188. * @description
  32189. * HTML `select` element with AngularJS data-binding.
  32190. *
  32191. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  32192. * between the scope and the `<select>` control (including setting default values).
  32193. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  32194. * {@link ngOptions `ngOptions`} directives.
  32195. *
  32196. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  32197. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  32198. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  32199. * Value and textContent can be interpolated.
  32200. *
  32201. * The {@link select.SelectController select controller} exposes utility functions that can be used
  32202. * to manipulate the select's behavior.
  32203. *
  32204. * ## Matching model and option values
  32205. *
  32206. * In general, the match between the model and an option is evaluated by strictly comparing the model
  32207. * value against the value of the available options.
  32208. *
  32209. * If you are setting the option value with the option's `value` attribute, or textContent, the
  32210. * value will always be a `string` which means that the model value must also be a string.
  32211. * Otherwise the `select` directive cannot match them correctly.
  32212. *
  32213. * To bind the model to a non-string value, you can use one of the following strategies:
  32214. * - the {@link ng.ngOptions `ngOptions`} directive
  32215. * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value})
  32216. * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be
  32217. * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example})
  32218. * - model $parsers / $formatters to convert the string value
  32219. * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example})
  32220. *
  32221. * If the viewValue of `ngModel` does not match any of the options, then the control
  32222. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  32223. *
  32224. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  32225. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  32226. * option. See example below for demonstration.
  32227. *
  32228. * ## Choosing between `ngRepeat` and `ngOptions`
  32229. *
  32230. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  32231. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits:
  32232. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  32233. * comprehension expression
  32234. * - reduced memory consumption by not creating a new scope for each repeated instance
  32235. * - increased render speed by creating the options in a documentFragment instead of individually
  32236. *
  32237. * Specifically, select with repeated options slows down significantly starting at 2000 options in
  32238. * Chrome and Internet Explorer / Edge.
  32239. *
  32240. *
  32241. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  32242. * @param {string=} name Property name of the form under which the control is published.
  32243. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  32244. * bound to the model as an array.
  32245. * @param {string=} required Sets `required` validation error key if the value is not entered.
  32246. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  32247. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  32248. * when you want to data-bind to the required attribute.
  32249. * @param {string=} ngChange AngularJS expression to be executed when selected option(s) changes due to user
  32250. * interaction with the select element.
  32251. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  32252. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  32253. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  32254. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  32255. *
  32256. *
  32257. * @example
  32258. * ### Simple `select` elements with static options
  32259. *
  32260. * <example name="static-select" module="staticSelect">
  32261. * <file name="index.html">
  32262. * <div ng-controller="ExampleController">
  32263. * <form name="myForm">
  32264. * <label for="singleSelect"> Single select: </label><br>
  32265. * <select name="singleSelect" ng-model="data.singleSelect">
  32266. * <option value="option-1">Option 1</option>
  32267. * <option value="option-2">Option 2</option>
  32268. * </select><br>
  32269. *
  32270. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  32271. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  32272. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  32273. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  32274. * <option value="option-2">Option 2</option>
  32275. * </select><br>
  32276. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  32277. * <tt>singleSelect = {{data.singleSelect}}</tt>
  32278. *
  32279. * <hr>
  32280. * <label for="multipleSelect"> Multiple select: </label><br>
  32281. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  32282. * <option value="option-1">Option 1</option>
  32283. * <option value="option-2">Option 2</option>
  32284. * <option value="option-3">Option 3</option>
  32285. * </select><br>
  32286. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  32287. * </form>
  32288. * </div>
  32289. * </file>
  32290. * <file name="app.js">
  32291. * angular.module('staticSelect', [])
  32292. * .controller('ExampleController', ['$scope', function($scope) {
  32293. * $scope.data = {
  32294. * singleSelect: null,
  32295. * multipleSelect: [],
  32296. * option1: 'option-1'
  32297. * };
  32298. *
  32299. * $scope.forceUnknownOption = function() {
  32300. * $scope.data.singleSelect = 'nonsense';
  32301. * };
  32302. * }]);
  32303. * </file>
  32304. *</example>
  32305. *
  32306. * @example
  32307. * ### Using `ngRepeat` to generate `select` options
  32308. * <example name="select-ngrepeat" module="ngrepeatSelect">
  32309. * <file name="index.html">
  32310. * <div ng-controller="ExampleController">
  32311. * <form name="myForm">
  32312. * <label for="repeatSelect"> Repeat select: </label>
  32313. * <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  32314. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  32315. * </select>
  32316. * </form>
  32317. * <hr>
  32318. * <tt>model = {{data.model}}</tt><br/>
  32319. * </div>
  32320. * </file>
  32321. * <file name="app.js">
  32322. * angular.module('ngrepeatSelect', [])
  32323. * .controller('ExampleController', ['$scope', function($scope) {
  32324. * $scope.data = {
  32325. * model: null,
  32326. * availableOptions: [
  32327. * {id: '1', name: 'Option A'},
  32328. * {id: '2', name: 'Option B'},
  32329. * {id: '3', name: 'Option C'}
  32330. * ]
  32331. * };
  32332. * }]);
  32333. * </file>
  32334. *</example>
  32335. *
  32336. * @example
  32337. * ### Using `ngValue` to bind the model to an array of objects
  32338. * <example name="select-ngvalue" module="ngvalueSelect">
  32339. * <file name="index.html">
  32340. * <div ng-controller="ExampleController">
  32341. * <form name="myForm">
  32342. * <label for="ngvalueselect"> ngvalue select: </label>
  32343. * <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
  32344. * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
  32345. * </select>
  32346. * </form>
  32347. * <hr>
  32348. * <pre>model = {{data.model | json}}</pre><br/>
  32349. * </div>
  32350. * </file>
  32351. * <file name="app.js">
  32352. * angular.module('ngvalueSelect', [])
  32353. * .controller('ExampleController', ['$scope', function($scope) {
  32354. * $scope.data = {
  32355. * model: null,
  32356. * availableOptions: [
  32357. {value: 'myString', name: 'string'},
  32358. {value: 1, name: 'integer'},
  32359. {value: true, name: 'boolean'},
  32360. {value: null, name: 'null'},
  32361. {value: {prop: 'value'}, name: 'object'},
  32362. {value: ['a'], name: 'array'}
  32363. * ]
  32364. * };
  32365. * }]);
  32366. * </file>
  32367. *</example>
  32368. *
  32369. * @example
  32370. * ### Using `select` with `ngOptions` and setting a default value
  32371. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  32372. *
  32373. * <example name="select-with-default-values" module="defaultValueSelect">
  32374. * <file name="index.html">
  32375. * <div ng-controller="ExampleController">
  32376. * <form name="myForm">
  32377. * <label for="mySelect">Make a choice:</label>
  32378. * <select name="mySelect" id="mySelect"
  32379. * ng-options="option.name for option in data.availableOptions track by option.id"
  32380. * ng-model="data.selectedOption"></select>
  32381. * </form>
  32382. * <hr>
  32383. * <tt>option = {{data.selectedOption}}</tt><br/>
  32384. * </div>
  32385. * </file>
  32386. * <file name="app.js">
  32387. * angular.module('defaultValueSelect', [])
  32388. * .controller('ExampleController', ['$scope', function($scope) {
  32389. * $scope.data = {
  32390. * availableOptions: [
  32391. * {id: '1', name: 'Option A'},
  32392. * {id: '2', name: 'Option B'},
  32393. * {id: '3', name: 'Option C'}
  32394. * ],
  32395. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  32396. * };
  32397. * }]);
  32398. * </file>
  32399. *</example>
  32400. *
  32401. * @example
  32402. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  32403. *
  32404. * <example name="select-with-non-string-options" module="nonStringSelect">
  32405. * <file name="index.html">
  32406. * <select ng-model="model.id" convert-to-number>
  32407. * <option value="0">Zero</option>
  32408. * <option value="1">One</option>
  32409. * <option value="2">Two</option>
  32410. * </select>
  32411. * {{ model }}
  32412. * </file>
  32413. * <file name="app.js">
  32414. * angular.module('nonStringSelect', [])
  32415. * .run(function($rootScope) {
  32416. * $rootScope.model = { id: 2 };
  32417. * })
  32418. * .directive('convertToNumber', function() {
  32419. * return {
  32420. * require: 'ngModel',
  32421. * link: function(scope, element, attrs, ngModel) {
  32422. * ngModel.$parsers.push(function(val) {
  32423. * return parseInt(val, 10);
  32424. * });
  32425. * ngModel.$formatters.push(function(val) {
  32426. * return '' + val;
  32427. * });
  32428. * }
  32429. * };
  32430. * });
  32431. * </file>
  32432. * <file name="protractor.js" type="protractor">
  32433. * it('should initialize to model', function() {
  32434. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  32435. * });
  32436. * </file>
  32437. * </example>
  32438. *
  32439. */
  32440. var selectDirective = function() {
  32441. return {
  32442. restrict: 'E',
  32443. require: ['select', '?ngModel'],
  32444. controller: SelectController,
  32445. priority: 1,
  32446. link: {
  32447. pre: selectPreLink,
  32448. post: selectPostLink
  32449. }
  32450. };
  32451. function selectPreLink(scope, element, attr, ctrls) {
  32452. var selectCtrl = ctrls[0];
  32453. var ngModelCtrl = ctrls[1];
  32454. // if ngModel is not defined, we don't need to do anything but set the registerOption
  32455. // function to noop, so options don't get added internally
  32456. if (!ngModelCtrl) {
  32457. selectCtrl.registerOption = noop;
  32458. return;
  32459. }
  32460. selectCtrl.ngModelCtrl = ngModelCtrl;
  32461. // When the selected item(s) changes we delegate getting the value of the select control
  32462. // to the `readValue` method, which can be changed if the select can have multiple
  32463. // selected values or if the options are being generated by `ngOptions`
  32464. element.on('change', function() {
  32465. selectCtrl.removeUnknownOption();
  32466. scope.$apply(function() {
  32467. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  32468. });
  32469. });
  32470. // If the select allows multiple values then we need to modify how we read and write
  32471. // values from and to the control; also what it means for the value to be empty and
  32472. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  32473. // doesn't trigger rendering if only an item in the array changes.
  32474. if (attr.multiple) {
  32475. selectCtrl.multiple = true;
  32476. // Read value now needs to check each option to see if it is selected
  32477. selectCtrl.readValue = function readMultipleValue() {
  32478. var array = [];
  32479. forEach(element.find('option'), function(option) {
  32480. if (option.selected && !option.disabled) {
  32481. var val = option.value;
  32482. array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
  32483. }
  32484. });
  32485. return array;
  32486. };
  32487. // Write value now needs to set the selected property of each matching option
  32488. selectCtrl.writeValue = function writeMultipleValue(value) {
  32489. forEach(element.find('option'), function(option) {
  32490. var shouldBeSelected = !!value && (includes(value, option.value) ||
  32491. includes(value, selectCtrl.selectValueMap[option.value]));
  32492. var currentlySelected = option.selected;
  32493. // Support: IE 9-11 only, Edge 12-15+
  32494. // In IE and Edge adding options to the selection via shift+click/UP/DOWN
  32495. // will de-select already selected options if "selected" on those options was set
  32496. // more than once (i.e. when the options were already selected)
  32497. // So we only modify the selected property if necessary.
  32498. // Note: this behavior cannot be replicated via unit tests because it only shows in the
  32499. // actual user interface.
  32500. if (shouldBeSelected !== currentlySelected) {
  32501. setOptionSelectedStatus(jqLite(option), shouldBeSelected);
  32502. }
  32503. });
  32504. };
  32505. // we have to do it on each watch since ngModel watches reference, but
  32506. // we need to work of an array, so we need to see if anything was inserted/removed
  32507. var lastView, lastViewRef = NaN;
  32508. scope.$watch(function selectMultipleWatch() {
  32509. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  32510. lastView = shallowCopy(ngModelCtrl.$viewValue);
  32511. ngModelCtrl.$render();
  32512. }
  32513. lastViewRef = ngModelCtrl.$viewValue;
  32514. });
  32515. // If we are a multiple select then value is now a collection
  32516. // so the meaning of $isEmpty changes
  32517. ngModelCtrl.$isEmpty = function(value) {
  32518. return !value || value.length === 0;
  32519. };
  32520. }
  32521. }
  32522. function selectPostLink(scope, element, attrs, ctrls) {
  32523. // if ngModel is not defined, we don't need to do anything
  32524. var ngModelCtrl = ctrls[1];
  32525. if (!ngModelCtrl) return;
  32526. var selectCtrl = ctrls[0];
  32527. // We delegate rendering to the `writeValue` method, which can be changed
  32528. // if the select can have multiple selected values or if the options are being
  32529. // generated by `ngOptions`.
  32530. // This must be done in the postLink fn to prevent $render to be called before
  32531. // all nodes have been linked correctly.
  32532. ngModelCtrl.$render = function() {
  32533. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  32534. };
  32535. }
  32536. };
  32537. // The option directive is purely designed to communicate the existence (or lack of)
  32538. // of dynamically created (and destroyed) option elements to their containing select
  32539. // directive via its controller.
  32540. var optionDirective = ['$interpolate', function($interpolate) {
  32541. return {
  32542. restrict: 'E',
  32543. priority: 100,
  32544. compile: function(element, attr) {
  32545. var interpolateValueFn, interpolateTextFn;
  32546. if (isDefined(attr.ngValue)) {
  32547. // Will be handled by registerOption
  32548. } else if (isDefined(attr.value)) {
  32549. // If the value attribute is defined, check if it contains an interpolation
  32550. interpolateValueFn = $interpolate(attr.value, true);
  32551. } else {
  32552. // If the value attribute is not defined then we fall back to the
  32553. // text content of the option element, which may be interpolated
  32554. interpolateTextFn = $interpolate(element.text(), true);
  32555. if (!interpolateTextFn) {
  32556. attr.$set('value', element.text());
  32557. }
  32558. }
  32559. return function(scope, element, attr) {
  32560. // This is an optimization over using ^^ since we don't want to have to search
  32561. // all the way to the root of the DOM for every single option element
  32562. var selectCtrlName = '$selectController',
  32563. parent = element.parent(),
  32564. selectCtrl = parent.data(selectCtrlName) ||
  32565. parent.parent().data(selectCtrlName); // in case we are in optgroup
  32566. if (selectCtrl) {
  32567. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  32568. }
  32569. };
  32570. }
  32571. };
  32572. }];
  32573. /**
  32574. * @ngdoc directive
  32575. * @name ngRequired
  32576. * @restrict A
  32577. *
  32578. * @param {expression} ngRequired AngularJS expression. If it evaluates to `true`, it sets the
  32579. * `required` attribute to the element and adds the `required`
  32580. * {@link ngModel.NgModelController#$validators `validator`}.
  32581. *
  32582. * @description
  32583. *
  32584. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  32585. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  32586. * applied to custom controls.
  32587. *
  32588. * The directive sets the `required` attribute on the element if the AngularJS expression inside
  32589. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  32590. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  32591. * for more info.
  32592. *
  32593. * The validator will set the `required` error key to true if the `required` attribute is set and
  32594. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  32595. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  32596. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  32597. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  32598. *
  32599. * @example
  32600. * <example name="ngRequiredDirective" module="ngRequiredExample">
  32601. * <file name="index.html">
  32602. * <script>
  32603. * angular.module('ngRequiredExample', [])
  32604. * .controller('ExampleController', ['$scope', function($scope) {
  32605. * $scope.required = true;
  32606. * }]);
  32607. * </script>
  32608. * <div ng-controller="ExampleController">
  32609. * <form name="form">
  32610. * <label for="required">Toggle required: </label>
  32611. * <input type="checkbox" ng-model="required" id="required" />
  32612. * <br>
  32613. * <label for="input">This input must be filled if `required` is true: </label>
  32614. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  32615. * <hr>
  32616. * required error set? = <code>{{form.input.$error.required}}</code><br>
  32617. * model = <code>{{model}}</code>
  32618. * </form>
  32619. * </div>
  32620. * </file>
  32621. * <file name="protractor.js" type="protractor">
  32622. var required = element(by.binding('form.input.$error.required'));
  32623. var model = element(by.binding('model'));
  32624. var input = element(by.id('input'));
  32625. it('should set the required error', function() {
  32626. expect(required.getText()).toContain('true');
  32627. input.sendKeys('123');
  32628. expect(required.getText()).not.toContain('true');
  32629. expect(model.getText()).toContain('123');
  32630. });
  32631. * </file>
  32632. * </example>
  32633. */
  32634. var requiredDirective = function() {
  32635. return {
  32636. restrict: 'A',
  32637. require: '?ngModel',
  32638. link: function(scope, elm, attr, ctrl) {
  32639. if (!ctrl) return;
  32640. attr.required = true; // force truthy in case we are on non input element
  32641. ctrl.$validators.required = function(modelValue, viewValue) {
  32642. return !attr.required || !ctrl.$isEmpty(viewValue);
  32643. };
  32644. attr.$observe('required', function() {
  32645. ctrl.$validate();
  32646. });
  32647. }
  32648. };
  32649. };
  32650. /**
  32651. * @ngdoc directive
  32652. * @name ngPattern
  32653. * @restrict A
  32654. *
  32655. * @param {expression|RegExp} ngPattern AngularJS expression that must evaluate to a `RegExp` or a `String`
  32656. * parsable into a `RegExp`, or a `RegExp` literal. See above for
  32657. * more details.
  32658. *
  32659. * @description
  32660. *
  32661. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  32662. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  32663. *
  32664. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  32665. * does not match a RegExp which is obtained from the `ngPattern` attribute value:
  32666. * - the value is an AngularJS expression:
  32667. * - If the expression evaluates to a RegExp object, then this is used directly.
  32668. * - If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  32669. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  32670. * - If the value is a RegExp literal, e.g. `ngPattern="/^\d+$/"`, it is used directly.
  32671. *
  32672. * <div class="alert alert-info">
  32673. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  32674. * start at the index of the last search's match, thus not taking the whole input value into
  32675. * account.
  32676. * </div>
  32677. *
  32678. * <div class="alert alert-info">
  32679. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  32680. * differences:
  32681. * <ol>
  32682. * <li>
  32683. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  32684. * not available.
  32685. * </li>
  32686. * <li>
  32687. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  32688. * interpolated.
  32689. * </li>
  32690. * </ol>
  32691. * </div>
  32692. *
  32693. * @example
  32694. * <example name="ngPatternDirective" module="ngPatternExample">
  32695. * <file name="index.html">
  32696. * <script>
  32697. * angular.module('ngPatternExample', [])
  32698. * .controller('ExampleController', ['$scope', function($scope) {
  32699. * $scope.regex = '\\d+';
  32700. * }]);
  32701. * </script>
  32702. * <div ng-controller="ExampleController">
  32703. * <form name="form">
  32704. * <label for="regex">Set a pattern (regex string): </label>
  32705. * <input type="text" ng-model="regex" id="regex" />
  32706. * <br>
  32707. * <label for="input">This input is restricted by the current pattern: </label>
  32708. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  32709. * <hr>
  32710. * input valid? = <code>{{form.input.$valid}}</code><br>
  32711. * model = <code>{{model}}</code>
  32712. * </form>
  32713. * </div>
  32714. * </file>
  32715. * <file name="protractor.js" type="protractor">
  32716. var model = element(by.binding('model'));
  32717. var input = element(by.id('input'));
  32718. it('should validate the input with the default pattern', function() {
  32719. input.sendKeys('aaa');
  32720. expect(model.getText()).not.toContain('aaa');
  32721. input.clear().then(function() {
  32722. input.sendKeys('123');
  32723. expect(model.getText()).toContain('123');
  32724. });
  32725. });
  32726. * </file>
  32727. * </example>
  32728. */
  32729. var patternDirective = function() {
  32730. return {
  32731. restrict: 'A',
  32732. require: '?ngModel',
  32733. link: function(scope, elm, attr, ctrl) {
  32734. if (!ctrl) return;
  32735. var regexp, patternExp = attr.ngPattern || attr.pattern;
  32736. attr.$observe('pattern', function(regex) {
  32737. if (isString(regex) && regex.length > 0) {
  32738. regex = new RegExp('^' + regex + '$');
  32739. }
  32740. if (regex && !regex.test) {
  32741. throw minErr('ngPattern')('noregexp',
  32742. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  32743. regex, startingTag(elm));
  32744. }
  32745. regexp = regex || undefined;
  32746. ctrl.$validate();
  32747. });
  32748. ctrl.$validators.pattern = function(modelValue, viewValue) {
  32749. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  32750. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  32751. };
  32752. }
  32753. };
  32754. };
  32755. /**
  32756. * @ngdoc directive
  32757. * @name ngMaxlength
  32758. * @restrict A
  32759. *
  32760. * @param {expression} ngMaxlength AngularJS expression that must evaluate to a `Number` or `String`
  32761. * parsable into a `Number`. Used as value for the `maxlength`
  32762. * {@link ngModel.NgModelController#$validators validator}.
  32763. *
  32764. * @description
  32765. *
  32766. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  32767. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  32768. *
  32769. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  32770. * is longer than the integer obtained by evaluating the AngularJS expression given in the
  32771. * `ngMaxlength` attribute value.
  32772. *
  32773. * <div class="alert alert-info">
  32774. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  32775. * differences:
  32776. * <ol>
  32777. * <li>
  32778. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  32779. * validation is not available.
  32780. * </li>
  32781. * <li>
  32782. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  32783. * interpolated.
  32784. * </li>
  32785. * </ol>
  32786. * </div>
  32787. *
  32788. * @example
  32789. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  32790. * <file name="index.html">
  32791. * <script>
  32792. * angular.module('ngMaxlengthExample', [])
  32793. * .controller('ExampleController', ['$scope', function($scope) {
  32794. * $scope.maxlength = 5;
  32795. * }]);
  32796. * </script>
  32797. * <div ng-controller="ExampleController">
  32798. * <form name="form">
  32799. * <label for="maxlength">Set a maxlength: </label>
  32800. * <input type="number" ng-model="maxlength" id="maxlength" />
  32801. * <br>
  32802. * <label for="input">This input is restricted by the current maxlength: </label>
  32803. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  32804. * <hr>
  32805. * input valid? = <code>{{form.input.$valid}}</code><br>
  32806. * model = <code>{{model}}</code>
  32807. * </form>
  32808. * </div>
  32809. * </file>
  32810. * <file name="protractor.js" type="protractor">
  32811. var model = element(by.binding('model'));
  32812. var input = element(by.id('input'));
  32813. it('should validate the input with the default maxlength', function() {
  32814. input.sendKeys('abcdef');
  32815. expect(model.getText()).not.toContain('abcdef');
  32816. input.clear().then(function() {
  32817. input.sendKeys('abcde');
  32818. expect(model.getText()).toContain('abcde');
  32819. });
  32820. });
  32821. * </file>
  32822. * </example>
  32823. */
  32824. var maxlengthDirective = function() {
  32825. return {
  32826. restrict: 'A',
  32827. require: '?ngModel',
  32828. link: function(scope, elm, attr, ctrl) {
  32829. if (!ctrl) return;
  32830. var maxlength = -1;
  32831. attr.$observe('maxlength', function(value) {
  32832. var intVal = toInt(value);
  32833. maxlength = isNumberNaN(intVal) ? -1 : intVal;
  32834. ctrl.$validate();
  32835. });
  32836. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  32837. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  32838. };
  32839. }
  32840. };
  32841. };
  32842. /**
  32843. * @ngdoc directive
  32844. * @name ngMinlength
  32845. * @restrict A
  32846. *
  32847. * @param {expression} ngMinlength AngularJS expression that must evaluate to a `Number` or `String`
  32848. * parsable into a `Number`. Used as value for the `minlength`
  32849. * {@link ngModel.NgModelController#$validators validator}.
  32850. *
  32851. * @description
  32852. *
  32853. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  32854. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  32855. *
  32856. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  32857. * is shorter than the integer obtained by evaluating the AngularJS expression given in the
  32858. * `ngMinlength` attribute value.
  32859. *
  32860. * <div class="alert alert-info">
  32861. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  32862. * differences:
  32863. * <ol>
  32864. * <li>
  32865. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  32866. * validation is not available.
  32867. * </li>
  32868. * <li>
  32869. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  32870. * interpolated.
  32871. * </li>
  32872. * </ol>
  32873. * </div>
  32874. *
  32875. * @example
  32876. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  32877. * <file name="index.html">
  32878. * <script>
  32879. * angular.module('ngMinlengthExample', [])
  32880. * .controller('ExampleController', ['$scope', function($scope) {
  32881. * $scope.minlength = 3;
  32882. * }]);
  32883. * </script>
  32884. * <div ng-controller="ExampleController">
  32885. * <form name="form">
  32886. * <label for="minlength">Set a minlength: </label>
  32887. * <input type="number" ng-model="minlength" id="minlength" />
  32888. * <br>
  32889. * <label for="input">This input is restricted by the current minlength: </label>
  32890. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  32891. * <hr>
  32892. * input valid? = <code>{{form.input.$valid}}</code><br>
  32893. * model = <code>{{model}}</code>
  32894. * </form>
  32895. * </div>
  32896. * </file>
  32897. * <file name="protractor.js" type="protractor">
  32898. var model = element(by.binding('model'));
  32899. var input = element(by.id('input'));
  32900. it('should validate the input with the default minlength', function() {
  32901. input.sendKeys('ab');
  32902. expect(model.getText()).not.toContain('ab');
  32903. input.sendKeys('abc');
  32904. expect(model.getText()).toContain('abc');
  32905. });
  32906. * </file>
  32907. * </example>
  32908. */
  32909. var minlengthDirective = function() {
  32910. return {
  32911. restrict: 'A',
  32912. require: '?ngModel',
  32913. link: function(scope, elm, attr, ctrl) {
  32914. if (!ctrl) return;
  32915. var minlength = 0;
  32916. attr.$observe('minlength', function(value) {
  32917. minlength = toInt(value) || 0;
  32918. ctrl.$validate();
  32919. });
  32920. ctrl.$validators.minlength = function(modelValue, viewValue) {
  32921. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  32922. };
  32923. }
  32924. };
  32925. };
  32926. if (window.angular.bootstrap) {
  32927. // AngularJS is already loaded, so we can return here...
  32928. if (window.console) {
  32929. console.log('WARNING: Tried to load AngularJS more than once.');
  32930. }
  32931. return;
  32932. }
  32933. // try to bind to jquery now so that one can write jqLite(fn)
  32934. // but we will rebind on bootstrap again.
  32935. bindJQuery();
  32936. publishExternalAPI(angular);
  32937. angular.module("ngLocale", [], ["$provide", function($provide) {
  32938. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  32939. function getDecimals(n) {
  32940. n = n + '';
  32941. var i = n.indexOf('.');
  32942. return (i == -1) ? 0 : n.length - i - 1;
  32943. }
  32944. function getVF(n, opt_precision) {
  32945. var v = opt_precision;
  32946. if (undefined === v) {
  32947. v = Math.min(getDecimals(n), 3);
  32948. }
  32949. var base = Math.pow(10, v);
  32950. var f = ((n * base) | 0) % base;
  32951. return {v: v, f: f};
  32952. }
  32953. $provide.value("$locale", {
  32954. "DATETIME_FORMATS": {
  32955. "AMPMS": [
  32956. "AM",
  32957. "PM"
  32958. ],
  32959. "DAY": [
  32960. "Sunday",
  32961. "Monday",
  32962. "Tuesday",
  32963. "Wednesday",
  32964. "Thursday",
  32965. "Friday",
  32966. "Saturday"
  32967. ],
  32968. "ERANAMES": [
  32969. "Before Christ",
  32970. "Anno Domini"
  32971. ],
  32972. "ERAS": [
  32973. "BC",
  32974. "AD"
  32975. ],
  32976. "FIRSTDAYOFWEEK": 6,
  32977. "MONTH": [
  32978. "January",
  32979. "February",
  32980. "March",
  32981. "April",
  32982. "May",
  32983. "June",
  32984. "July",
  32985. "August",
  32986. "September",
  32987. "October",
  32988. "November",
  32989. "December"
  32990. ],
  32991. "SHORTDAY": [
  32992. "Sun",
  32993. "Mon",
  32994. "Tue",
  32995. "Wed",
  32996. "Thu",
  32997. "Fri",
  32998. "Sat"
  32999. ],
  33000. "SHORTMONTH": [
  33001. "Jan",
  33002. "Feb",
  33003. "Mar",
  33004. "Apr",
  33005. "May",
  33006. "Jun",
  33007. "Jul",
  33008. "Aug",
  33009. "Sep",
  33010. "Oct",
  33011. "Nov",
  33012. "Dec"
  33013. ],
  33014. "STANDALONEMONTH": [
  33015. "January",
  33016. "February",
  33017. "March",
  33018. "April",
  33019. "May",
  33020. "June",
  33021. "July",
  33022. "August",
  33023. "September",
  33024. "October",
  33025. "November",
  33026. "December"
  33027. ],
  33028. "WEEKENDRANGE": [
  33029. 5,
  33030. 6
  33031. ],
  33032. "fullDate": "EEEE, MMMM d, y",
  33033. "longDate": "MMMM d, y",
  33034. "medium": "MMM d, y h:mm:ss a",
  33035. "mediumDate": "MMM d, y",
  33036. "mediumTime": "h:mm:ss a",
  33037. "short": "M/d/yy h:mm a",
  33038. "shortDate": "M/d/yy",
  33039. "shortTime": "h:mm a"
  33040. },
  33041. "NUMBER_FORMATS": {
  33042. "CURRENCY_SYM": "$",
  33043. "DECIMAL_SEP": ".",
  33044. "GROUP_SEP": ",",
  33045. "PATTERNS": [
  33046. {
  33047. "gSize": 3,
  33048. "lgSize": 3,
  33049. "maxFrac": 3,
  33050. "minFrac": 0,
  33051. "minInt": 1,
  33052. "negPre": "-",
  33053. "negSuf": "",
  33054. "posPre": "",
  33055. "posSuf": ""
  33056. },
  33057. {
  33058. "gSize": 3,
  33059. "lgSize": 3,
  33060. "maxFrac": 2,
  33061. "minFrac": 2,
  33062. "minInt": 1,
  33063. "negPre": "-\u00a4",
  33064. "negSuf": "",
  33065. "posPre": "\u00a4",
  33066. "posSuf": ""
  33067. }
  33068. ]
  33069. },
  33070. "id": "en-us",
  33071. "localeID": "en_US",
  33072. "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;}
  33073. });
  33074. }]);
  33075. jqLite(function() {
  33076. angularInit(window.document, bootstrap);
  33077. });
  33078. })(window);
  33079. !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>');