angular.js 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345
  1. /**
  2. * @license AngularJS v1.6.3
  3. * (c) 2010-2017 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function() {
  39. var code = arguments[0],
  40. template = arguments[1],
  41. message = '[' + (module ? module + ':' : '') + code + '] ',
  42. templateArgs = sliceArgs(arguments, 2).map(function(arg) {
  43. return toDebugString(arg, minErrConfig.objectMaxDepth);
  44. }),
  45. paramPrefix, i;
  46. message += template.replace(/\{\d+\}/g, function(match) {
  47. var index = +match.slice(1, -1);
  48. if (index < templateArgs.length) {
  49. return templateArgs[index];
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.6.3/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]);
  57. }
  58. return new ErrorConstructor(message);
  59. };
  60. }
  61. /* We need to tell ESLint what variables are being exported */
  62. /* exported
  63. angular,
  64. msie,
  65. jqLite,
  66. jQuery,
  67. slice,
  68. splice,
  69. push,
  70. toString,
  71. minErrConfig,
  72. errorHandlingConfig,
  73. isValidObjectMaxDepth,
  74. ngMinErr,
  75. angularModule,
  76. uid,
  77. REGEX_STRING_REGEXP,
  78. VALIDITY_STATE_PROPERTY,
  79. lowercase,
  80. uppercase,
  81. manualLowercase,
  82. manualUppercase,
  83. nodeName_,
  84. isArrayLike,
  85. forEach,
  86. forEachSorted,
  87. reverseParams,
  88. nextUid,
  89. setHashKey,
  90. extend,
  91. toInt,
  92. inherit,
  93. merge,
  94. noop,
  95. identity,
  96. valueFn,
  97. isUndefined,
  98. isDefined,
  99. isObject,
  100. isBlankObject,
  101. isString,
  102. isNumber,
  103. isNumberNaN,
  104. isDate,
  105. isArray,
  106. isFunction,
  107. isRegExp,
  108. isWindow,
  109. isScope,
  110. isFile,
  111. isFormData,
  112. isBlob,
  113. isBoolean,
  114. isPromiseLike,
  115. trim,
  116. escapeForRegexp,
  117. isElement,
  118. makeMap,
  119. includes,
  120. arrayRemove,
  121. copy,
  122. equals,
  123. csp,
  124. jq,
  125. concat,
  126. sliceArgs,
  127. bind,
  128. toJsonReplacer,
  129. toJson,
  130. fromJson,
  131. convertTimezoneToLocal,
  132. timezoneToOffset,
  133. startingTag,
  134. tryDecodeURIComponent,
  135. parseKeyValue,
  136. toKeyValue,
  137. encodeUriSegment,
  138. encodeUriQuery,
  139. angularInit,
  140. bootstrap,
  141. getTestability,
  142. snake_case,
  143. bindJQuery,
  144. assertArg,
  145. assertArgFn,
  146. assertNotHasOwnProperty,
  147. getter,
  148. getBlockNodes,
  149. hasOwnProperty,
  150. createMap,
  151. stringify,
  152. NODE_TYPE_ELEMENT,
  153. NODE_TYPE_ATTRIBUTE,
  154. NODE_TYPE_TEXT,
  155. NODE_TYPE_COMMENT,
  156. NODE_TYPE_DOCUMENT,
  157. NODE_TYPE_DOCUMENT_FRAGMENT
  158. */
  159. ////////////////////////////////////
  160. /**
  161. * @ngdoc module
  162. * @name ng
  163. * @module ng
  164. * @installation
  165. * @description
  166. *
  167. * # ng (core module)
  168. * The ng module is loaded by default when an AngularJS application is started. The module itself
  169. * contains the essential components for an AngularJS application to function. The table below
  170. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  171. * components available within this core module.
  172. *
  173. * <div doc-module-components="ng"></div>
  174. */
  175. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  176. // The name of a form control's ValidityState property.
  177. // This is used so that it's possible for internal tests to create mock ValidityStates.
  178. var VALIDITY_STATE_PROPERTY = 'validity';
  179. var hasOwnProperty = Object.prototype.hasOwnProperty;
  180. var minErrConfig = {
  181. objectMaxDepth: 5
  182. };
  183. /**
  184. * @ngdoc function
  185. * @name angular.errorHandlingConfig
  186. * @module ng
  187. * @kind function
  188. *
  189. * @description
  190. * Configure several aspects of error handling in AngularJS if used as a setter or return the
  191. * current configuration if used as a getter. The following options are supported:
  192. *
  193. * - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages.
  194. *
  195. * Omitted or undefined options will leave the corresponding configuration values unchanged.
  196. *
  197. * @param {Object=} config - The configuration object. May only contain the options that need to be
  198. * updated. Supported keys:
  199. *
  200. * * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a
  201. * non-positive or non-numeric value, removes the max depth limit.
  202. * Default: 5
  203. */
  204. function errorHandlingConfig(config) {
  205. if (isObject(config)) {
  206. if (isDefined(config.objectMaxDepth)) {
  207. minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN;
  208. }
  209. } else {
  210. return minErrConfig;
  211. }
  212. }
  213. /**
  214. * @private
  215. * @param {Number} maxDepth
  216. * @return {boolean}
  217. */
  218. function isValidObjectMaxDepth(maxDepth) {
  219. return isNumber(maxDepth) && maxDepth > 0;
  220. }
  221. /**
  222. * @ngdoc function
  223. * @name angular.lowercase
  224. * @module ng
  225. * @kind function
  226. *
  227. * @deprecated
  228. * sinceVersion="1.5.0"
  229. * removeVersion="1.7.0"
  230. * Use [String.prototype.toLowerCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) instead.
  231. *
  232. * @description Converts the specified string to lowercase.
  233. * @param {string} string String to be converted to lowercase.
  234. * @returns {string} Lowercased string.
  235. */
  236. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  237. /**
  238. * @ngdoc function
  239. * @name angular.uppercase
  240. * @module ng
  241. * @kind function
  242. *
  243. * @deprecated
  244. * sinceVersion="1.5.0"
  245. * removeVersion="1.7.0"
  246. * Use [String.prototype.toUpperCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) instead.
  247. *
  248. * @description Converts the specified string to uppercase.
  249. * @param {string} string String to be converted to uppercase.
  250. * @returns {string} Uppercased string.
  251. */
  252. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  253. var manualLowercase = function(s) {
  254. /* eslint-disable no-bitwise */
  255. return isString(s)
  256. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  257. : s;
  258. /* eslint-enable */
  259. };
  260. var manualUppercase = function(s) {
  261. /* eslint-disable no-bitwise */
  262. return isString(s)
  263. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  264. : s;
  265. /* eslint-enable */
  266. };
  267. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  268. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  269. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  270. if ('i' !== 'I'.toLowerCase()) {
  271. lowercase = manualLowercase;
  272. uppercase = manualUppercase;
  273. }
  274. var
  275. msie, // holds major version number for IE, or NaN if UA is not IE.
  276. jqLite, // delay binding since jQuery could be loaded after us.
  277. jQuery, // delay binding
  278. slice = [].slice,
  279. splice = [].splice,
  280. push = [].push,
  281. toString = Object.prototype.toString,
  282. getPrototypeOf = Object.getPrototypeOf,
  283. ngMinErr = minErr('ng'),
  284. /** @name angular */
  285. angular = window.angular || (window.angular = {}),
  286. angularModule,
  287. uid = 0;
  288. // Support: IE 9-11 only
  289. /**
  290. * documentMode is an IE-only property
  291. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  292. */
  293. msie = window.document.documentMode;
  294. /**
  295. * @private
  296. * @param {*} obj
  297. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  298. * String ...)
  299. */
  300. function isArrayLike(obj) {
  301. // `null`, `undefined` and `window` are not array-like
  302. if (obj == null || isWindow(obj)) return false;
  303. // arrays, strings and jQuery/jqLite objects are array like
  304. // * jqLite is either the jQuery or jqLite constructor function
  305. // * we have to check the existence of jqLite first as this method is called
  306. // via the forEach method when constructing the jqLite object in the first place
  307. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  308. // Support: iOS 8.2 (not reproducible in simulator)
  309. // "length" in obj used to prevent JIT error (gh-11508)
  310. var length = 'length' in Object(obj) && obj.length;
  311. // NodeList objects (with `item` method) and
  312. // other objects with suitable length characteristics are array-like
  313. return isNumber(length) &&
  314. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');
  315. }
  316. /**
  317. * @ngdoc function
  318. * @name angular.forEach
  319. * @module ng
  320. * @kind function
  321. *
  322. * @description
  323. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  324. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  325. * is the value of an object property or an array element, `key` is the object property key or
  326. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  327. *
  328. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  329. * using the `hasOwnProperty` method.
  330. *
  331. * Unlike ES262's
  332. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  333. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  334. * return the value provided.
  335. *
  336. ```js
  337. var values = {name: 'misko', gender: 'male'};
  338. var log = [];
  339. angular.forEach(values, function(value, key) {
  340. this.push(key + ': ' + value);
  341. }, log);
  342. expect(log).toEqual(['name: misko', 'gender: male']);
  343. ```
  344. *
  345. * @param {Object|Array} obj Object to iterate over.
  346. * @param {Function} iterator Iterator function.
  347. * @param {Object=} context Object to become context (`this`) for the iterator function.
  348. * @returns {Object|Array} Reference to `obj`.
  349. */
  350. function forEach(obj, iterator, context) {
  351. var key, length;
  352. if (obj) {
  353. if (isFunction(obj)) {
  354. for (key in obj) {
  355. if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
  356. iterator.call(context, obj[key], key, obj);
  357. }
  358. }
  359. } else if (isArray(obj) || isArrayLike(obj)) {
  360. var isPrimitive = typeof obj !== 'object';
  361. for (key = 0, length = obj.length; key < length; key++) {
  362. if (isPrimitive || key in obj) {
  363. iterator.call(context, obj[key], key, obj);
  364. }
  365. }
  366. } else if (obj.forEach && obj.forEach !== forEach) {
  367. obj.forEach(iterator, context, obj);
  368. } else if (isBlankObject(obj)) {
  369. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  370. for (key in obj) {
  371. iterator.call(context, obj[key], key, obj);
  372. }
  373. } else if (typeof obj.hasOwnProperty === 'function') {
  374. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  375. for (key in obj) {
  376. if (obj.hasOwnProperty(key)) {
  377. iterator.call(context, obj[key], key, obj);
  378. }
  379. }
  380. } else {
  381. // Slow path for objects which do not have a method `hasOwnProperty`
  382. for (key in obj) {
  383. if (hasOwnProperty.call(obj, key)) {
  384. iterator.call(context, obj[key], key, obj);
  385. }
  386. }
  387. }
  388. }
  389. return obj;
  390. }
  391. function forEachSorted(obj, iterator, context) {
  392. var keys = Object.keys(obj).sort();
  393. for (var i = 0; i < keys.length; i++) {
  394. iterator.call(context, obj[keys[i]], keys[i]);
  395. }
  396. return keys;
  397. }
  398. /**
  399. * when using forEach the params are value, key, but it is often useful to have key, value.
  400. * @param {function(string, *)} iteratorFn
  401. * @returns {function(*, string)}
  402. */
  403. function reverseParams(iteratorFn) {
  404. return function(value, key) {iteratorFn(key, value);};
  405. }
  406. /**
  407. * A consistent way of creating unique IDs in angular.
  408. *
  409. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  410. * we hit number precision issues in JavaScript.
  411. *
  412. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  413. *
  414. * @returns {number} an unique alpha-numeric string
  415. */
  416. function nextUid() {
  417. return ++uid;
  418. }
  419. /**
  420. * Set or clear the hashkey for an object.
  421. * @param obj object
  422. * @param h the hashkey (!truthy to delete the hashkey)
  423. */
  424. function setHashKey(obj, h) {
  425. if (h) {
  426. obj.$$hashKey = h;
  427. } else {
  428. delete obj.$$hashKey;
  429. }
  430. }
  431. function baseExtend(dst, objs, deep) {
  432. var h = dst.$$hashKey;
  433. for (var i = 0, ii = objs.length; i < ii; ++i) {
  434. var obj = objs[i];
  435. if (!isObject(obj) && !isFunction(obj)) continue;
  436. var keys = Object.keys(obj);
  437. for (var j = 0, jj = keys.length; j < jj; j++) {
  438. var key = keys[j];
  439. var src = obj[key];
  440. if (deep && isObject(src)) {
  441. if (isDate(src)) {
  442. dst[key] = new Date(src.valueOf());
  443. } else if (isRegExp(src)) {
  444. dst[key] = new RegExp(src);
  445. } else if (src.nodeName) {
  446. dst[key] = src.cloneNode(true);
  447. } else if (isElement(src)) {
  448. dst[key] = src.clone();
  449. } else {
  450. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  451. baseExtend(dst[key], [src], true);
  452. }
  453. } else {
  454. dst[key] = src;
  455. }
  456. }
  457. }
  458. setHashKey(dst, h);
  459. return dst;
  460. }
  461. /**
  462. * @ngdoc function
  463. * @name angular.extend
  464. * @module ng
  465. * @kind function
  466. *
  467. * @description
  468. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  469. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  470. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  471. *
  472. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  473. * {@link angular.merge} for this.
  474. *
  475. * @param {Object} dst Destination object.
  476. * @param {...Object} src Source object(s).
  477. * @returns {Object} Reference to `dst`.
  478. */
  479. function extend(dst) {
  480. return baseExtend(dst, slice.call(arguments, 1), false);
  481. }
  482. /**
  483. * @ngdoc function
  484. * @name angular.merge
  485. * @module ng
  486. * @kind function
  487. *
  488. * @description
  489. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  490. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  491. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  492. *
  493. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  494. * objects, performing a deep copy.
  495. *
  496. * @param {Object} dst Destination object.
  497. * @param {...Object} src Source object(s).
  498. * @returns {Object} Reference to `dst`.
  499. */
  500. function merge(dst) {
  501. return baseExtend(dst, slice.call(arguments, 1), true);
  502. }
  503. function toInt(str) {
  504. return parseInt(str, 10);
  505. }
  506. var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
  507. // eslint-disable-next-line no-self-compare
  508. return num !== num;
  509. };
  510. function inherit(parent, extra) {
  511. return extend(Object.create(parent), extra);
  512. }
  513. /**
  514. * @ngdoc function
  515. * @name angular.noop
  516. * @module ng
  517. * @kind function
  518. *
  519. * @description
  520. * A function that performs no operations. This function can be useful when writing code in the
  521. * functional style.
  522. ```js
  523. function foo(callback) {
  524. var result = calculateResult();
  525. (callback || angular.noop)(result);
  526. }
  527. ```
  528. */
  529. function noop() {}
  530. noop.$inject = [];
  531. /**
  532. * @ngdoc function
  533. * @name angular.identity
  534. * @module ng
  535. * @kind function
  536. *
  537. * @description
  538. * A function that returns its first argument. This function is useful when writing code in the
  539. * functional style.
  540. *
  541. ```js
  542. function transformer(transformationFn, value) {
  543. return (transformationFn || angular.identity)(value);
  544. };
  545. // E.g.
  546. function getResult(fn, input) {
  547. return (fn || angular.identity)(input);
  548. };
  549. getResult(function(n) { return n * 2; }, 21); // returns 42
  550. getResult(null, 21); // returns 21
  551. getResult(undefined, 21); // returns 21
  552. ```
  553. *
  554. * @param {*} value to be returned.
  555. * @returns {*} the value passed in.
  556. */
  557. function identity($) {return $;}
  558. identity.$inject = [];
  559. function valueFn(value) {return function valueRef() {return value;};}
  560. function hasCustomToString(obj) {
  561. return isFunction(obj.toString) && obj.toString !== toString;
  562. }
  563. /**
  564. * @ngdoc function
  565. * @name angular.isUndefined
  566. * @module ng
  567. * @kind function
  568. *
  569. * @description
  570. * Determines if a reference is undefined.
  571. *
  572. * @param {*} value Reference to check.
  573. * @returns {boolean} True if `value` is undefined.
  574. */
  575. function isUndefined(value) {return typeof value === 'undefined';}
  576. /**
  577. * @ngdoc function
  578. * @name angular.isDefined
  579. * @module ng
  580. * @kind function
  581. *
  582. * @description
  583. * Determines if a reference is defined.
  584. *
  585. * @param {*} value Reference to check.
  586. * @returns {boolean} True if `value` is defined.
  587. */
  588. function isDefined(value) {return typeof value !== 'undefined';}
  589. /**
  590. * @ngdoc function
  591. * @name angular.isObject
  592. * @module ng
  593. * @kind function
  594. *
  595. * @description
  596. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  597. * considered to be objects. Note that JavaScript arrays are objects.
  598. *
  599. * @param {*} value Reference to check.
  600. * @returns {boolean} True if `value` is an `Object` but not `null`.
  601. */
  602. function isObject(value) {
  603. // http://jsperf.com/isobject4
  604. return value !== null && typeof value === 'object';
  605. }
  606. /**
  607. * Determine if a value is an object with a null prototype
  608. *
  609. * @returns {boolean} True if `value` is an `Object` with a null prototype
  610. */
  611. function isBlankObject(value) {
  612. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  613. }
  614. /**
  615. * @ngdoc function
  616. * @name angular.isString
  617. * @module ng
  618. * @kind function
  619. *
  620. * @description
  621. * Determines if a reference is a `String`.
  622. *
  623. * @param {*} value Reference to check.
  624. * @returns {boolean} True if `value` is a `String`.
  625. */
  626. function isString(value) {return typeof value === 'string';}
  627. /**
  628. * @ngdoc function
  629. * @name angular.isNumber
  630. * @module ng
  631. * @kind function
  632. *
  633. * @description
  634. * Determines if a reference is a `Number`.
  635. *
  636. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  637. *
  638. * If you wish to exclude these then you can use the native
  639. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  640. * method.
  641. *
  642. * @param {*} value Reference to check.
  643. * @returns {boolean} True if `value` is a `Number`.
  644. */
  645. function isNumber(value) {return typeof value === 'number';}
  646. /**
  647. * @ngdoc function
  648. * @name angular.isDate
  649. * @module ng
  650. * @kind function
  651. *
  652. * @description
  653. * Determines if a value is a date.
  654. *
  655. * @param {*} value Reference to check.
  656. * @returns {boolean} True if `value` is a `Date`.
  657. */
  658. function isDate(value) {
  659. return toString.call(value) === '[object Date]';
  660. }
  661. /**
  662. * @ngdoc function
  663. * @name angular.isArray
  664. * @module ng
  665. * @kind function
  666. *
  667. * @description
  668. * Determines if a reference is an `Array`. Alias of Array.isArray.
  669. *
  670. * @param {*} value Reference to check.
  671. * @returns {boolean} True if `value` is an `Array`.
  672. */
  673. var isArray = Array.isArray;
  674. /**
  675. * @ngdoc function
  676. * @name angular.isFunction
  677. * @module ng
  678. * @kind function
  679. *
  680. * @description
  681. * Determines if a reference is a `Function`.
  682. *
  683. * @param {*} value Reference to check.
  684. * @returns {boolean} True if `value` is a `Function`.
  685. */
  686. function isFunction(value) {return typeof value === 'function';}
  687. /**
  688. * Determines if a value is a regular expression object.
  689. *
  690. * @private
  691. * @param {*} value Reference to check.
  692. * @returns {boolean} True if `value` is a `RegExp`.
  693. */
  694. function isRegExp(value) {
  695. return toString.call(value) === '[object RegExp]';
  696. }
  697. /**
  698. * Checks if `obj` is a window object.
  699. *
  700. * @private
  701. * @param {*} obj Object to check
  702. * @returns {boolean} True if `obj` is a window obj.
  703. */
  704. function isWindow(obj) {
  705. return obj && obj.window === obj;
  706. }
  707. function isScope(obj) {
  708. return obj && obj.$evalAsync && obj.$watch;
  709. }
  710. function isFile(obj) {
  711. return toString.call(obj) === '[object File]';
  712. }
  713. function isFormData(obj) {
  714. return toString.call(obj) === '[object FormData]';
  715. }
  716. function isBlob(obj) {
  717. return toString.call(obj) === '[object Blob]';
  718. }
  719. function isBoolean(value) {
  720. return typeof value === 'boolean';
  721. }
  722. function isPromiseLike(obj) {
  723. return obj && isFunction(obj.then);
  724. }
  725. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
  726. function isTypedArray(value) {
  727. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  728. }
  729. function isArrayBuffer(obj) {
  730. return toString.call(obj) === '[object ArrayBuffer]';
  731. }
  732. var trim = function(value) {
  733. return isString(value) ? value.trim() : value;
  734. };
  735. // Copied from:
  736. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  737. // Prereq: s is a string.
  738. var escapeForRegexp = function(s) {
  739. return s
  740. .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
  741. // eslint-disable-next-line no-control-regex
  742. .replace(/\x08/g, '\\x08');
  743. };
  744. /**
  745. * @ngdoc function
  746. * @name angular.isElement
  747. * @module ng
  748. * @kind function
  749. *
  750. * @description
  751. * Determines if a reference is a DOM element (or wrapped jQuery element).
  752. *
  753. * @param {*} value Reference to check.
  754. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  755. */
  756. function isElement(node) {
  757. return !!(node &&
  758. (node.nodeName // We are a direct element.
  759. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  760. }
  761. /**
  762. * @param str 'key1,key2,...'
  763. * @returns {object} in the form of {key1:true, key2:true, ...}
  764. */
  765. function makeMap(str) {
  766. var obj = {}, items = str.split(','), i;
  767. for (i = 0; i < items.length; i++) {
  768. obj[items[i]] = true;
  769. }
  770. return obj;
  771. }
  772. function nodeName_(element) {
  773. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  774. }
  775. function includes(array, obj) {
  776. return Array.prototype.indexOf.call(array, obj) !== -1;
  777. }
  778. function arrayRemove(array, value) {
  779. var index = array.indexOf(value);
  780. if (index >= 0) {
  781. array.splice(index, 1);
  782. }
  783. return index;
  784. }
  785. /**
  786. * @ngdoc function
  787. * @name angular.copy
  788. * @module ng
  789. * @kind function
  790. *
  791. * @description
  792. * Creates a deep copy of `source`, which should be an object or an array.
  793. *
  794. * * If no destination is supplied, a copy of the object or array is created.
  795. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  796. * are deleted and then all elements/properties from the source are copied to it.
  797. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  798. * * If `source` is identical to `destination` an exception will be thrown.
  799. *
  800. * <br />
  801. * <div class="alert alert-warning">
  802. * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
  803. * and on `destination`) will be ignored.
  804. * </div>
  805. *
  806. * @param {*} source The source that will be used to make a copy.
  807. * Can be any type, including primitives, `null`, and `undefined`.
  808. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  809. * provided, must be of the same type as `source`.
  810. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  811. *
  812. * @example
  813. <example module="copyExample" name="angular-copy">
  814. <file name="index.html">
  815. <div ng-controller="ExampleController">
  816. <form novalidate class="simple-form">
  817. <label>Name: <input type="text" ng-model="user.name" /></label><br />
  818. <label>Age: <input type="number" ng-model="user.age" /></label><br />
  819. Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
  820. <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
  821. <button ng-click="reset()">RESET</button>
  822. <button ng-click="update(user)">SAVE</button>
  823. </form>
  824. <pre>form = {{user | json}}</pre>
  825. <pre>master = {{master | json}}</pre>
  826. </div>
  827. </file>
  828. <file name="script.js">
  829. // Module: copyExample
  830. angular.
  831. module('copyExample', []).
  832. controller('ExampleController', ['$scope', function($scope) {
  833. $scope.master = {};
  834. $scope.reset = function() {
  835. // Example with 1 argument
  836. $scope.user = angular.copy($scope.master);
  837. };
  838. $scope.update = function(user) {
  839. // Example with 2 arguments
  840. angular.copy(user, $scope.master);
  841. };
  842. $scope.reset();
  843. }]);
  844. </file>
  845. </example>
  846. */
  847. function copy(source, destination, maxDepth) {
  848. var stackSource = [];
  849. var stackDest = [];
  850. maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN;
  851. if (destination) {
  852. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  853. throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
  854. }
  855. if (source === destination) {
  856. throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
  857. }
  858. // Empty the destination object
  859. if (isArray(destination)) {
  860. destination.length = 0;
  861. } else {
  862. forEach(destination, function(value, key) {
  863. if (key !== '$$hashKey') {
  864. delete destination[key];
  865. }
  866. });
  867. }
  868. stackSource.push(source);
  869. stackDest.push(destination);
  870. return copyRecurse(source, destination, maxDepth);
  871. }
  872. return copyElement(source, maxDepth);
  873. function copyRecurse(source, destination, maxDepth) {
  874. maxDepth--;
  875. if (maxDepth < 0) {
  876. return '...';
  877. }
  878. var h = destination.$$hashKey;
  879. var key;
  880. if (isArray(source)) {
  881. for (var i = 0, ii = source.length; i < ii; i++) {
  882. destination.push(copyElement(source[i], maxDepth));
  883. }
  884. } else if (isBlankObject(source)) {
  885. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  886. for (key in source) {
  887. destination[key] = copyElement(source[key], maxDepth);
  888. }
  889. } else if (source && typeof source.hasOwnProperty === 'function') {
  890. // Slow path, which must rely on hasOwnProperty
  891. for (key in source) {
  892. if (source.hasOwnProperty(key)) {
  893. destination[key] = copyElement(source[key], maxDepth);
  894. }
  895. }
  896. } else {
  897. // Slowest path --- hasOwnProperty can't be called as a method
  898. for (key in source) {
  899. if (hasOwnProperty.call(source, key)) {
  900. destination[key] = copyElement(source[key], maxDepth);
  901. }
  902. }
  903. }
  904. setHashKey(destination, h);
  905. return destination;
  906. }
  907. function copyElement(source, maxDepth) {
  908. // Simple values
  909. if (!isObject(source)) {
  910. return source;
  911. }
  912. // Already copied values
  913. var index = stackSource.indexOf(source);
  914. if (index !== -1) {
  915. return stackDest[index];
  916. }
  917. if (isWindow(source) || isScope(source)) {
  918. throw ngMinErr('cpws',
  919. 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
  920. }
  921. var needsRecurse = false;
  922. var destination = copyType(source);
  923. if (destination === undefined) {
  924. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  925. needsRecurse = true;
  926. }
  927. stackSource.push(source);
  928. stackDest.push(destination);
  929. return needsRecurse
  930. ? copyRecurse(source, destination, maxDepth)
  931. : destination;
  932. }
  933. function copyType(source) {
  934. switch (toString.call(source)) {
  935. case '[object Int8Array]':
  936. case '[object Int16Array]':
  937. case '[object Int32Array]':
  938. case '[object Float32Array]':
  939. case '[object Float64Array]':
  940. case '[object Uint8Array]':
  941. case '[object Uint8ClampedArray]':
  942. case '[object Uint16Array]':
  943. case '[object Uint32Array]':
  944. return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
  945. case '[object ArrayBuffer]':
  946. // Support: IE10
  947. if (!source.slice) {
  948. // If we're in this case we know the environment supports ArrayBuffer
  949. /* eslint-disable no-undef */
  950. var copied = new ArrayBuffer(source.byteLength);
  951. new Uint8Array(copied).set(new Uint8Array(source));
  952. /* eslint-enable */
  953. return copied;
  954. }
  955. return source.slice(0);
  956. case '[object Boolean]':
  957. case '[object Number]':
  958. case '[object String]':
  959. case '[object Date]':
  960. return new source.constructor(source.valueOf());
  961. case '[object RegExp]':
  962. var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
  963. re.lastIndex = source.lastIndex;
  964. return re;
  965. case '[object Blob]':
  966. return new source.constructor([source], {type: source.type});
  967. }
  968. if (isFunction(source.cloneNode)) {
  969. return source.cloneNode(true);
  970. }
  971. }
  972. }
  973. /**
  974. * @ngdoc function
  975. * @name angular.equals
  976. * @module ng
  977. * @kind function
  978. *
  979. * @description
  980. * Determines if two objects or two values are equivalent. Supports value types, regular
  981. * expressions, arrays and objects.
  982. *
  983. * Two objects or values are considered equivalent if at least one of the following is true:
  984. *
  985. * * Both objects or values pass `===` comparison.
  986. * * Both objects or values are of the same type and all of their properties are equal by
  987. * comparing them with `angular.equals`.
  988. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  989. * * Both values represent the same regular expression (In JavaScript,
  990. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  991. * representation matches).
  992. *
  993. * During a property comparison, properties of `function` type and properties with names
  994. * that begin with `$` are ignored.
  995. *
  996. * Scope and DOMWindow objects are being compared only by identify (`===`).
  997. *
  998. * @param {*} o1 Object or value to compare.
  999. * @param {*} o2 Object or value to compare.
  1000. * @returns {boolean} True if arguments are equal.
  1001. *
  1002. * @example
  1003. <example module="equalsExample" name="equalsExample">
  1004. <file name="index.html">
  1005. <div ng-controller="ExampleController">
  1006. <form novalidate>
  1007. <h3>User 1</h3>
  1008. Name: <input type="text" ng-model="user1.name">
  1009. Age: <input type="number" ng-model="user1.age">
  1010. <h3>User 2</h3>
  1011. Name: <input type="text" ng-model="user2.name">
  1012. Age: <input type="number" ng-model="user2.age">
  1013. <div>
  1014. <br/>
  1015. <input type="button" value="Compare" ng-click="compare()">
  1016. </div>
  1017. User 1: <pre>{{user1 | json}}</pre>
  1018. User 2: <pre>{{user2 | json}}</pre>
  1019. Equal: <pre>{{result}}</pre>
  1020. </form>
  1021. </div>
  1022. </file>
  1023. <file name="script.js">
  1024. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  1025. $scope.user1 = {};
  1026. $scope.user2 = {};
  1027. $scope.compare = function() {
  1028. $scope.result = angular.equals($scope.user1, $scope.user2);
  1029. };
  1030. }]);
  1031. </file>
  1032. </example>
  1033. */
  1034. function equals(o1, o2) {
  1035. if (o1 === o2) return true;
  1036. if (o1 === null || o2 === null) return false;
  1037. // eslint-disable-next-line no-self-compare
  1038. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  1039. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  1040. if (t1 === t2 && t1 === 'object') {
  1041. if (isArray(o1)) {
  1042. if (!isArray(o2)) return false;
  1043. if ((length = o1.length) === o2.length) {
  1044. for (key = 0; key < length; key++) {
  1045. if (!equals(o1[key], o2[key])) return false;
  1046. }
  1047. return true;
  1048. }
  1049. } else if (isDate(o1)) {
  1050. if (!isDate(o2)) return false;
  1051. return equals(o1.getTime(), o2.getTime());
  1052. } else if (isRegExp(o1)) {
  1053. if (!isRegExp(o2)) return false;
  1054. return o1.toString() === o2.toString();
  1055. } else {
  1056. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  1057. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  1058. keySet = createMap();
  1059. for (key in o1) {
  1060. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  1061. if (!equals(o1[key], o2[key])) return false;
  1062. keySet[key] = true;
  1063. }
  1064. for (key in o2) {
  1065. if (!(key in keySet) &&
  1066. key.charAt(0) !== '$' &&
  1067. isDefined(o2[key]) &&
  1068. !isFunction(o2[key])) return false;
  1069. }
  1070. return true;
  1071. }
  1072. }
  1073. return false;
  1074. }
  1075. var csp = function() {
  1076. if (!isDefined(csp.rules)) {
  1077. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  1078. window.document.querySelector('[data-ng-csp]'));
  1079. if (ngCspElement) {
  1080. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  1081. ngCspElement.getAttribute('data-ng-csp');
  1082. csp.rules = {
  1083. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  1084. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  1085. };
  1086. } else {
  1087. csp.rules = {
  1088. noUnsafeEval: noUnsafeEval(),
  1089. noInlineStyle: false
  1090. };
  1091. }
  1092. }
  1093. return csp.rules;
  1094. function noUnsafeEval() {
  1095. try {
  1096. // eslint-disable-next-line no-new, no-new-func
  1097. new Function('');
  1098. return false;
  1099. } catch (e) {
  1100. return true;
  1101. }
  1102. }
  1103. };
  1104. /**
  1105. * @ngdoc directive
  1106. * @module ng
  1107. * @name ngJq
  1108. *
  1109. * @element ANY
  1110. * @param {string=} ngJq the name of the library available under `window`
  1111. * to be used for angular.element
  1112. * @description
  1113. * Use this directive to force the angular.element library. This should be
  1114. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1115. * the jquery variable under window (eg. jQuery).
  1116. *
  1117. * Since angular looks for this directive when it is loaded (doesn't wait for the
  1118. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1119. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1120. * others ignored.
  1121. *
  1122. * @example
  1123. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1124. ```html
  1125. <!doctype html>
  1126. <html ng-app ng-jq>
  1127. ...
  1128. ...
  1129. </html>
  1130. ```
  1131. * @example
  1132. * This example shows how to use a jQuery based library of a different name.
  1133. * The library name must be available at the top most 'window'.
  1134. ```html
  1135. <!doctype html>
  1136. <html ng-app ng-jq="jQueryLib">
  1137. ...
  1138. ...
  1139. </html>
  1140. ```
  1141. */
  1142. var jq = function() {
  1143. if (isDefined(jq.name_)) return jq.name_;
  1144. var el;
  1145. var i, ii = ngAttrPrefixes.length, prefix, name;
  1146. for (i = 0; i < ii; ++i) {
  1147. prefix = ngAttrPrefixes[i];
  1148. el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
  1149. if (el) {
  1150. name = el.getAttribute(prefix + 'jq');
  1151. break;
  1152. }
  1153. }
  1154. return (jq.name_ = name);
  1155. };
  1156. function concat(array1, array2, index) {
  1157. return array1.concat(slice.call(array2, index));
  1158. }
  1159. function sliceArgs(args, startIndex) {
  1160. return slice.call(args, startIndex || 0);
  1161. }
  1162. /**
  1163. * @ngdoc function
  1164. * @name angular.bind
  1165. * @module ng
  1166. * @kind function
  1167. *
  1168. * @description
  1169. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1170. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1171. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1172. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1173. *
  1174. * @param {Object} self Context which `fn` should be evaluated in.
  1175. * @param {function()} fn Function to be bound.
  1176. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1177. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1178. */
  1179. function bind(self, fn) {
  1180. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1181. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1182. return curryArgs.length
  1183. ? function() {
  1184. return arguments.length
  1185. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1186. : fn.apply(self, curryArgs);
  1187. }
  1188. : function() {
  1189. return arguments.length
  1190. ? fn.apply(self, arguments)
  1191. : fn.call(self);
  1192. };
  1193. } else {
  1194. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1195. return fn;
  1196. }
  1197. }
  1198. function toJsonReplacer(key, value) {
  1199. var val = value;
  1200. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1201. val = undefined;
  1202. } else if (isWindow(value)) {
  1203. val = '$WINDOW';
  1204. } else if (value && window.document === value) {
  1205. val = '$DOCUMENT';
  1206. } else if (isScope(value)) {
  1207. val = '$SCOPE';
  1208. }
  1209. return val;
  1210. }
  1211. /**
  1212. * @ngdoc function
  1213. * @name angular.toJson
  1214. * @module ng
  1215. * @kind function
  1216. *
  1217. * @description
  1218. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1219. * stripped since angular uses this notation internally.
  1220. *
  1221. * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
  1222. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1223. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1224. * @returns {string|undefined} JSON-ified string representing `obj`.
  1225. * @knownIssue
  1226. *
  1227. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1228. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1229. * `Date.prototype.toJSON` method as follows:
  1230. *
  1231. * ```
  1232. * var _DatetoJSON = Date.prototype.toJSON;
  1233. * Date.prototype.toJSON = function() {
  1234. * try {
  1235. * return _DatetoJSON.call(this);
  1236. * } catch(e) {
  1237. * if (e instanceof RangeError) {
  1238. * return null;
  1239. * }
  1240. * throw e;
  1241. * }
  1242. * };
  1243. * ```
  1244. *
  1245. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1246. */
  1247. function toJson(obj, pretty) {
  1248. if (isUndefined(obj)) return undefined;
  1249. if (!isNumber(pretty)) {
  1250. pretty = pretty ? 2 : null;
  1251. }
  1252. return JSON.stringify(obj, toJsonReplacer, pretty);
  1253. }
  1254. /**
  1255. * @ngdoc function
  1256. * @name angular.fromJson
  1257. * @module ng
  1258. * @kind function
  1259. *
  1260. * @description
  1261. * Deserializes a JSON string.
  1262. *
  1263. * @param {string} json JSON string to deserialize.
  1264. * @returns {Object|Array|string|number} Deserialized JSON string.
  1265. */
  1266. function fromJson(json) {
  1267. return isString(json)
  1268. ? JSON.parse(json)
  1269. : json;
  1270. }
  1271. var ALL_COLONS = /:/g;
  1272. function timezoneToOffset(timezone, fallback) {
  1273. // Support: IE 9-11 only, Edge 13-14+
  1274. // IE/Edge do not "understand" colon (`:`) in timezone
  1275. timezone = timezone.replace(ALL_COLONS, '');
  1276. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1277. return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1278. }
  1279. function addDateMinutes(date, minutes) {
  1280. date = new Date(date.getTime());
  1281. date.setMinutes(date.getMinutes() + minutes);
  1282. return date;
  1283. }
  1284. function convertTimezoneToLocal(date, timezone, reverse) {
  1285. reverse = reverse ? -1 : 1;
  1286. var dateTimezoneOffset = date.getTimezoneOffset();
  1287. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1288. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1289. }
  1290. /**
  1291. * @returns {string} Returns the string representation of the element.
  1292. */
  1293. function startingTag(element) {
  1294. element = jqLite(element).clone();
  1295. try {
  1296. // turns out IE does not let you set .html() on elements which
  1297. // are not allowed to have children. So we just ignore it.
  1298. element.empty();
  1299. } catch (e) { /* empty */ }
  1300. var elemHtml = jqLite('<div>').append(element).html();
  1301. try {
  1302. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1303. elemHtml.
  1304. match(/^(<[^>]+>)/)[1].
  1305. replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1306. } catch (e) {
  1307. return lowercase(elemHtml);
  1308. }
  1309. }
  1310. /////////////////////////////////////////////////
  1311. /**
  1312. * Tries to decode the URI component without throwing an exception.
  1313. *
  1314. * @private
  1315. * @param str value potential URI component to check.
  1316. * @returns {boolean} True if `value` can be decoded
  1317. * with the decodeURIComponent function.
  1318. */
  1319. function tryDecodeURIComponent(value) {
  1320. try {
  1321. return decodeURIComponent(value);
  1322. } catch (e) {
  1323. // Ignore any invalid uri component.
  1324. }
  1325. }
  1326. /**
  1327. * Parses an escaped url query string into key-value pairs.
  1328. * @returns {Object.<string,boolean|Array>}
  1329. */
  1330. function parseKeyValue(/**string*/keyValue) {
  1331. var obj = {};
  1332. forEach((keyValue || '').split('&'), function(keyValue) {
  1333. var splitPoint, key, val;
  1334. if (keyValue) {
  1335. key = keyValue = keyValue.replace(/\+/g,'%20');
  1336. splitPoint = keyValue.indexOf('=');
  1337. if (splitPoint !== -1) {
  1338. key = keyValue.substring(0, splitPoint);
  1339. val = keyValue.substring(splitPoint + 1);
  1340. }
  1341. key = tryDecodeURIComponent(key);
  1342. if (isDefined(key)) {
  1343. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1344. if (!hasOwnProperty.call(obj, key)) {
  1345. obj[key] = val;
  1346. } else if (isArray(obj[key])) {
  1347. obj[key].push(val);
  1348. } else {
  1349. obj[key] = [obj[key],val];
  1350. }
  1351. }
  1352. }
  1353. });
  1354. return obj;
  1355. }
  1356. function toKeyValue(obj) {
  1357. var parts = [];
  1358. forEach(obj, function(value, key) {
  1359. if (isArray(value)) {
  1360. forEach(value, function(arrayValue) {
  1361. parts.push(encodeUriQuery(key, true) +
  1362. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1363. });
  1364. } else {
  1365. parts.push(encodeUriQuery(key, true) +
  1366. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1367. }
  1368. });
  1369. return parts.length ? parts.join('&') : '';
  1370. }
  1371. /**
  1372. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1373. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1374. * segments:
  1375. * segment = *pchar
  1376. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1377. * pct-encoded = "%" HEXDIG HEXDIG
  1378. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1379. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1380. * / "*" / "+" / "," / ";" / "="
  1381. */
  1382. function encodeUriSegment(val) {
  1383. return encodeUriQuery(val, true).
  1384. replace(/%26/gi, '&').
  1385. replace(/%3D/gi, '=').
  1386. replace(/%2B/gi, '+');
  1387. }
  1388. /**
  1389. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1390. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1391. * encoded per http://tools.ietf.org/html/rfc3986:
  1392. * query = *( pchar / "/" / "?" )
  1393. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1394. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1395. * pct-encoded = "%" HEXDIG HEXDIG
  1396. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1397. * / "*" / "+" / "," / ";" / "="
  1398. */
  1399. function encodeUriQuery(val, pctEncodeSpaces) {
  1400. return encodeURIComponent(val).
  1401. replace(/%40/gi, '@').
  1402. replace(/%3A/gi, ':').
  1403. replace(/%24/g, '$').
  1404. replace(/%2C/gi, ',').
  1405. replace(/%3B/gi, ';').
  1406. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1407. }
  1408. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1409. function getNgAttribute(element, ngAttr) {
  1410. var attr, i, ii = ngAttrPrefixes.length;
  1411. for (i = 0; i < ii; ++i) {
  1412. attr = ngAttrPrefixes[i] + ngAttr;
  1413. if (isString(attr = element.getAttribute(attr))) {
  1414. return attr;
  1415. }
  1416. }
  1417. return null;
  1418. }
  1419. function allowAutoBootstrap(document) {
  1420. var script = document.currentScript;
  1421. if (!script) {
  1422. // IE does not have `document.currentScript`
  1423. return true;
  1424. }
  1425. // If the `currentScript` property has been clobbered just return false, since this indicates a probable attack
  1426. if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) {
  1427. return false;
  1428. }
  1429. var attributes = script.attributes;
  1430. var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')];
  1431. return srcs.every(function(src) {
  1432. if (!src) {
  1433. return true;
  1434. }
  1435. if (!src.value) {
  1436. return false;
  1437. }
  1438. var link = document.createElement('a');
  1439. link.href = src.value;
  1440. if (document.location.origin === link.origin) {
  1441. // Same-origin resources are always allowed, even for non-whitelisted schemes.
  1442. return true;
  1443. }
  1444. // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
  1445. // This is to prevent angular.js bundled with browser extensions from being used to bypass the
  1446. // content security policy in web pages and other browser extensions.
  1447. switch (link.protocol) {
  1448. case 'http:':
  1449. case 'https:':
  1450. case 'ftp:':
  1451. case 'blob:':
  1452. case 'file:':
  1453. case 'data:':
  1454. return true;
  1455. default:
  1456. return false;
  1457. }
  1458. });
  1459. }
  1460. // Cached as it has to run during loading so that document.currentScript is available.
  1461. var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
  1462. /**
  1463. * @ngdoc directive
  1464. * @name ngApp
  1465. * @module ng
  1466. *
  1467. * @element ANY
  1468. * @param {angular.Module} ngApp an optional application
  1469. * {@link angular.module module} name to load.
  1470. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1471. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1472. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1473. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1474. * tracking down the root of these bugs.
  1475. *
  1476. * @description
  1477. *
  1478. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1479. * designates the **root element** of the application and is typically placed near the root element
  1480. * of the page - e.g. on the `<body>` or `<html>` tags.
  1481. *
  1482. * There are a few things to keep in mind when using `ngApp`:
  1483. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1484. * found in the document will be used to define the root element to auto-bootstrap as an
  1485. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1486. * {@link angular.bootstrap} instead.
  1487. * - AngularJS applications cannot be nested within each other.
  1488. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1489. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1490. * {@link ngRoute.ngView `ngView`}.
  1491. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1492. * causing animations to stop working and making the injector inaccessible from outside the app.
  1493. *
  1494. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1495. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1496. * should contain the application code needed or have dependencies on other modules that will
  1497. * contain the code. See {@link angular.module} for more information.
  1498. *
  1499. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1500. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1501. * would not be resolved to `3`.
  1502. *
  1503. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1504. *
  1505. <example module="ngAppDemo" name="ng-app">
  1506. <file name="index.html">
  1507. <div ng-controller="ngAppDemoController">
  1508. I can add: {{a}} + {{b}} = {{ a+b }}
  1509. </div>
  1510. </file>
  1511. <file name="script.js">
  1512. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1513. $scope.a = 1;
  1514. $scope.b = 2;
  1515. });
  1516. </file>
  1517. </example>
  1518. *
  1519. * Using `ngStrictDi`, you would see something like this:
  1520. *
  1521. <example ng-app-included="true" name="strict-di">
  1522. <file name="index.html">
  1523. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1524. <div ng-controller="GoodController1">
  1525. I can add: {{a}} + {{b}} = {{ a+b }}
  1526. <p>This renders because the controller does not fail to
  1527. instantiate, by using explicit annotation style (see
  1528. script.js for details)
  1529. </p>
  1530. </div>
  1531. <div ng-controller="GoodController2">
  1532. Name: <input ng-model="name"><br />
  1533. Hello, {{name}}!
  1534. <p>This renders because the controller does not fail to
  1535. instantiate, by using explicit annotation style
  1536. (see script.js for details)
  1537. </p>
  1538. </div>
  1539. <div ng-controller="BadController">
  1540. I can add: {{a}} + {{b}} = {{ a+b }}
  1541. <p>The controller could not be instantiated, due to relying
  1542. on automatic function annotations (which are disabled in
  1543. strict mode). As such, the content of this section is not
  1544. interpolated, and there should be an error in your web console.
  1545. </p>
  1546. </div>
  1547. </div>
  1548. </file>
  1549. <file name="script.js">
  1550. angular.module('ngAppStrictDemo', [])
  1551. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1552. // rather than an explicit annotation
  1553. .controller('BadController', function($scope) {
  1554. $scope.a = 1;
  1555. $scope.b = 2;
  1556. })
  1557. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1558. // due to using explicit annotations using the array style and $inject property, respectively.
  1559. .controller('GoodController1', ['$scope', function($scope) {
  1560. $scope.a = 1;
  1561. $scope.b = 2;
  1562. }])
  1563. .controller('GoodController2', GoodController2);
  1564. function GoodController2($scope) {
  1565. $scope.name = 'World';
  1566. }
  1567. GoodController2.$inject = ['$scope'];
  1568. </file>
  1569. <file name="style.css">
  1570. div[ng-controller] {
  1571. margin-bottom: 1em;
  1572. -webkit-border-radius: 4px;
  1573. border-radius: 4px;
  1574. border: 1px solid;
  1575. padding: .5em;
  1576. }
  1577. div[ng-controller^=Good] {
  1578. border-color: #d6e9c6;
  1579. background-color: #dff0d8;
  1580. color: #3c763d;
  1581. }
  1582. div[ng-controller^=Bad] {
  1583. border-color: #ebccd1;
  1584. background-color: #f2dede;
  1585. color: #a94442;
  1586. margin-bottom: 0;
  1587. }
  1588. </file>
  1589. </example>
  1590. */
  1591. function angularInit(element, bootstrap) {
  1592. var appElement,
  1593. module,
  1594. config = {};
  1595. // The element `element` has priority over any other element.
  1596. forEach(ngAttrPrefixes, function(prefix) {
  1597. var name = prefix + 'app';
  1598. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1599. appElement = element;
  1600. module = element.getAttribute(name);
  1601. }
  1602. });
  1603. forEach(ngAttrPrefixes, function(prefix) {
  1604. var name = prefix + 'app';
  1605. var candidate;
  1606. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1607. appElement = candidate;
  1608. module = candidate.getAttribute(name);
  1609. }
  1610. });
  1611. if (appElement) {
  1612. if (!isAutoBootstrapAllowed) {
  1613. window.console.error('Angular: disabling automatic bootstrap. <script> protocol indicates ' +
  1614. 'an extension, document.location.href does not match.');
  1615. return;
  1616. }
  1617. config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
  1618. bootstrap(appElement, module ? [module] : [], config);
  1619. }
  1620. }
  1621. /**
  1622. * @ngdoc function
  1623. * @name angular.bootstrap
  1624. * @module ng
  1625. * @description
  1626. * Use this function to manually start up angular application.
  1627. *
  1628. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1629. *
  1630. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1631. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1632. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1633. * multiple instances of Angular try to work on the DOM.
  1634. *
  1635. * <div class="alert alert-warning">
  1636. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1637. * They must use {@link ng.directive:ngApp ngApp}.
  1638. * </div>
  1639. *
  1640. * <div class="alert alert-warning">
  1641. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1642. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1643. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1644. * causing animations to stop working and making the injector inaccessible from outside the app.
  1645. * </div>
  1646. *
  1647. * ```html
  1648. * <!doctype html>
  1649. * <html>
  1650. * <body>
  1651. * <div ng-controller="WelcomeController">
  1652. * {{greeting}}
  1653. * </div>
  1654. *
  1655. * <script src="angular.js"></script>
  1656. * <script>
  1657. * var app = angular.module('demo', [])
  1658. * .controller('WelcomeController', function($scope) {
  1659. * $scope.greeting = 'Welcome!';
  1660. * });
  1661. * angular.bootstrap(document, ['demo']);
  1662. * </script>
  1663. * </body>
  1664. * </html>
  1665. * ```
  1666. *
  1667. * @param {DOMElement} element DOM element which is the root of angular application.
  1668. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1669. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1670. * function that will be invoked by the injector as a `config` block.
  1671. * See: {@link angular.module modules}
  1672. * @param {Object=} config an object for defining configuration options for the application. The
  1673. * following keys are supported:
  1674. *
  1675. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1676. * assist in finding bugs which break minified code. Defaults to `false`.
  1677. *
  1678. * @returns {auto.$injector} Returns the newly created injector for this app.
  1679. */
  1680. function bootstrap(element, modules, config) {
  1681. if (!isObject(config)) config = {};
  1682. var defaultConfig = {
  1683. strictDi: false
  1684. };
  1685. config = extend(defaultConfig, config);
  1686. var doBootstrap = function() {
  1687. element = jqLite(element);
  1688. if (element.injector()) {
  1689. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1690. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1691. throw ngMinErr(
  1692. 'btstrpd',
  1693. 'App already bootstrapped with this element \'{0}\'',
  1694. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1695. }
  1696. modules = modules || [];
  1697. modules.unshift(['$provide', function($provide) {
  1698. $provide.value('$rootElement', element);
  1699. }]);
  1700. if (config.debugInfoEnabled) {
  1701. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1702. modules.push(['$compileProvider', function($compileProvider) {
  1703. $compileProvider.debugInfoEnabled(true);
  1704. }]);
  1705. }
  1706. modules.unshift('ng');
  1707. var injector = createInjector(modules, config.strictDi);
  1708. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1709. function bootstrapApply(scope, element, compile, injector) {
  1710. scope.$apply(function() {
  1711. element.data('$injector', injector);
  1712. compile(element)(scope);
  1713. });
  1714. }]
  1715. );
  1716. return injector;
  1717. };
  1718. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1719. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1720. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1721. config.debugInfoEnabled = true;
  1722. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1723. }
  1724. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1725. return doBootstrap();
  1726. }
  1727. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1728. angular.resumeBootstrap = function(extraModules) {
  1729. forEach(extraModules, function(module) {
  1730. modules.push(module);
  1731. });
  1732. return doBootstrap();
  1733. };
  1734. if (isFunction(angular.resumeDeferredBootstrap)) {
  1735. angular.resumeDeferredBootstrap();
  1736. }
  1737. }
  1738. /**
  1739. * @ngdoc function
  1740. * @name angular.reloadWithDebugInfo
  1741. * @module ng
  1742. * @description
  1743. * Use this function to reload the current application with debug information turned on.
  1744. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1745. *
  1746. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1747. */
  1748. function reloadWithDebugInfo() {
  1749. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1750. window.location.reload();
  1751. }
  1752. /**
  1753. * @name angular.getTestability
  1754. * @module ng
  1755. * @description
  1756. * Get the testability service for the instance of Angular on the given
  1757. * element.
  1758. * @param {DOMElement} element DOM element which is the root of angular application.
  1759. */
  1760. function getTestability(rootElement) {
  1761. var injector = angular.element(rootElement).injector();
  1762. if (!injector) {
  1763. throw ngMinErr('test',
  1764. 'no injector found for element argument to getTestability');
  1765. }
  1766. return injector.get('$$testability');
  1767. }
  1768. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1769. function snake_case(name, separator) {
  1770. separator = separator || '_';
  1771. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1772. return (pos ? separator : '') + letter.toLowerCase();
  1773. });
  1774. }
  1775. var bindJQueryFired = false;
  1776. function bindJQuery() {
  1777. var originalCleanData;
  1778. if (bindJQueryFired) {
  1779. return;
  1780. }
  1781. // bind to jQuery if present;
  1782. var jqName = jq();
  1783. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1784. !jqName ? undefined : // use jqLite
  1785. window[jqName]; // use jQuery specified by `ngJq`
  1786. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1787. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1788. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1789. // versions. It will not work for sure with jQuery <1.7, though.
  1790. if (jQuery && jQuery.fn.on) {
  1791. jqLite = jQuery;
  1792. extend(jQuery.fn, {
  1793. scope: JQLitePrototype.scope,
  1794. isolateScope: JQLitePrototype.isolateScope,
  1795. controller: /** @type {?} */ (JQLitePrototype).controller,
  1796. injector: JQLitePrototype.injector,
  1797. inheritedData: JQLitePrototype.inheritedData
  1798. });
  1799. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1800. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1801. // the $destroy event on all removed nodes.
  1802. originalCleanData = jQuery.cleanData;
  1803. jQuery.cleanData = function(elems) {
  1804. var events;
  1805. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1806. events = jQuery._data(elem, 'events');
  1807. if (events && events.$destroy) {
  1808. jQuery(elem).triggerHandler('$destroy');
  1809. }
  1810. }
  1811. originalCleanData(elems);
  1812. };
  1813. } else {
  1814. jqLite = JQLite;
  1815. }
  1816. angular.element = jqLite;
  1817. // Prevent double-proxying.
  1818. bindJQueryFired = true;
  1819. }
  1820. /**
  1821. * throw error if the argument is falsy.
  1822. */
  1823. function assertArg(arg, name, reason) {
  1824. if (!arg) {
  1825. throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
  1826. }
  1827. return arg;
  1828. }
  1829. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1830. if (acceptArrayAnnotation && isArray(arg)) {
  1831. arg = arg[arg.length - 1];
  1832. }
  1833. assertArg(isFunction(arg), name, 'not a function, got ' +
  1834. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1835. return arg;
  1836. }
  1837. /**
  1838. * throw error if the name given is hasOwnProperty
  1839. * @param {String} name the name to test
  1840. * @param {String} context the context in which the name is used, such as module or directive
  1841. */
  1842. function assertNotHasOwnProperty(name, context) {
  1843. if (name === 'hasOwnProperty') {
  1844. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1845. }
  1846. }
  1847. /**
  1848. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1849. * @param {Object} obj starting object
  1850. * @param {String} path path to traverse
  1851. * @param {boolean} [bindFnToScope=true]
  1852. * @returns {Object} value as accessible by path
  1853. */
  1854. //TODO(misko): this function needs to be removed
  1855. function getter(obj, path, bindFnToScope) {
  1856. if (!path) return obj;
  1857. var keys = path.split('.');
  1858. var key;
  1859. var lastInstance = obj;
  1860. var len = keys.length;
  1861. for (var i = 0; i < len; i++) {
  1862. key = keys[i];
  1863. if (obj) {
  1864. obj = (lastInstance = obj)[key];
  1865. }
  1866. }
  1867. if (!bindFnToScope && isFunction(obj)) {
  1868. return bind(lastInstance, obj);
  1869. }
  1870. return obj;
  1871. }
  1872. /**
  1873. * Return the DOM siblings between the first and last node in the given array.
  1874. * @param {Array} array like object
  1875. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1876. */
  1877. function getBlockNodes(nodes) {
  1878. // TODO(perf): update `nodes` instead of creating a new object?
  1879. var node = nodes[0];
  1880. var endNode = nodes[nodes.length - 1];
  1881. var blockNodes;
  1882. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1883. if (blockNodes || nodes[i] !== node) {
  1884. if (!blockNodes) {
  1885. blockNodes = jqLite(slice.call(nodes, 0, i));
  1886. }
  1887. blockNodes.push(node);
  1888. }
  1889. }
  1890. return blockNodes || nodes;
  1891. }
  1892. /**
  1893. * Creates a new object without a prototype. This object is useful for lookup without having to
  1894. * guard against prototypically inherited properties via hasOwnProperty.
  1895. *
  1896. * Related micro-benchmarks:
  1897. * - http://jsperf.com/object-create2
  1898. * - http://jsperf.com/proto-map-lookup/2
  1899. * - http://jsperf.com/for-in-vs-object-keys2
  1900. *
  1901. * @returns {Object}
  1902. */
  1903. function createMap() {
  1904. return Object.create(null);
  1905. }
  1906. function stringify(value) {
  1907. if (value == null) { // null || undefined
  1908. return '';
  1909. }
  1910. switch (typeof value) {
  1911. case 'string':
  1912. break;
  1913. case 'number':
  1914. value = '' + value;
  1915. break;
  1916. default:
  1917. if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
  1918. value = value.toString();
  1919. } else {
  1920. value = toJson(value);
  1921. }
  1922. }
  1923. return value;
  1924. }
  1925. var NODE_TYPE_ELEMENT = 1;
  1926. var NODE_TYPE_ATTRIBUTE = 2;
  1927. var NODE_TYPE_TEXT = 3;
  1928. var NODE_TYPE_COMMENT = 8;
  1929. var NODE_TYPE_DOCUMENT = 9;
  1930. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1931. /**
  1932. * @ngdoc type
  1933. * @name angular.Module
  1934. * @module ng
  1935. * @description
  1936. *
  1937. * Interface for configuring angular {@link angular.module modules}.
  1938. */
  1939. function setupModuleLoader(window) {
  1940. var $injectorMinErr = minErr('$injector');
  1941. var ngMinErr = minErr('ng');
  1942. function ensure(obj, name, factory) {
  1943. return obj[name] || (obj[name] = factory());
  1944. }
  1945. var angular = ensure(window, 'angular', Object);
  1946. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1947. angular.$$minErr = angular.$$minErr || minErr;
  1948. return ensure(angular, 'module', function() {
  1949. /** @type {Object.<string, angular.Module>} */
  1950. var modules = {};
  1951. /**
  1952. * @ngdoc function
  1953. * @name angular.module
  1954. * @module ng
  1955. * @description
  1956. *
  1957. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1958. * modules.
  1959. * All modules (angular core or 3rd party) that should be available to an application must be
  1960. * registered using this mechanism.
  1961. *
  1962. * Passing one argument retrieves an existing {@link angular.Module},
  1963. * whereas passing more than one argument creates a new {@link angular.Module}
  1964. *
  1965. *
  1966. * # Module
  1967. *
  1968. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1969. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1970. *
  1971. * ```js
  1972. * // Create a new module
  1973. * var myModule = angular.module('myModule', []);
  1974. *
  1975. * // register a new service
  1976. * myModule.value('appName', 'MyCoolApp');
  1977. *
  1978. * // configure existing services inside initialization blocks.
  1979. * myModule.config(['$locationProvider', function($locationProvider) {
  1980. * // Configure existing providers
  1981. * $locationProvider.hashPrefix('!');
  1982. * }]);
  1983. * ```
  1984. *
  1985. * Then you can create an injector and load your modules like this:
  1986. *
  1987. * ```js
  1988. * var injector = angular.injector(['ng', 'myModule'])
  1989. * ```
  1990. *
  1991. * However it's more likely that you'll just use
  1992. * {@link ng.directive:ngApp ngApp} or
  1993. * {@link angular.bootstrap} to simplify this process for you.
  1994. *
  1995. * @param {!string} name The name of the module to create or retrieve.
  1996. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1997. * unspecified then the module is being retrieved for further configuration.
  1998. * @param {Function=} configFn Optional configuration function for the module. Same as
  1999. * {@link angular.Module#config Module#config()}.
  2000. * @returns {angular.Module} new module with the {@link angular.Module} api.
  2001. */
  2002. return function module(name, requires, configFn) {
  2003. var info = {};
  2004. var assertNotHasOwnProperty = function(name, context) {
  2005. if (name === 'hasOwnProperty') {
  2006. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  2007. }
  2008. };
  2009. assertNotHasOwnProperty(name, 'module');
  2010. if (requires && modules.hasOwnProperty(name)) {
  2011. modules[name] = null;
  2012. }
  2013. return ensure(modules, name, function() {
  2014. if (!requires) {
  2015. throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
  2016. 'the module name or forgot to load it. If registering a module ensure that you ' +
  2017. 'specify the dependencies as the second argument.', name);
  2018. }
  2019. /** @type {!Array.<Array.<*>>} */
  2020. var invokeQueue = [];
  2021. /** @type {!Array.<Function>} */
  2022. var configBlocks = [];
  2023. /** @type {!Array.<Function>} */
  2024. var runBlocks = [];
  2025. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  2026. /** @type {angular.Module} */
  2027. var moduleInstance = {
  2028. // Private state
  2029. _invokeQueue: invokeQueue,
  2030. _configBlocks: configBlocks,
  2031. _runBlocks: runBlocks,
  2032. /**
  2033. * @ngdoc method
  2034. * @name angular.Module#info
  2035. * @module ng
  2036. *
  2037. * @param {Object=} info Information about the module
  2038. * @returns {Object|Module} The current info object for this module if called as a getter,
  2039. * or `this` if called as a setter.
  2040. *
  2041. * @description
  2042. * Read and write custom information about this module.
  2043. * For example you could put the version of the module in here.
  2044. *
  2045. * ```js
  2046. * angular.module('myModule', []).info({ version: '1.0.0' });
  2047. * ```
  2048. *
  2049. * The version could then be read back out by accessing the module elsewhere:
  2050. *
  2051. * ```
  2052. * var version = angular.module('myModule').info().version;
  2053. * ```
  2054. *
  2055. * You can also retrieve this information during runtime via the
  2056. * {@link $injector#modules `$injector.modules`} property:
  2057. *
  2058. * ```js
  2059. * var version = $injector.modules['myModule'].info().version;
  2060. * ```
  2061. */
  2062. info: function(value) {
  2063. if (isDefined(value)) {
  2064. if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value');
  2065. info = value;
  2066. return this;
  2067. }
  2068. return info;
  2069. },
  2070. /**
  2071. * @ngdoc property
  2072. * @name angular.Module#requires
  2073. * @module ng
  2074. *
  2075. * @description
  2076. * Holds the list of modules which the injector will load before the current module is
  2077. * loaded.
  2078. */
  2079. requires: requires,
  2080. /**
  2081. * @ngdoc property
  2082. * @name angular.Module#name
  2083. * @module ng
  2084. *
  2085. * @description
  2086. * Name of the module.
  2087. */
  2088. name: name,
  2089. /**
  2090. * @ngdoc method
  2091. * @name angular.Module#provider
  2092. * @module ng
  2093. * @param {string} name service name
  2094. * @param {Function} providerType Construction function for creating new instance of the
  2095. * service.
  2096. * @description
  2097. * See {@link auto.$provide#provider $provide.provider()}.
  2098. */
  2099. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  2100. /**
  2101. * @ngdoc method
  2102. * @name angular.Module#factory
  2103. * @module ng
  2104. * @param {string} name service name
  2105. * @param {Function} providerFunction Function for creating new instance of the service.
  2106. * @description
  2107. * See {@link auto.$provide#factory $provide.factory()}.
  2108. */
  2109. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  2110. /**
  2111. * @ngdoc method
  2112. * @name angular.Module#service
  2113. * @module ng
  2114. * @param {string} name service name
  2115. * @param {Function} constructor A constructor function that will be instantiated.
  2116. * @description
  2117. * See {@link auto.$provide#service $provide.service()}.
  2118. */
  2119. service: invokeLaterAndSetModuleName('$provide', 'service'),
  2120. /**
  2121. * @ngdoc method
  2122. * @name angular.Module#value
  2123. * @module ng
  2124. * @param {string} name service name
  2125. * @param {*} object Service instance object.
  2126. * @description
  2127. * See {@link auto.$provide#value $provide.value()}.
  2128. */
  2129. value: invokeLater('$provide', 'value'),
  2130. /**
  2131. * @ngdoc method
  2132. * @name angular.Module#constant
  2133. * @module ng
  2134. * @param {string} name constant name
  2135. * @param {*} object Constant value.
  2136. * @description
  2137. * Because the constants are fixed, they get applied before other provide methods.
  2138. * See {@link auto.$provide#constant $provide.constant()}.
  2139. */
  2140. constant: invokeLater('$provide', 'constant', 'unshift'),
  2141. /**
  2142. * @ngdoc method
  2143. * @name angular.Module#decorator
  2144. * @module ng
  2145. * @param {string} name The name of the service to decorate.
  2146. * @param {Function} decorFn This function will be invoked when the service needs to be
  2147. * instantiated and should return the decorated service instance.
  2148. * @description
  2149. * See {@link auto.$provide#decorator $provide.decorator()}.
  2150. */
  2151. decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
  2152. /**
  2153. * @ngdoc method
  2154. * @name angular.Module#animation
  2155. * @module ng
  2156. * @param {string} name animation name
  2157. * @param {Function} animationFactory Factory function for creating new instance of an
  2158. * animation.
  2159. * @description
  2160. *
  2161. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  2162. *
  2163. *
  2164. * Defines an animation hook that can be later used with
  2165. * {@link $animate $animate} service and directives that use this service.
  2166. *
  2167. * ```js
  2168. * module.animation('.animation-name', function($inject1, $inject2) {
  2169. * return {
  2170. * eventName : function(element, done) {
  2171. * //code to run the animation
  2172. * //once complete, then run done()
  2173. * return function cancellationFunction(element) {
  2174. * //code to cancel the animation
  2175. * }
  2176. * }
  2177. * }
  2178. * })
  2179. * ```
  2180. *
  2181. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  2182. * {@link ngAnimate ngAnimate module} for more information.
  2183. */
  2184. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  2185. /**
  2186. * @ngdoc method
  2187. * @name angular.Module#filter
  2188. * @module ng
  2189. * @param {string} name Filter name - this must be a valid angular expression identifier
  2190. * @param {Function} filterFactory Factory function for creating new instance of filter.
  2191. * @description
  2192. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  2193. *
  2194. * <div class="alert alert-warning">
  2195. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  2196. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  2197. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  2198. * (`myapp_subsection_filterx`).
  2199. * </div>
  2200. */
  2201. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  2202. /**
  2203. * @ngdoc method
  2204. * @name angular.Module#controller
  2205. * @module ng
  2206. * @param {string|Object} name Controller name, or an object map of controllers where the
  2207. * keys are the names and the values are the constructors.
  2208. * @param {Function} constructor Controller constructor function.
  2209. * @description
  2210. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2211. */
  2212. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2213. /**
  2214. * @ngdoc method
  2215. * @name angular.Module#directive
  2216. * @module ng
  2217. * @param {string|Object} name Directive name, or an object map of directives where the
  2218. * keys are the names and the values are the factories.
  2219. * @param {Function} directiveFactory Factory function for creating new instance of
  2220. * directives.
  2221. * @description
  2222. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2223. */
  2224. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2225. /**
  2226. * @ngdoc method
  2227. * @name angular.Module#component
  2228. * @module ng
  2229. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  2230. * @param {Object} options Component definition object (a simplified
  2231. * {@link ng.$compile#directive-definition-object directive definition object})
  2232. *
  2233. * @description
  2234. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2235. */
  2236. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2237. /**
  2238. * @ngdoc method
  2239. * @name angular.Module#config
  2240. * @module ng
  2241. * @param {Function} configFn Execute this function on module load. Useful for service
  2242. * configuration.
  2243. * @description
  2244. * Use this method to register work which needs to be performed on module loading.
  2245. * For more about how to configure services, see
  2246. * {@link providers#provider-recipe Provider Recipe}.
  2247. */
  2248. config: config,
  2249. /**
  2250. * @ngdoc method
  2251. * @name angular.Module#run
  2252. * @module ng
  2253. * @param {Function} initializationFn Execute this function after injector creation.
  2254. * Useful for application initialization.
  2255. * @description
  2256. * Use this method to register work which should be performed when the injector is done
  2257. * loading all modules.
  2258. */
  2259. run: function(block) {
  2260. runBlocks.push(block);
  2261. return this;
  2262. }
  2263. };
  2264. if (configFn) {
  2265. config(configFn);
  2266. }
  2267. return moduleInstance;
  2268. /**
  2269. * @param {string} provider
  2270. * @param {string} method
  2271. * @param {String=} insertMethod
  2272. * @returns {angular.Module}
  2273. */
  2274. function invokeLater(provider, method, insertMethod, queue) {
  2275. if (!queue) queue = invokeQueue;
  2276. return function() {
  2277. queue[insertMethod || 'push']([provider, method, arguments]);
  2278. return moduleInstance;
  2279. };
  2280. }
  2281. /**
  2282. * @param {string} provider
  2283. * @param {string} method
  2284. * @returns {angular.Module}
  2285. */
  2286. function invokeLaterAndSetModuleName(provider, method, queue) {
  2287. if (!queue) queue = invokeQueue;
  2288. return function(recipeName, factoryFunction) {
  2289. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2290. queue.push([provider, method, arguments]);
  2291. return moduleInstance;
  2292. };
  2293. }
  2294. });
  2295. };
  2296. });
  2297. }
  2298. /* global shallowCopy: true */
  2299. /**
  2300. * Creates a shallow copy of an object, an array or a primitive.
  2301. *
  2302. * Assumes that there are no proto properties for objects.
  2303. */
  2304. function shallowCopy(src, dst) {
  2305. if (isArray(src)) {
  2306. dst = dst || [];
  2307. for (var i = 0, ii = src.length; i < ii; i++) {
  2308. dst[i] = src[i];
  2309. }
  2310. } else if (isObject(src)) {
  2311. dst = dst || {};
  2312. for (var key in src) {
  2313. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2314. dst[key] = src[key];
  2315. }
  2316. }
  2317. }
  2318. return dst || src;
  2319. }
  2320. /* global toDebugString: true */
  2321. function serializeObject(obj, maxDepth) {
  2322. var seen = [];
  2323. // There is no direct way to stringify object until reaching a specific depth
  2324. // and a very deep object can cause a performance issue, so we copy the object
  2325. // based on this specific depth and then stringify it.
  2326. if (isValidObjectMaxDepth(maxDepth)) {
  2327. obj = copy(obj, null, maxDepth);
  2328. }
  2329. return JSON.stringify(obj, function(key, val) {
  2330. val = toJsonReplacer(key, val);
  2331. if (isObject(val)) {
  2332. if (seen.indexOf(val) >= 0) return '...';
  2333. seen.push(val);
  2334. }
  2335. return val;
  2336. });
  2337. }
  2338. function toDebugString(obj, maxDepth) {
  2339. if (typeof obj === 'function') {
  2340. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2341. } else if (isUndefined(obj)) {
  2342. return 'undefined';
  2343. } else if (typeof obj !== 'string') {
  2344. return serializeObject(obj, maxDepth);
  2345. }
  2346. return obj;
  2347. }
  2348. /* global angularModule: true,
  2349. version: true,
  2350. $CompileProvider,
  2351. htmlAnchorDirective,
  2352. inputDirective,
  2353. inputDirective,
  2354. formDirective,
  2355. scriptDirective,
  2356. selectDirective,
  2357. optionDirective,
  2358. ngBindDirective,
  2359. ngBindHtmlDirective,
  2360. ngBindTemplateDirective,
  2361. ngClassDirective,
  2362. ngClassEvenDirective,
  2363. ngClassOddDirective,
  2364. ngCloakDirective,
  2365. ngControllerDirective,
  2366. ngFormDirective,
  2367. ngHideDirective,
  2368. ngIfDirective,
  2369. ngIncludeDirective,
  2370. ngIncludeFillContentDirective,
  2371. ngInitDirective,
  2372. ngNonBindableDirective,
  2373. ngPluralizeDirective,
  2374. ngRepeatDirective,
  2375. ngShowDirective,
  2376. ngStyleDirective,
  2377. ngSwitchDirective,
  2378. ngSwitchWhenDirective,
  2379. ngSwitchDefaultDirective,
  2380. ngOptionsDirective,
  2381. ngTranscludeDirective,
  2382. ngModelDirective,
  2383. ngListDirective,
  2384. ngChangeDirective,
  2385. patternDirective,
  2386. patternDirective,
  2387. requiredDirective,
  2388. requiredDirective,
  2389. minlengthDirective,
  2390. minlengthDirective,
  2391. maxlengthDirective,
  2392. maxlengthDirective,
  2393. ngValueDirective,
  2394. ngModelOptionsDirective,
  2395. ngAttributeAliasDirectives,
  2396. ngEventDirectives,
  2397. $AnchorScrollProvider,
  2398. $AnimateProvider,
  2399. $CoreAnimateCssProvider,
  2400. $$CoreAnimateJsProvider,
  2401. $$CoreAnimateQueueProvider,
  2402. $$AnimateRunnerFactoryProvider,
  2403. $$AnimateAsyncRunFactoryProvider,
  2404. $BrowserProvider,
  2405. $CacheFactoryProvider,
  2406. $ControllerProvider,
  2407. $DateProvider,
  2408. $DocumentProvider,
  2409. $$IsDocumentHiddenProvider,
  2410. $ExceptionHandlerProvider,
  2411. $FilterProvider,
  2412. $$ForceReflowProvider,
  2413. $InterpolateProvider,
  2414. $IntervalProvider,
  2415. $HttpProvider,
  2416. $HttpParamSerializerProvider,
  2417. $HttpParamSerializerJQLikeProvider,
  2418. $HttpBackendProvider,
  2419. $xhrFactoryProvider,
  2420. $jsonpCallbacksProvider,
  2421. $LocationProvider,
  2422. $LogProvider,
  2423. $$MapProvider,
  2424. $ParseProvider,
  2425. $RootScopeProvider,
  2426. $QProvider,
  2427. $$QProvider,
  2428. $$SanitizeUriProvider,
  2429. $SceProvider,
  2430. $SceDelegateProvider,
  2431. $SnifferProvider,
  2432. $TemplateCacheProvider,
  2433. $TemplateRequestProvider,
  2434. $$TestabilityProvider,
  2435. $TimeoutProvider,
  2436. $$RAFProvider,
  2437. $WindowProvider,
  2438. $$jqLiteProvider,
  2439. $$CookieReaderProvider
  2440. */
  2441. /**
  2442. * @ngdoc object
  2443. * @name angular.version
  2444. * @module ng
  2445. * @description
  2446. * An object that contains information about the current AngularJS version.
  2447. *
  2448. * This object has the following properties:
  2449. *
  2450. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2451. * - `major` – `{number}` – Major version number, such as "0".
  2452. * - `minor` – `{number}` – Minor version number, such as "9".
  2453. * - `dot` – `{number}` – Dot version number, such as "18".
  2454. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2455. */
  2456. var version = {
  2457. // These placeholder strings will be replaced by grunt's `build` task.
  2458. // They need to be double- or single-quoted.
  2459. full: '1.6.3',
  2460. major: 1,
  2461. minor: 6,
  2462. dot: 3,
  2463. codeName: 'scriptalicious-bootstrapping'
  2464. };
  2465. function publishExternalAPI(angular) {
  2466. extend(angular, {
  2467. 'errorHandlingConfig': errorHandlingConfig,
  2468. 'bootstrap': bootstrap,
  2469. 'copy': copy,
  2470. 'extend': extend,
  2471. 'merge': merge,
  2472. 'equals': equals,
  2473. 'element': jqLite,
  2474. 'forEach': forEach,
  2475. 'injector': createInjector,
  2476. 'noop': noop,
  2477. 'bind': bind,
  2478. 'toJson': toJson,
  2479. 'fromJson': fromJson,
  2480. 'identity': identity,
  2481. 'isUndefined': isUndefined,
  2482. 'isDefined': isDefined,
  2483. 'isString': isString,
  2484. 'isFunction': isFunction,
  2485. 'isObject': isObject,
  2486. 'isNumber': isNumber,
  2487. 'isElement': isElement,
  2488. 'isArray': isArray,
  2489. 'version': version,
  2490. 'isDate': isDate,
  2491. 'lowercase': lowercase,
  2492. 'uppercase': uppercase,
  2493. 'callbacks': {$$counter: 0},
  2494. 'getTestability': getTestability,
  2495. 'reloadWithDebugInfo': reloadWithDebugInfo,
  2496. '$$minErr': minErr,
  2497. '$$csp': csp,
  2498. '$$encodeUriSegment': encodeUriSegment,
  2499. '$$encodeUriQuery': encodeUriQuery,
  2500. '$$stringify': stringify
  2501. });
  2502. angularModule = setupModuleLoader(window);
  2503. angularModule('ng', ['ngLocale'], ['$provide',
  2504. function ngModule($provide) {
  2505. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2506. $provide.provider({
  2507. $$sanitizeUri: $$SanitizeUriProvider
  2508. });
  2509. $provide.provider('$compile', $CompileProvider).
  2510. directive({
  2511. a: htmlAnchorDirective,
  2512. input: inputDirective,
  2513. textarea: inputDirective,
  2514. form: formDirective,
  2515. script: scriptDirective,
  2516. select: selectDirective,
  2517. option: optionDirective,
  2518. ngBind: ngBindDirective,
  2519. ngBindHtml: ngBindHtmlDirective,
  2520. ngBindTemplate: ngBindTemplateDirective,
  2521. ngClass: ngClassDirective,
  2522. ngClassEven: ngClassEvenDirective,
  2523. ngClassOdd: ngClassOddDirective,
  2524. ngCloak: ngCloakDirective,
  2525. ngController: ngControllerDirective,
  2526. ngForm: ngFormDirective,
  2527. ngHide: ngHideDirective,
  2528. ngIf: ngIfDirective,
  2529. ngInclude: ngIncludeDirective,
  2530. ngInit: ngInitDirective,
  2531. ngNonBindable: ngNonBindableDirective,
  2532. ngPluralize: ngPluralizeDirective,
  2533. ngRepeat: ngRepeatDirective,
  2534. ngShow: ngShowDirective,
  2535. ngStyle: ngStyleDirective,
  2536. ngSwitch: ngSwitchDirective,
  2537. ngSwitchWhen: ngSwitchWhenDirective,
  2538. ngSwitchDefault: ngSwitchDefaultDirective,
  2539. ngOptions: ngOptionsDirective,
  2540. ngTransclude: ngTranscludeDirective,
  2541. ngModel: ngModelDirective,
  2542. ngList: ngListDirective,
  2543. ngChange: ngChangeDirective,
  2544. pattern: patternDirective,
  2545. ngPattern: patternDirective,
  2546. required: requiredDirective,
  2547. ngRequired: requiredDirective,
  2548. minlength: minlengthDirective,
  2549. ngMinlength: minlengthDirective,
  2550. maxlength: maxlengthDirective,
  2551. ngMaxlength: maxlengthDirective,
  2552. ngValue: ngValueDirective,
  2553. ngModelOptions: ngModelOptionsDirective
  2554. }).
  2555. directive({
  2556. ngInclude: ngIncludeFillContentDirective
  2557. }).
  2558. directive(ngAttributeAliasDirectives).
  2559. directive(ngEventDirectives);
  2560. $provide.provider({
  2561. $anchorScroll: $AnchorScrollProvider,
  2562. $animate: $AnimateProvider,
  2563. $animateCss: $CoreAnimateCssProvider,
  2564. $$animateJs: $$CoreAnimateJsProvider,
  2565. $$animateQueue: $$CoreAnimateQueueProvider,
  2566. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2567. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2568. $browser: $BrowserProvider,
  2569. $cacheFactory: $CacheFactoryProvider,
  2570. $controller: $ControllerProvider,
  2571. $document: $DocumentProvider,
  2572. $$isDocumentHidden: $$IsDocumentHiddenProvider,
  2573. $exceptionHandler: $ExceptionHandlerProvider,
  2574. $filter: $FilterProvider,
  2575. $$forceReflow: $$ForceReflowProvider,
  2576. $interpolate: $InterpolateProvider,
  2577. $interval: $IntervalProvider,
  2578. $http: $HttpProvider,
  2579. $httpParamSerializer: $HttpParamSerializerProvider,
  2580. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2581. $httpBackend: $HttpBackendProvider,
  2582. $xhrFactory: $xhrFactoryProvider,
  2583. $jsonpCallbacks: $jsonpCallbacksProvider,
  2584. $location: $LocationProvider,
  2585. $log: $LogProvider,
  2586. $parse: $ParseProvider,
  2587. $rootScope: $RootScopeProvider,
  2588. $q: $QProvider,
  2589. $$q: $$QProvider,
  2590. $sce: $SceProvider,
  2591. $sceDelegate: $SceDelegateProvider,
  2592. $sniffer: $SnifferProvider,
  2593. $templateCache: $TemplateCacheProvider,
  2594. $templateRequest: $TemplateRequestProvider,
  2595. $$testability: $$TestabilityProvider,
  2596. $timeout: $TimeoutProvider,
  2597. $window: $WindowProvider,
  2598. $$rAF: $$RAFProvider,
  2599. $$jqLite: $$jqLiteProvider,
  2600. $$Map: $$MapProvider,
  2601. $$cookieReader: $$CookieReaderProvider
  2602. });
  2603. }
  2604. ])
  2605. .info({ angularVersion: '1.6.3' });
  2606. }
  2607. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2608. * Any commits to this file should be reviewed with security in mind. *
  2609. * Changes to this file can potentially create security vulnerabilities. *
  2610. * An approval from 2 Core members with history of modifying *
  2611. * this file is required. *
  2612. * *
  2613. * Does the change somehow allow for arbitrary javascript to be executed? *
  2614. * Or allows for someone to change the prototype of built-in objects? *
  2615. * Or gives undesired access to variables likes document or window? *
  2616. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2617. /* global
  2618. JQLitePrototype: true,
  2619. BOOLEAN_ATTR: true,
  2620. ALIASED_ATTR: true
  2621. */
  2622. //////////////////////////////////
  2623. //JQLite
  2624. //////////////////////////////////
  2625. /**
  2626. * @ngdoc function
  2627. * @name angular.element
  2628. * @module ng
  2629. * @kind function
  2630. *
  2631. * @description
  2632. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2633. *
  2634. * If jQuery is available, `angular.element` is an alias for the
  2635. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2636. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2637. *
  2638. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2639. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2640. * commonly needed functionality with the goal of having a very small footprint.
  2641. *
  2642. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2643. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2644. * specific version of jQuery if multiple versions exist on the page.
  2645. *
  2646. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2647. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2648. *
  2649. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2650. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2651. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2652. *
  2653. * ## Angular's jqLite
  2654. * jqLite provides only the following jQuery methods:
  2655. *
  2656. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2657. * - [`after()`](http://api.jquery.com/after/)
  2658. * - [`append()`](http://api.jquery.com/append/)
  2659. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2660. * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
  2661. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2662. * - [`clone()`](http://api.jquery.com/clone/)
  2663. * - [`contents()`](http://api.jquery.com/contents/)
  2664. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2665. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2666. * - [`data()`](http://api.jquery.com/data/)
  2667. * - [`detach()`](http://api.jquery.com/detach/)
  2668. * - [`empty()`](http://api.jquery.com/empty/)
  2669. * - [`eq()`](http://api.jquery.com/eq/)
  2670. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2671. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2672. * - [`html()`](http://api.jquery.com/html/)
  2673. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2674. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2675. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2676. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2677. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2678. * - [`prepend()`](http://api.jquery.com/prepend/)
  2679. * - [`prop()`](http://api.jquery.com/prop/)
  2680. * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
  2681. * - [`remove()`](http://api.jquery.com/remove/)
  2682. * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
  2683. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2684. * - [`removeData()`](http://api.jquery.com/removeData/)
  2685. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2686. * - [`text()`](http://api.jquery.com/text/)
  2687. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2688. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2689. * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
  2690. * - [`val()`](http://api.jquery.com/val/)
  2691. * - [`wrap()`](http://api.jquery.com/wrap/)
  2692. *
  2693. * ## jQuery/jqLite Extras
  2694. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2695. *
  2696. * ### Events
  2697. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2698. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2699. * element before it is removed.
  2700. *
  2701. * ### Methods
  2702. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2703. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2704. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2705. * `'ngModel'`).
  2706. * - `injector()` - retrieves the injector of the current element or its parent.
  2707. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2708. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2709. * be enabled.
  2710. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2711. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2712. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2713. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2714. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2715. * parent element is reached.
  2716. *
  2717. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2718. * https://github.com/angular/angular.js/issues/14251 for more information.
  2719. *
  2720. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2721. * @returns {Object} jQuery object.
  2722. */
  2723. JQLite.expando = 'ng339';
  2724. var jqCache = JQLite.cache = {},
  2725. jqId = 1;
  2726. /*
  2727. * !!! This is an undocumented "private" function !!!
  2728. */
  2729. JQLite._data = function(node) {
  2730. //jQuery always returns an object on cache miss
  2731. return this.cache[node[this.expando]] || {};
  2732. };
  2733. function jqNextId() { return ++jqId; }
  2734. var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
  2735. var MS_HACK_REGEXP = /^-ms-/;
  2736. var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
  2737. var jqLiteMinErr = minErr('jqLite');
  2738. /**
  2739. * Converts kebab-case to camelCase.
  2740. * There is also a special case for the ms prefix starting with a lowercase letter.
  2741. * @param name Name to normalize
  2742. */
  2743. function cssKebabToCamel(name) {
  2744. return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
  2745. }
  2746. function fnCamelCaseReplace(all, letter) {
  2747. return letter.toUpperCase();
  2748. }
  2749. /**
  2750. * Converts kebab-case to camelCase.
  2751. * @param name Name to normalize
  2752. */
  2753. function kebabToCamel(name) {
  2754. return name
  2755. .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
  2756. }
  2757. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2758. var HTML_REGEXP = /<|&#?\w+;/;
  2759. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2760. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2761. var wrapMap = {
  2762. 'option': [1, '<select multiple="multiple">', '</select>'],
  2763. 'thead': [1, '<table>', '</table>'],
  2764. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2765. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2766. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2767. '_default': [0, '', '']
  2768. };
  2769. wrapMap.optgroup = wrapMap.option;
  2770. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2771. wrapMap.th = wrapMap.td;
  2772. function jqLiteIsTextNode(html) {
  2773. return !HTML_REGEXP.test(html);
  2774. }
  2775. function jqLiteAcceptsData(node) {
  2776. // The window object can accept data but has no nodeType
  2777. // Otherwise we are only interested in elements (1) and documents (9)
  2778. var nodeType = node.nodeType;
  2779. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2780. }
  2781. function jqLiteHasData(node) {
  2782. for (var key in jqCache[node.ng339]) {
  2783. return true;
  2784. }
  2785. return false;
  2786. }
  2787. function jqLiteCleanData(nodes) {
  2788. for (var i = 0, ii = nodes.length; i < ii; i++) {
  2789. jqLiteRemoveData(nodes[i]);
  2790. }
  2791. }
  2792. function jqLiteBuildFragment(html, context) {
  2793. var tmp, tag, wrap,
  2794. fragment = context.createDocumentFragment(),
  2795. nodes = [], i;
  2796. if (jqLiteIsTextNode(html)) {
  2797. // Convert non-html into a text node
  2798. nodes.push(context.createTextNode(html));
  2799. } else {
  2800. // Convert html into DOM nodes
  2801. tmp = fragment.appendChild(context.createElement('div'));
  2802. tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
  2803. wrap = wrapMap[tag] || wrapMap._default;
  2804. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
  2805. // Descend through wrappers to the right content
  2806. i = wrap[0];
  2807. while (i--) {
  2808. tmp = tmp.lastChild;
  2809. }
  2810. nodes = concat(nodes, tmp.childNodes);
  2811. tmp = fragment.firstChild;
  2812. tmp.textContent = '';
  2813. }
  2814. // Remove wrapper from fragment
  2815. fragment.textContent = '';
  2816. fragment.innerHTML = ''; // Clear inner HTML
  2817. forEach(nodes, function(node) {
  2818. fragment.appendChild(node);
  2819. });
  2820. return fragment;
  2821. }
  2822. function jqLiteParseHTML(html, context) {
  2823. context = context || window.document;
  2824. var parsed;
  2825. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2826. return [context.createElement(parsed[1])];
  2827. }
  2828. if ((parsed = jqLiteBuildFragment(html, context))) {
  2829. return parsed.childNodes;
  2830. }
  2831. return [];
  2832. }
  2833. function jqLiteWrapNode(node, wrapper) {
  2834. var parent = node.parentNode;
  2835. if (parent) {
  2836. parent.replaceChild(wrapper, node);
  2837. }
  2838. wrapper.appendChild(node);
  2839. }
  2840. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2841. var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
  2842. // eslint-disable-next-line no-bitwise
  2843. return !!(this.compareDocumentPosition(arg) & 16);
  2844. };
  2845. /////////////////////////////////////////////
  2846. function JQLite(element) {
  2847. if (element instanceof JQLite) {
  2848. return element;
  2849. }
  2850. var argIsString;
  2851. if (isString(element)) {
  2852. element = trim(element);
  2853. argIsString = true;
  2854. }
  2855. if (!(this instanceof JQLite)) {
  2856. if (argIsString && element.charAt(0) !== '<') {
  2857. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2858. }
  2859. return new JQLite(element);
  2860. }
  2861. if (argIsString) {
  2862. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2863. } else if (isFunction(element)) {
  2864. jqLiteReady(element);
  2865. } else {
  2866. jqLiteAddNodes(this, element);
  2867. }
  2868. }
  2869. function jqLiteClone(element) {
  2870. return element.cloneNode(true);
  2871. }
  2872. function jqLiteDealoc(element, onlyDescendants) {
  2873. if (!onlyDescendants) jqLiteRemoveData(element);
  2874. if (element.querySelectorAll) {
  2875. var descendants = element.querySelectorAll('*');
  2876. for (var i = 0, l = descendants.length; i < l; i++) {
  2877. jqLiteRemoveData(descendants[i]);
  2878. }
  2879. }
  2880. }
  2881. function jqLiteOff(element, type, fn, unsupported) {
  2882. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2883. var expandoStore = jqLiteExpandoStore(element);
  2884. var events = expandoStore && expandoStore.events;
  2885. var handle = expandoStore && expandoStore.handle;
  2886. if (!handle) return; //no listeners registered
  2887. if (!type) {
  2888. for (type in events) {
  2889. if (type !== '$destroy') {
  2890. element.removeEventListener(type, handle);
  2891. }
  2892. delete events[type];
  2893. }
  2894. } else {
  2895. var removeHandler = function(type) {
  2896. var listenerFns = events[type];
  2897. if (isDefined(fn)) {
  2898. arrayRemove(listenerFns || [], fn);
  2899. }
  2900. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2901. element.removeEventListener(type, handle);
  2902. delete events[type];
  2903. }
  2904. };
  2905. forEach(type.split(' '), function(type) {
  2906. removeHandler(type);
  2907. if (MOUSE_EVENT_MAP[type]) {
  2908. removeHandler(MOUSE_EVENT_MAP[type]);
  2909. }
  2910. });
  2911. }
  2912. }
  2913. function jqLiteRemoveData(element, name) {
  2914. var expandoId = element.ng339;
  2915. var expandoStore = expandoId && jqCache[expandoId];
  2916. if (expandoStore) {
  2917. if (name) {
  2918. delete expandoStore.data[name];
  2919. return;
  2920. }
  2921. if (expandoStore.handle) {
  2922. if (expandoStore.events.$destroy) {
  2923. expandoStore.handle({}, '$destroy');
  2924. }
  2925. jqLiteOff(element);
  2926. }
  2927. delete jqCache[expandoId];
  2928. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2929. }
  2930. }
  2931. function jqLiteExpandoStore(element, createIfNecessary) {
  2932. var expandoId = element.ng339,
  2933. expandoStore = expandoId && jqCache[expandoId];
  2934. if (createIfNecessary && !expandoStore) {
  2935. element.ng339 = expandoId = jqNextId();
  2936. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2937. }
  2938. return expandoStore;
  2939. }
  2940. function jqLiteData(element, key, value) {
  2941. if (jqLiteAcceptsData(element)) {
  2942. var prop;
  2943. var isSimpleSetter = isDefined(value);
  2944. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2945. var massGetter = !key;
  2946. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2947. var data = expandoStore && expandoStore.data;
  2948. if (isSimpleSetter) { // data('key', value)
  2949. data[kebabToCamel(key)] = value;
  2950. } else {
  2951. if (massGetter) { // data()
  2952. return data;
  2953. } else {
  2954. if (isSimpleGetter) { // data('key')
  2955. // don't force creation of expandoStore if it doesn't exist yet
  2956. return data && data[kebabToCamel(key)];
  2957. } else { // mass-setter: data({key1: val1, key2: val2})
  2958. for (prop in key) {
  2959. data[kebabToCamel(prop)] = key[prop];
  2960. }
  2961. }
  2962. }
  2963. }
  2964. }
  2965. }
  2966. function jqLiteHasClass(element, selector) {
  2967. if (!element.getAttribute) return false;
  2968. return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
  2969. indexOf(' ' + selector + ' ') > -1);
  2970. }
  2971. function jqLiteRemoveClass(element, cssClasses) {
  2972. if (cssClasses && element.setAttribute) {
  2973. forEach(cssClasses.split(' '), function(cssClass) {
  2974. element.setAttribute('class', trim(
  2975. (' ' + (element.getAttribute('class') || '') + ' ')
  2976. .replace(/[\n\t]/g, ' ')
  2977. .replace(' ' + trim(cssClass) + ' ', ' '))
  2978. );
  2979. });
  2980. }
  2981. }
  2982. function jqLiteAddClass(element, cssClasses) {
  2983. if (cssClasses && element.setAttribute) {
  2984. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2985. .replace(/[\n\t]/g, ' ');
  2986. forEach(cssClasses.split(' '), function(cssClass) {
  2987. cssClass = trim(cssClass);
  2988. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2989. existingClasses += cssClass + ' ';
  2990. }
  2991. });
  2992. element.setAttribute('class', trim(existingClasses));
  2993. }
  2994. }
  2995. function jqLiteAddNodes(root, elements) {
  2996. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2997. if (elements) {
  2998. // if a Node (the most common case)
  2999. if (elements.nodeType) {
  3000. root[root.length++] = elements;
  3001. } else {
  3002. var length = elements.length;
  3003. // if an Array or NodeList and not a Window
  3004. if (typeof length === 'number' && elements.window !== elements) {
  3005. if (length) {
  3006. for (var i = 0; i < length; i++) {
  3007. root[root.length++] = elements[i];
  3008. }
  3009. }
  3010. } else {
  3011. root[root.length++] = elements;
  3012. }
  3013. }
  3014. }
  3015. }
  3016. function jqLiteController(element, name) {
  3017. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  3018. }
  3019. function jqLiteInheritedData(element, name, value) {
  3020. // if element is the document object work with the html element instead
  3021. // this makes $(document).scope() possible
  3022. if (element.nodeType === NODE_TYPE_DOCUMENT) {
  3023. element = element.documentElement;
  3024. }
  3025. var names = isArray(name) ? name : [name];
  3026. while (element) {
  3027. for (var i = 0, ii = names.length; i < ii; i++) {
  3028. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  3029. }
  3030. // If dealing with a document fragment node with a host element, and no parent, use the host
  3031. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  3032. // to lookup parent controllers.
  3033. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  3034. }
  3035. }
  3036. function jqLiteEmpty(element) {
  3037. jqLiteDealoc(element, true);
  3038. while (element.firstChild) {
  3039. element.removeChild(element.firstChild);
  3040. }
  3041. }
  3042. function jqLiteRemove(element, keepData) {
  3043. if (!keepData) jqLiteDealoc(element);
  3044. var parent = element.parentNode;
  3045. if (parent) parent.removeChild(element);
  3046. }
  3047. function jqLiteDocumentLoaded(action, win) {
  3048. win = win || window;
  3049. if (win.document.readyState === 'complete') {
  3050. // Force the action to be run async for consistent behavior
  3051. // from the action's point of view
  3052. // i.e. it will definitely not be in a $apply
  3053. win.setTimeout(action);
  3054. } else {
  3055. // No need to unbind this handler as load is only ever called once
  3056. jqLite(win).on('load', action);
  3057. }
  3058. }
  3059. function jqLiteReady(fn) {
  3060. function trigger() {
  3061. window.document.removeEventListener('DOMContentLoaded', trigger);
  3062. window.removeEventListener('load', trigger);
  3063. fn();
  3064. }
  3065. // check if document is already loaded
  3066. if (window.document.readyState === 'complete') {
  3067. window.setTimeout(fn);
  3068. } else {
  3069. // We can not use jqLite since we are not done loading and jQuery could be loaded later.
  3070. // Works for modern browsers and IE9
  3071. window.document.addEventListener('DOMContentLoaded', trigger);
  3072. // Fallback to window.onload for others
  3073. window.addEventListener('load', trigger);
  3074. }
  3075. }
  3076. //////////////////////////////////////////
  3077. // Functions which are declared directly.
  3078. //////////////////////////////////////////
  3079. var JQLitePrototype = JQLite.prototype = {
  3080. ready: jqLiteReady,
  3081. toString: function() {
  3082. var value = [];
  3083. forEach(this, function(e) { value.push('' + e);});
  3084. return '[' + value.join(', ') + ']';
  3085. },
  3086. eq: function(index) {
  3087. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  3088. },
  3089. length: 0,
  3090. push: push,
  3091. sort: [].sort,
  3092. splice: [].splice
  3093. };
  3094. //////////////////////////////////////////
  3095. // Functions iterating getter/setters.
  3096. // these functions return self on setter and
  3097. // value on get.
  3098. //////////////////////////////////////////
  3099. var BOOLEAN_ATTR = {};
  3100. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  3101. BOOLEAN_ATTR[lowercase(value)] = value;
  3102. });
  3103. var BOOLEAN_ELEMENTS = {};
  3104. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  3105. BOOLEAN_ELEMENTS[value] = true;
  3106. });
  3107. var ALIASED_ATTR = {
  3108. 'ngMinlength': 'minlength',
  3109. 'ngMaxlength': 'maxlength',
  3110. 'ngMin': 'min',
  3111. 'ngMax': 'max',
  3112. 'ngPattern': 'pattern',
  3113. 'ngStep': 'step'
  3114. };
  3115. function getBooleanAttrName(element, name) {
  3116. // check dom last since we will most likely fail on name
  3117. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  3118. // booleanAttr is here twice to minimize DOM access
  3119. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  3120. }
  3121. function getAliasedAttrName(name) {
  3122. return ALIASED_ATTR[name];
  3123. }
  3124. forEach({
  3125. data: jqLiteData,
  3126. removeData: jqLiteRemoveData,
  3127. hasData: jqLiteHasData,
  3128. cleanData: jqLiteCleanData
  3129. }, function(fn, name) {
  3130. JQLite[name] = fn;
  3131. });
  3132. forEach({
  3133. data: jqLiteData,
  3134. inheritedData: jqLiteInheritedData,
  3135. scope: function(element) {
  3136. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3137. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  3138. },
  3139. isolateScope: function(element) {
  3140. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3141. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  3142. },
  3143. controller: jqLiteController,
  3144. injector: function(element) {
  3145. return jqLiteInheritedData(element, '$injector');
  3146. },
  3147. removeAttr: function(element, name) {
  3148. element.removeAttribute(name);
  3149. },
  3150. hasClass: jqLiteHasClass,
  3151. css: function(element, name, value) {
  3152. name = cssKebabToCamel(name);
  3153. if (isDefined(value)) {
  3154. element.style[name] = value;
  3155. } else {
  3156. return element.style[name];
  3157. }
  3158. },
  3159. attr: function(element, name, value) {
  3160. var ret;
  3161. var nodeType = element.nodeType;
  3162. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
  3163. !element.getAttribute) {
  3164. return;
  3165. }
  3166. var lowercasedName = lowercase(name);
  3167. var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
  3168. if (isDefined(value)) {
  3169. // setter
  3170. if (value === null || (value === false && isBooleanAttr)) {
  3171. element.removeAttribute(name);
  3172. } else {
  3173. element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
  3174. }
  3175. } else {
  3176. // getter
  3177. ret = element.getAttribute(name);
  3178. if (isBooleanAttr && ret !== null) {
  3179. ret = lowercasedName;
  3180. }
  3181. // Normalize non-existing attributes to undefined (as jQuery).
  3182. return ret === null ? undefined : ret;
  3183. }
  3184. },
  3185. prop: function(element, name, value) {
  3186. if (isDefined(value)) {
  3187. element[name] = value;
  3188. } else {
  3189. return element[name];
  3190. }
  3191. },
  3192. text: (function() {
  3193. getText.$dv = '';
  3194. return getText;
  3195. function getText(element, value) {
  3196. if (isUndefined(value)) {
  3197. var nodeType = element.nodeType;
  3198. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  3199. }
  3200. element.textContent = value;
  3201. }
  3202. })(),
  3203. val: function(element, value) {
  3204. if (isUndefined(value)) {
  3205. if (element.multiple && nodeName_(element) === 'select') {
  3206. var result = [];
  3207. forEach(element.options, function(option) {
  3208. if (option.selected) {
  3209. result.push(option.value || option.text);
  3210. }
  3211. });
  3212. return result;
  3213. }
  3214. return element.value;
  3215. }
  3216. element.value = value;
  3217. },
  3218. html: function(element, value) {
  3219. if (isUndefined(value)) {
  3220. return element.innerHTML;
  3221. }
  3222. jqLiteDealoc(element, true);
  3223. element.innerHTML = value;
  3224. },
  3225. empty: jqLiteEmpty
  3226. }, function(fn, name) {
  3227. /**
  3228. * Properties: writes return selection, reads return first value
  3229. */
  3230. JQLite.prototype[name] = function(arg1, arg2) {
  3231. var i, key;
  3232. var nodeCount = this.length;
  3233. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3234. // in a way that survives minification.
  3235. // jqLiteEmpty takes no arguments but is a setter.
  3236. if (fn !== jqLiteEmpty &&
  3237. (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3238. if (isObject(arg1)) {
  3239. // we are a write, but the object properties are the key/values
  3240. for (i = 0; i < nodeCount; i++) {
  3241. if (fn === jqLiteData) {
  3242. // data() takes the whole object in jQuery
  3243. fn(this[i], arg1);
  3244. } else {
  3245. for (key in arg1) {
  3246. fn(this[i], key, arg1[key]);
  3247. }
  3248. }
  3249. }
  3250. // return self for chaining
  3251. return this;
  3252. } else {
  3253. // we are a read, so read the first child.
  3254. // TODO: do we still need this?
  3255. var value = fn.$dv;
  3256. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3257. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3258. for (var j = 0; j < jj; j++) {
  3259. var nodeValue = fn(this[j], arg1, arg2);
  3260. value = value ? value + nodeValue : nodeValue;
  3261. }
  3262. return value;
  3263. }
  3264. } else {
  3265. // we are a write, so apply to all children
  3266. for (i = 0; i < nodeCount; i++) {
  3267. fn(this[i], arg1, arg2);
  3268. }
  3269. // return self for chaining
  3270. return this;
  3271. }
  3272. };
  3273. });
  3274. function createEventHandler(element, events) {
  3275. var eventHandler = function(event, type) {
  3276. // jQuery specific api
  3277. event.isDefaultPrevented = function() {
  3278. return event.defaultPrevented;
  3279. };
  3280. var eventFns = events[type || event.type];
  3281. var eventFnsLength = eventFns ? eventFns.length : 0;
  3282. if (!eventFnsLength) return;
  3283. if (isUndefined(event.immediatePropagationStopped)) {
  3284. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3285. event.stopImmediatePropagation = function() {
  3286. event.immediatePropagationStopped = true;
  3287. if (event.stopPropagation) {
  3288. event.stopPropagation();
  3289. }
  3290. if (originalStopImmediatePropagation) {
  3291. originalStopImmediatePropagation.call(event);
  3292. }
  3293. };
  3294. }
  3295. event.isImmediatePropagationStopped = function() {
  3296. return event.immediatePropagationStopped === true;
  3297. };
  3298. // Some events have special handlers that wrap the real handler
  3299. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3300. // Copy event handlers in case event handlers array is modified during execution.
  3301. if ((eventFnsLength > 1)) {
  3302. eventFns = shallowCopy(eventFns);
  3303. }
  3304. for (var i = 0; i < eventFnsLength; i++) {
  3305. if (!event.isImmediatePropagationStopped()) {
  3306. handlerWrapper(element, event, eventFns[i]);
  3307. }
  3308. }
  3309. };
  3310. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3311. // events on `element`
  3312. eventHandler.elem = element;
  3313. return eventHandler;
  3314. }
  3315. function defaultHandlerWrapper(element, event, handler) {
  3316. handler.call(element, event);
  3317. }
  3318. function specialMouseHandlerWrapper(target, event, handler) {
  3319. // Refer to jQuery's implementation of mouseenter & mouseleave
  3320. // Read about mouseenter and mouseleave:
  3321. // http://www.quirksmode.org/js/events_mouse.html#link8
  3322. var related = event.relatedTarget;
  3323. // For mousenter/leave call the handler if related is outside the target.
  3324. // NB: No relatedTarget if the mouse left/entered the browser window
  3325. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3326. handler.call(target, event);
  3327. }
  3328. }
  3329. //////////////////////////////////////////
  3330. // Functions iterating traversal.
  3331. // These functions chain results into a single
  3332. // selector.
  3333. //////////////////////////////////////////
  3334. forEach({
  3335. removeData: jqLiteRemoveData,
  3336. on: function jqLiteOn(element, type, fn, unsupported) {
  3337. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3338. // Do not add event handlers to non-elements because they will not be cleaned up.
  3339. if (!jqLiteAcceptsData(element)) {
  3340. return;
  3341. }
  3342. var expandoStore = jqLiteExpandoStore(element, true);
  3343. var events = expandoStore.events;
  3344. var handle = expandoStore.handle;
  3345. if (!handle) {
  3346. handle = expandoStore.handle = createEventHandler(element, events);
  3347. }
  3348. // http://jsperf.com/string-indexof-vs-split
  3349. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3350. var i = types.length;
  3351. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3352. var eventFns = events[type];
  3353. if (!eventFns) {
  3354. eventFns = events[type] = [];
  3355. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3356. if (type !== '$destroy' && !noEventListener) {
  3357. element.addEventListener(type, handle);
  3358. }
  3359. }
  3360. eventFns.push(fn);
  3361. };
  3362. while (i--) {
  3363. type = types[i];
  3364. if (MOUSE_EVENT_MAP[type]) {
  3365. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3366. addHandler(type, undefined, true);
  3367. } else {
  3368. addHandler(type);
  3369. }
  3370. }
  3371. },
  3372. off: jqLiteOff,
  3373. one: function(element, type, fn) {
  3374. element = jqLite(element);
  3375. //add the listener twice so that when it is called
  3376. //you can remove the original function and still be
  3377. //able to call element.off(ev, fn) normally
  3378. element.on(type, function onFn() {
  3379. element.off(type, fn);
  3380. element.off(type, onFn);
  3381. });
  3382. element.on(type, fn);
  3383. },
  3384. replaceWith: function(element, replaceNode) {
  3385. var index, parent = element.parentNode;
  3386. jqLiteDealoc(element);
  3387. forEach(new JQLite(replaceNode), function(node) {
  3388. if (index) {
  3389. parent.insertBefore(node, index.nextSibling);
  3390. } else {
  3391. parent.replaceChild(node, element);
  3392. }
  3393. index = node;
  3394. });
  3395. },
  3396. children: function(element) {
  3397. var children = [];
  3398. forEach(element.childNodes, function(element) {
  3399. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3400. children.push(element);
  3401. }
  3402. });
  3403. return children;
  3404. },
  3405. contents: function(element) {
  3406. return element.contentDocument || element.childNodes || [];
  3407. },
  3408. append: function(element, node) {
  3409. var nodeType = element.nodeType;
  3410. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3411. node = new JQLite(node);
  3412. for (var i = 0, ii = node.length; i < ii; i++) {
  3413. var child = node[i];
  3414. element.appendChild(child);
  3415. }
  3416. },
  3417. prepend: function(element, node) {
  3418. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3419. var index = element.firstChild;
  3420. forEach(new JQLite(node), function(child) {
  3421. element.insertBefore(child, index);
  3422. });
  3423. }
  3424. },
  3425. wrap: function(element, wrapNode) {
  3426. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3427. },
  3428. remove: jqLiteRemove,
  3429. detach: function(element) {
  3430. jqLiteRemove(element, true);
  3431. },
  3432. after: function(element, newElement) {
  3433. var index = element, parent = element.parentNode;
  3434. if (parent) {
  3435. newElement = new JQLite(newElement);
  3436. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3437. var node = newElement[i];
  3438. parent.insertBefore(node, index.nextSibling);
  3439. index = node;
  3440. }
  3441. }
  3442. },
  3443. addClass: jqLiteAddClass,
  3444. removeClass: jqLiteRemoveClass,
  3445. toggleClass: function(element, selector, condition) {
  3446. if (selector) {
  3447. forEach(selector.split(' '), function(className) {
  3448. var classCondition = condition;
  3449. if (isUndefined(classCondition)) {
  3450. classCondition = !jqLiteHasClass(element, className);
  3451. }
  3452. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3453. });
  3454. }
  3455. },
  3456. parent: function(element) {
  3457. var parent = element.parentNode;
  3458. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3459. },
  3460. next: function(element) {
  3461. return element.nextElementSibling;
  3462. },
  3463. find: function(element, selector) {
  3464. if (element.getElementsByTagName) {
  3465. return element.getElementsByTagName(selector);
  3466. } else {
  3467. return [];
  3468. }
  3469. },
  3470. clone: jqLiteClone,
  3471. triggerHandler: function(element, event, extraParameters) {
  3472. var dummyEvent, eventFnsCopy, handlerArgs;
  3473. var eventName = event.type || event;
  3474. var expandoStore = jqLiteExpandoStore(element);
  3475. var events = expandoStore && expandoStore.events;
  3476. var eventFns = events && events[eventName];
  3477. if (eventFns) {
  3478. // Create a dummy event to pass to the handlers
  3479. dummyEvent = {
  3480. preventDefault: function() { this.defaultPrevented = true; },
  3481. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3482. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3483. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3484. stopPropagation: noop,
  3485. type: eventName,
  3486. target: element
  3487. };
  3488. // If a custom event was provided then extend our dummy event with it
  3489. if (event.type) {
  3490. dummyEvent = extend(dummyEvent, event);
  3491. }
  3492. // Copy event handlers in case event handlers array is modified during execution.
  3493. eventFnsCopy = shallowCopy(eventFns);
  3494. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3495. forEach(eventFnsCopy, function(fn) {
  3496. if (!dummyEvent.isImmediatePropagationStopped()) {
  3497. fn.apply(element, handlerArgs);
  3498. }
  3499. });
  3500. }
  3501. }
  3502. }, function(fn, name) {
  3503. /**
  3504. * chaining functions
  3505. */
  3506. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3507. var value;
  3508. for (var i = 0, ii = this.length; i < ii; i++) {
  3509. if (isUndefined(value)) {
  3510. value = fn(this[i], arg1, arg2, arg3);
  3511. if (isDefined(value)) {
  3512. // any function which returns a value needs to be wrapped
  3513. value = jqLite(value);
  3514. }
  3515. } else {
  3516. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3517. }
  3518. }
  3519. return isDefined(value) ? value : this;
  3520. };
  3521. });
  3522. // bind legacy bind/unbind to on/off
  3523. JQLite.prototype.bind = JQLite.prototype.on;
  3524. JQLite.prototype.unbind = JQLite.prototype.off;
  3525. // Provider for private $$jqLite service
  3526. /** @this */
  3527. function $$jqLiteProvider() {
  3528. this.$get = function $$jqLite() {
  3529. return extend(JQLite, {
  3530. hasClass: function(node, classes) {
  3531. if (node.attr) node = node[0];
  3532. return jqLiteHasClass(node, classes);
  3533. },
  3534. addClass: function(node, classes) {
  3535. if (node.attr) node = node[0];
  3536. return jqLiteAddClass(node, classes);
  3537. },
  3538. removeClass: function(node, classes) {
  3539. if (node.attr) node = node[0];
  3540. return jqLiteRemoveClass(node, classes);
  3541. }
  3542. });
  3543. };
  3544. }
  3545. /**
  3546. * Computes a hash of an 'obj'.
  3547. * Hash of a:
  3548. * string is string
  3549. * number is number as string
  3550. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3551. * that is also assigned to the $$hashKey property of the object.
  3552. *
  3553. * @param obj
  3554. * @returns {string} hash string such that the same input will have the same hash string.
  3555. * The resulting string key is in 'type:hashKey' format.
  3556. */
  3557. function hashKey(obj, nextUidFn) {
  3558. var key = obj && obj.$$hashKey;
  3559. if (key) {
  3560. if (typeof key === 'function') {
  3561. key = obj.$$hashKey();
  3562. }
  3563. return key;
  3564. }
  3565. var objType = typeof obj;
  3566. if (objType === 'function' || (objType === 'object' && obj !== null)) {
  3567. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3568. } else {
  3569. key = objType + ':' + obj;
  3570. }
  3571. return key;
  3572. }
  3573. // A minimal ES2015 Map implementation.
  3574. // Should be bug/feature equivalent to the native implementations of supported browsers
  3575. // (for the features required in Angular).
  3576. // See https://kangax.github.io/compat-table/es6/#test-Map
  3577. var nanKey = Object.create(null);
  3578. function NgMapShim() {
  3579. this._keys = [];
  3580. this._values = [];
  3581. this._lastKey = NaN;
  3582. this._lastIndex = -1;
  3583. }
  3584. NgMapShim.prototype = {
  3585. _idx: function(key) {
  3586. if (key === this._lastKey) {
  3587. return this._lastIndex;
  3588. }
  3589. this._lastKey = key;
  3590. this._lastIndex = this._keys.indexOf(key);
  3591. return this._lastIndex;
  3592. },
  3593. _transformKey: function(key) {
  3594. return isNumberNaN(key) ? nanKey : key;
  3595. },
  3596. get: function(key) {
  3597. key = this._transformKey(key);
  3598. var idx = this._idx(key);
  3599. if (idx !== -1) {
  3600. return this._values[idx];
  3601. }
  3602. },
  3603. set: function(key, value) {
  3604. key = this._transformKey(key);
  3605. var idx = this._idx(key);
  3606. if (idx === -1) {
  3607. idx = this._lastIndex = this._keys.length;
  3608. }
  3609. this._keys[idx] = key;
  3610. this._values[idx] = value;
  3611. // Support: IE11
  3612. // Do not `return this` to simulate the partial IE11 implementation
  3613. },
  3614. delete: function(key) {
  3615. key = this._transformKey(key);
  3616. var idx = this._idx(key);
  3617. if (idx === -1) {
  3618. return false;
  3619. }
  3620. this._keys.splice(idx, 1);
  3621. this._values.splice(idx, 1);
  3622. this._lastKey = NaN;
  3623. this._lastIndex = -1;
  3624. return true;
  3625. }
  3626. };
  3627. // For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations
  3628. // are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map`
  3629. // implementations get more stable, we can reconsider switching to `window.Map` (when available).
  3630. var NgMap = NgMapShim;
  3631. var $$MapProvider = [/** @this */function() {
  3632. this.$get = [function() {
  3633. return NgMap;
  3634. }];
  3635. }];
  3636. /**
  3637. * @ngdoc function
  3638. * @module ng
  3639. * @name angular.injector
  3640. * @kind function
  3641. *
  3642. * @description
  3643. * Creates an injector object that can be used for retrieving services as well as for
  3644. * dependency injection (see {@link guide/di dependency injection}).
  3645. *
  3646. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3647. * {@link angular.module}. The `ng` module must be explicitly added.
  3648. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3649. * disallows argument name annotation inference.
  3650. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3651. *
  3652. * @example
  3653. * Typical usage
  3654. * ```js
  3655. * // create an injector
  3656. * var $injector = angular.injector(['ng']);
  3657. *
  3658. * // use the injector to kick off your application
  3659. * // use the type inference to auto inject arguments, or use implicit injection
  3660. * $injector.invoke(function($rootScope, $compile, $document) {
  3661. * $compile($document)($rootScope);
  3662. * $rootScope.$digest();
  3663. * });
  3664. * ```
  3665. *
  3666. * Sometimes you want to get access to the injector of a currently running Angular app
  3667. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3668. * application has been bootstrapped. You can do this using the extra `injector()` added
  3669. * to JQuery/jqLite elements. See {@link angular.element}.
  3670. *
  3671. * *This is fairly rare but could be the case if a third party library is injecting the
  3672. * markup.*
  3673. *
  3674. * In the following example a new block of HTML containing a `ng-controller`
  3675. * directive is added to the end of the document body by JQuery. We then compile and link
  3676. * it into the current AngularJS scope.
  3677. *
  3678. * ```js
  3679. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3680. * $(document.body).append($div);
  3681. *
  3682. * angular.element(document).injector().invoke(function($compile) {
  3683. * var scope = angular.element($div).scope();
  3684. * $compile($div)(scope);
  3685. * });
  3686. * ```
  3687. */
  3688. /**
  3689. * @ngdoc module
  3690. * @name auto
  3691. * @installation
  3692. * @description
  3693. *
  3694. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3695. */
  3696. var ARROW_ARG = /^([^(]+?)=>/;
  3697. var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
  3698. var FN_ARG_SPLIT = /,/;
  3699. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3700. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3701. var $injectorMinErr = minErr('$injector');
  3702. function stringifyFn(fn) {
  3703. return Function.prototype.toString.call(fn);
  3704. }
  3705. function extractArgs(fn) {
  3706. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3707. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3708. return args;
  3709. }
  3710. function anonFn(fn) {
  3711. // For anonymous functions, showing at the very least the function signature can help in
  3712. // debugging.
  3713. var args = extractArgs(fn);
  3714. if (args) {
  3715. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3716. }
  3717. return 'fn';
  3718. }
  3719. function annotate(fn, strictDi, name) {
  3720. var $inject,
  3721. argDecl,
  3722. last;
  3723. if (typeof fn === 'function') {
  3724. if (!($inject = fn.$inject)) {
  3725. $inject = [];
  3726. if (fn.length) {
  3727. if (strictDi) {
  3728. if (!isString(name) || !name) {
  3729. name = fn.name || anonFn(fn);
  3730. }
  3731. throw $injectorMinErr('strictdi',
  3732. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3733. }
  3734. argDecl = extractArgs(fn);
  3735. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3736. arg.replace(FN_ARG, function(all, underscore, name) {
  3737. $inject.push(name);
  3738. });
  3739. });
  3740. }
  3741. fn.$inject = $inject;
  3742. }
  3743. } else if (isArray(fn)) {
  3744. last = fn.length - 1;
  3745. assertArgFn(fn[last], 'fn');
  3746. $inject = fn.slice(0, last);
  3747. } else {
  3748. assertArgFn(fn, 'fn', true);
  3749. }
  3750. return $inject;
  3751. }
  3752. ///////////////////////////////////////
  3753. /**
  3754. * @ngdoc service
  3755. * @name $injector
  3756. *
  3757. * @description
  3758. *
  3759. * `$injector` is used to retrieve object instances as defined by
  3760. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3761. * and load modules.
  3762. *
  3763. * The following always holds true:
  3764. *
  3765. * ```js
  3766. * var $injector = angular.injector();
  3767. * expect($injector.get('$injector')).toBe($injector);
  3768. * expect($injector.invoke(function($injector) {
  3769. * return $injector;
  3770. * })).toBe($injector);
  3771. * ```
  3772. *
  3773. * # Injection Function Annotation
  3774. *
  3775. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3776. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3777. *
  3778. * ```js
  3779. * // inferred (only works if code not minified/obfuscated)
  3780. * $injector.invoke(function(serviceA){});
  3781. *
  3782. * // annotated
  3783. * function explicit(serviceA) {};
  3784. * explicit.$inject = ['serviceA'];
  3785. * $injector.invoke(explicit);
  3786. *
  3787. * // inline
  3788. * $injector.invoke(['serviceA', function(serviceA){}]);
  3789. * ```
  3790. *
  3791. * ## Inference
  3792. *
  3793. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3794. * can then be parsed and the function arguments can be extracted. This method of discovering
  3795. * annotations is disallowed when the injector is in strict mode.
  3796. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3797. * argument names.
  3798. *
  3799. * ## `$inject` Annotation
  3800. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3801. *
  3802. * ## Inline
  3803. * As an array of injection names, where the last item in the array is the function to call.
  3804. */
  3805. /**
  3806. * @ngdoc property
  3807. * @name $injector#modules
  3808. * @type {Object}
  3809. * @description
  3810. * A hash containing all the modules that have been loaded into the
  3811. * $injector.
  3812. *
  3813. * You can use this property to find out information about a module via the
  3814. * {@link angular.Module#info `myModule.info(...)`} method.
  3815. *
  3816. * For example:
  3817. *
  3818. * ```
  3819. * var info = $injector.modules['ngAnimate'].info();
  3820. * ```
  3821. *
  3822. * **Do not use this property to attempt to modify the modules after the application
  3823. * has been bootstrapped.**
  3824. */
  3825. /**
  3826. * @ngdoc method
  3827. * @name $injector#get
  3828. *
  3829. * @description
  3830. * Return an instance of the service.
  3831. *
  3832. * @param {string} name The name of the instance to retrieve.
  3833. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3834. * @return {*} The instance.
  3835. */
  3836. /**
  3837. * @ngdoc method
  3838. * @name $injector#invoke
  3839. *
  3840. * @description
  3841. * Invoke the method and supply the method arguments from the `$injector`.
  3842. *
  3843. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3844. * injected according to the {@link guide/di $inject Annotation} rules.
  3845. * @param {Object=} self The `this` for the invoked method.
  3846. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3847. * object first, before the `$injector` is consulted.
  3848. * @returns {*} the value returned by the invoked `fn` function.
  3849. */
  3850. /**
  3851. * @ngdoc method
  3852. * @name $injector#has
  3853. *
  3854. * @description
  3855. * Allows the user to query if the particular service exists.
  3856. *
  3857. * @param {string} name Name of the service to query.
  3858. * @returns {boolean} `true` if injector has given service.
  3859. */
  3860. /**
  3861. * @ngdoc method
  3862. * @name $injector#instantiate
  3863. * @description
  3864. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3865. * operator, and supplies all of the arguments to the constructor function as specified by the
  3866. * constructor annotation.
  3867. *
  3868. * @param {Function} Type Annotated constructor function.
  3869. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3870. * object first, before the `$injector` is consulted.
  3871. * @returns {Object} new instance of `Type`.
  3872. */
  3873. /**
  3874. * @ngdoc method
  3875. * @name $injector#annotate
  3876. *
  3877. * @description
  3878. * Returns an array of service names which the function is requesting for injection. This API is
  3879. * used by the injector to determine which services need to be injected into the function when the
  3880. * function is invoked. There are three ways in which the function can be annotated with the needed
  3881. * dependencies.
  3882. *
  3883. * # Argument names
  3884. *
  3885. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3886. * by converting the function into a string using `toString()` method and extracting the argument
  3887. * names.
  3888. * ```js
  3889. * // Given
  3890. * function MyController($scope, $route) {
  3891. * // ...
  3892. * }
  3893. *
  3894. * // Then
  3895. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3896. * ```
  3897. *
  3898. * You can disallow this method by using strict injection mode.
  3899. *
  3900. * This method does not work with code minification / obfuscation. For this reason the following
  3901. * annotation strategies are supported.
  3902. *
  3903. * # The `$inject` property
  3904. *
  3905. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3906. * represent names of services to be injected into the function.
  3907. * ```js
  3908. * // Given
  3909. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3910. * // ...
  3911. * }
  3912. * // Define function dependencies
  3913. * MyController['$inject'] = ['$scope', '$route'];
  3914. *
  3915. * // Then
  3916. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3917. * ```
  3918. *
  3919. * # The array notation
  3920. *
  3921. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3922. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3923. * a way that survives minification is a better choice:
  3924. *
  3925. * ```js
  3926. * // We wish to write this (not minification / obfuscation safe)
  3927. * injector.invoke(function($compile, $rootScope) {
  3928. * // ...
  3929. * });
  3930. *
  3931. * // We are forced to write break inlining
  3932. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3933. * // ...
  3934. * };
  3935. * tmpFn.$inject = ['$compile', '$rootScope'];
  3936. * injector.invoke(tmpFn);
  3937. *
  3938. * // To better support inline function the inline annotation is supported
  3939. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3940. * // ...
  3941. * }]);
  3942. *
  3943. * // Therefore
  3944. * expect(injector.annotate(
  3945. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3946. * ).toEqual(['$compile', '$rootScope']);
  3947. * ```
  3948. *
  3949. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3950. * be retrieved as described above.
  3951. *
  3952. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3953. *
  3954. * @returns {Array.<string>} The names of the services which the function requires.
  3955. */
  3956. /**
  3957. * @ngdoc service
  3958. * @name $provide
  3959. *
  3960. * @description
  3961. *
  3962. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3963. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3964. * {@link angular.Module}.
  3965. *
  3966. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3967. * factories** are functions which, in turn, are created by a **service provider**.
  3968. * The **service providers** are constructor functions. When instantiated they must contain a
  3969. * property called `$get`, which holds the **service factory** function.
  3970. *
  3971. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3972. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3973. * function to get the instance of the **service**.
  3974. *
  3975. * Often services have no configuration options and there is no need to add methods to the service
  3976. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3977. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3978. * services without specifying a provider.
  3979. *
  3980. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  3981. * {@link auto.$injector $injector}
  3982. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  3983. * providers and services.
  3984. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  3985. * services, not providers.
  3986. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  3987. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3988. * given factory function.
  3989. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  3990. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3991. * a new object using the given constructor function.
  3992. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  3993. * will be able to modify or replace the implementation of another service.
  3994. *
  3995. * See the individual methods for more information and examples.
  3996. */
  3997. /**
  3998. * @ngdoc method
  3999. * @name $provide#provider
  4000. * @description
  4001. *
  4002. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  4003. * are constructor functions, whose instances are responsible for "providing" a factory for a
  4004. * service.
  4005. *
  4006. * Service provider names start with the name of the service they provide followed by `Provider`.
  4007. * For example, the {@link ng.$log $log} service has a provider called
  4008. * {@link ng.$logProvider $logProvider}.
  4009. *
  4010. * Service provider objects can have additional methods which allow configuration of the provider
  4011. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  4012. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  4013. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  4014. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  4015. * console or not.
  4016. *
  4017. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  4018. 'Provider'` key.
  4019. * @param {(Object|function())} provider If the provider is:
  4020. *
  4021. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  4022. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  4023. * - `Constructor`: a new instance of the provider will be created using
  4024. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  4025. *
  4026. * @returns {Object} registered provider instance
  4027. * @example
  4028. *
  4029. * The following example shows how to create a simple event tracking service and register it using
  4030. * {@link auto.$provide#provider $provide.provider()}.
  4031. *
  4032. * ```js
  4033. * // Define the eventTracker provider
  4034. * function EventTrackerProvider() {
  4035. * var trackingUrl = '/track';
  4036. *
  4037. * // A provider method for configuring where the tracked events should been saved
  4038. * this.setTrackingUrl = function(url) {
  4039. * trackingUrl = url;
  4040. * };
  4041. *
  4042. * // The service factory function
  4043. * this.$get = ['$http', function($http) {
  4044. * var trackedEvents = {};
  4045. * return {
  4046. * // Call this to track an event
  4047. * event: function(event) {
  4048. * var count = trackedEvents[event] || 0;
  4049. * count += 1;
  4050. * trackedEvents[event] = count;
  4051. * return count;
  4052. * },
  4053. * // Call this to save the tracked events to the trackingUrl
  4054. * save: function() {
  4055. * $http.post(trackingUrl, trackedEvents);
  4056. * }
  4057. * };
  4058. * }];
  4059. * }
  4060. *
  4061. * describe('eventTracker', function() {
  4062. * var postSpy;
  4063. *
  4064. * beforeEach(module(function($provide) {
  4065. * // Register the eventTracker provider
  4066. * $provide.provider('eventTracker', EventTrackerProvider);
  4067. * }));
  4068. *
  4069. * beforeEach(module(function(eventTrackerProvider) {
  4070. * // Configure eventTracker provider
  4071. * eventTrackerProvider.setTrackingUrl('/custom-track');
  4072. * }));
  4073. *
  4074. * it('tracks events', inject(function(eventTracker) {
  4075. * expect(eventTracker.event('login')).toEqual(1);
  4076. * expect(eventTracker.event('login')).toEqual(2);
  4077. * }));
  4078. *
  4079. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  4080. * postSpy = spyOn($http, 'post');
  4081. * eventTracker.event('login');
  4082. * eventTracker.save();
  4083. * expect(postSpy).toHaveBeenCalled();
  4084. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  4085. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  4086. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  4087. * }));
  4088. * });
  4089. * ```
  4090. */
  4091. /**
  4092. * @ngdoc method
  4093. * @name $provide#factory
  4094. * @description
  4095. *
  4096. * Register a **service factory**, which will be called to return the service instance.
  4097. * This is short for registering a service where its provider consists of only a `$get` property,
  4098. * which is the given service factory function.
  4099. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  4100. * configure your service in a provider.
  4101. *
  4102. * @param {string} name The name of the instance.
  4103. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  4104. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  4105. * @returns {Object} registered provider instance
  4106. *
  4107. * @example
  4108. * Here is an example of registering a service
  4109. * ```js
  4110. * $provide.factory('ping', ['$http', function($http) {
  4111. * return function ping() {
  4112. * return $http.send('/ping');
  4113. * };
  4114. * }]);
  4115. * ```
  4116. * You would then inject and use this service like this:
  4117. * ```js
  4118. * someModule.controller('Ctrl', ['ping', function(ping) {
  4119. * ping();
  4120. * }]);
  4121. * ```
  4122. */
  4123. /**
  4124. * @ngdoc method
  4125. * @name $provide#service
  4126. * @description
  4127. *
  4128. * Register a **service constructor**, which will be invoked with `new` to create the service
  4129. * instance.
  4130. * This is short for registering a service where its provider's `$get` property is a factory
  4131. * function that returns an instance instantiated by the injector from the service constructor
  4132. * function.
  4133. *
  4134. * Internally it looks a bit like this:
  4135. *
  4136. * ```
  4137. * {
  4138. * $get: function() {
  4139. * return $injector.instantiate(constructor);
  4140. * }
  4141. * }
  4142. * ```
  4143. *
  4144. *
  4145. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  4146. * as a type/class.
  4147. *
  4148. * @param {string} name The name of the instance.
  4149. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  4150. * that will be instantiated.
  4151. * @returns {Object} registered provider instance
  4152. *
  4153. * @example
  4154. * Here is an example of registering a service using
  4155. * {@link auto.$provide#service $provide.service(class)}.
  4156. * ```js
  4157. * var Ping = function($http) {
  4158. * this.$http = $http;
  4159. * };
  4160. *
  4161. * Ping.$inject = ['$http'];
  4162. *
  4163. * Ping.prototype.send = function() {
  4164. * return this.$http.get('/ping');
  4165. * };
  4166. * $provide.service('ping', Ping);
  4167. * ```
  4168. * You would then inject and use this service like this:
  4169. * ```js
  4170. * someModule.controller('Ctrl', ['ping', function(ping) {
  4171. * ping.send();
  4172. * }]);
  4173. * ```
  4174. */
  4175. /**
  4176. * @ngdoc method
  4177. * @name $provide#value
  4178. * @description
  4179. *
  4180. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  4181. * number, an array, an object or a function. This is short for registering a service where its
  4182. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  4183. * service**. That also means it is not possible to inject other services into a value service.
  4184. *
  4185. * Value services are similar to constant services, except that they cannot be injected into a
  4186. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  4187. * an Angular {@link auto.$provide#decorator decorator}.
  4188. *
  4189. * @param {string} name The name of the instance.
  4190. * @param {*} value The value.
  4191. * @returns {Object} registered provider instance
  4192. *
  4193. * @example
  4194. * Here are some examples of creating value services.
  4195. * ```js
  4196. * $provide.value('ADMIN_USER', 'admin');
  4197. *
  4198. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  4199. *
  4200. * $provide.value('halfOf', function(value) {
  4201. * return value / 2;
  4202. * });
  4203. * ```
  4204. */
  4205. /**
  4206. * @ngdoc method
  4207. * @name $provide#constant
  4208. * @description
  4209. *
  4210. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  4211. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  4212. * possible to inject other services into a constant.
  4213. *
  4214. * But unlike {@link auto.$provide#value value}, a constant can be
  4215. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  4216. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  4217. *
  4218. * @param {string} name The name of the constant.
  4219. * @param {*} value The constant value.
  4220. * @returns {Object} registered instance
  4221. *
  4222. * @example
  4223. * Here a some examples of creating constants:
  4224. * ```js
  4225. * $provide.constant('SHARD_HEIGHT', 306);
  4226. *
  4227. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  4228. *
  4229. * $provide.constant('double', function(value) {
  4230. * return value * 2;
  4231. * });
  4232. * ```
  4233. */
  4234. /**
  4235. * @ngdoc method
  4236. * @name $provide#decorator
  4237. * @description
  4238. *
  4239. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  4240. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  4241. * service. The return value of the decorator function may be the original service, or a new service
  4242. * that replaces (or wraps and delegates to) the original service.
  4243. *
  4244. * You can find out more about using decorators in the {@link guide/decorators} guide.
  4245. *
  4246. * @param {string} name The name of the service to decorate.
  4247. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  4248. * provided and should return the decorated service instance. The function is called using
  4249. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  4250. * Local injection arguments:
  4251. *
  4252. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  4253. * decorated or delegated to.
  4254. *
  4255. * @example
  4256. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  4257. * calls to {@link ng.$log#error $log.warn()}.
  4258. * ```js
  4259. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4260. * $delegate.warn = $delegate.error;
  4261. * return $delegate;
  4262. * }]);
  4263. * ```
  4264. */
  4265. function createInjector(modulesToLoad, strictDi) {
  4266. strictDi = (strictDi === true);
  4267. var INSTANTIATING = {},
  4268. providerSuffix = 'Provider',
  4269. path = [],
  4270. loadedModules = new NgMap(),
  4271. providerCache = {
  4272. $provide: {
  4273. provider: supportObject(provider),
  4274. factory: supportObject(factory),
  4275. service: supportObject(service),
  4276. value: supportObject(value),
  4277. constant: supportObject(constant),
  4278. decorator: decorator
  4279. }
  4280. },
  4281. providerInjector = (providerCache.$injector =
  4282. createInternalInjector(providerCache, function(serviceName, caller) {
  4283. if (angular.isString(caller)) {
  4284. path.push(caller);
  4285. }
  4286. throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
  4287. })),
  4288. instanceCache = {},
  4289. protoInstanceInjector =
  4290. createInternalInjector(instanceCache, function(serviceName, caller) {
  4291. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4292. return instanceInjector.invoke(
  4293. provider.$get, provider, undefined, serviceName);
  4294. }),
  4295. instanceInjector = protoInstanceInjector;
  4296. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4297. instanceInjector.modules = providerInjector.modules = createMap();
  4298. var runBlocks = loadModules(modulesToLoad);
  4299. instanceInjector = protoInstanceInjector.get('$injector');
  4300. instanceInjector.strictDi = strictDi;
  4301. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4302. return instanceInjector;
  4303. ////////////////////////////////////
  4304. // $provider
  4305. ////////////////////////////////////
  4306. function supportObject(delegate) {
  4307. return function(key, value) {
  4308. if (isObject(key)) {
  4309. forEach(key, reverseParams(delegate));
  4310. } else {
  4311. return delegate(key, value);
  4312. }
  4313. };
  4314. }
  4315. function provider(name, provider_) {
  4316. assertNotHasOwnProperty(name, 'service');
  4317. if (isFunction(provider_) || isArray(provider_)) {
  4318. provider_ = providerInjector.instantiate(provider_);
  4319. }
  4320. if (!provider_.$get) {
  4321. throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
  4322. }
  4323. return (providerCache[name + providerSuffix] = provider_);
  4324. }
  4325. function enforceReturnValue(name, factory) {
  4326. return /** @this */ function enforcedReturnValue() {
  4327. var result = instanceInjector.invoke(factory, this);
  4328. if (isUndefined(result)) {
  4329. throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
  4330. }
  4331. return result;
  4332. };
  4333. }
  4334. function factory(name, factoryFn, enforce) {
  4335. return provider(name, {
  4336. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4337. });
  4338. }
  4339. function service(name, constructor) {
  4340. return factory(name, ['$injector', function($injector) {
  4341. return $injector.instantiate(constructor);
  4342. }]);
  4343. }
  4344. function value(name, val) { return factory(name, valueFn(val), false); }
  4345. function constant(name, value) {
  4346. assertNotHasOwnProperty(name, 'constant');
  4347. providerCache[name] = value;
  4348. instanceCache[name] = value;
  4349. }
  4350. function decorator(serviceName, decorFn) {
  4351. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4352. orig$get = origProvider.$get;
  4353. origProvider.$get = function() {
  4354. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4355. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4356. };
  4357. }
  4358. ////////////////////////////////////
  4359. // Module Loading
  4360. ////////////////////////////////////
  4361. function loadModules(modulesToLoad) {
  4362. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4363. var runBlocks = [], moduleFn;
  4364. forEach(modulesToLoad, function(module) {
  4365. if (loadedModules.get(module)) return;
  4366. loadedModules.set(module, true);
  4367. function runInvokeQueue(queue) {
  4368. var i, ii;
  4369. for (i = 0, ii = queue.length; i < ii; i++) {
  4370. var invokeArgs = queue[i],
  4371. provider = providerInjector.get(invokeArgs[0]);
  4372. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4373. }
  4374. }
  4375. try {
  4376. if (isString(module)) {
  4377. moduleFn = angularModule(module);
  4378. instanceInjector.modules[module] = moduleFn;
  4379. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4380. runInvokeQueue(moduleFn._invokeQueue);
  4381. runInvokeQueue(moduleFn._configBlocks);
  4382. } else if (isFunction(module)) {
  4383. runBlocks.push(providerInjector.invoke(module));
  4384. } else if (isArray(module)) {
  4385. runBlocks.push(providerInjector.invoke(module));
  4386. } else {
  4387. assertArgFn(module, 'module');
  4388. }
  4389. } catch (e) {
  4390. if (isArray(module)) {
  4391. module = module[module.length - 1];
  4392. }
  4393. if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
  4394. // Safari & FF's stack traces don't contain error.message content
  4395. // unlike those of Chrome and IE
  4396. // So if stack doesn't contain message, we create a new string that contains both.
  4397. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4398. // eslint-disable-next-line no-ex-assign
  4399. e = e.message + '\n' + e.stack;
  4400. }
  4401. throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
  4402. module, e.stack || e.message || e);
  4403. }
  4404. });
  4405. return runBlocks;
  4406. }
  4407. ////////////////////////////////////
  4408. // internal Injector
  4409. ////////////////////////////////////
  4410. function createInternalInjector(cache, factory) {
  4411. function getService(serviceName, caller) {
  4412. if (cache.hasOwnProperty(serviceName)) {
  4413. if (cache[serviceName] === INSTANTIATING) {
  4414. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4415. serviceName + ' <- ' + path.join(' <- '));
  4416. }
  4417. return cache[serviceName];
  4418. } else {
  4419. try {
  4420. path.unshift(serviceName);
  4421. cache[serviceName] = INSTANTIATING;
  4422. cache[serviceName] = factory(serviceName, caller);
  4423. return cache[serviceName];
  4424. } catch (err) {
  4425. if (cache[serviceName] === INSTANTIATING) {
  4426. delete cache[serviceName];
  4427. }
  4428. throw err;
  4429. } finally {
  4430. path.shift();
  4431. }
  4432. }
  4433. }
  4434. function injectionArgs(fn, locals, serviceName) {
  4435. var args = [],
  4436. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4437. for (var i = 0, length = $inject.length; i < length; i++) {
  4438. var key = $inject[i];
  4439. if (typeof key !== 'string') {
  4440. throw $injectorMinErr('itkn',
  4441. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4442. }
  4443. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4444. getService(key, serviceName));
  4445. }
  4446. return args;
  4447. }
  4448. function isClass(func) {
  4449. // Support: IE 9-11 only
  4450. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4451. if (msie || typeof func !== 'function') {
  4452. return false;
  4453. }
  4454. var result = func.$$ngIsClass;
  4455. if (!isBoolean(result)) {
  4456. // Support: Edge 12-13 only
  4457. // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
  4458. result = func.$$ngIsClass = /^(?:class\b|constructor\()/.test(stringifyFn(func));
  4459. }
  4460. return result;
  4461. }
  4462. function invoke(fn, self, locals, serviceName) {
  4463. if (typeof locals === 'string') {
  4464. serviceName = locals;
  4465. locals = null;
  4466. }
  4467. var args = injectionArgs(fn, locals, serviceName);
  4468. if (isArray(fn)) {
  4469. fn = fn[fn.length - 1];
  4470. }
  4471. if (!isClass(fn)) {
  4472. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4473. // #5388
  4474. return fn.apply(self, args);
  4475. } else {
  4476. args.unshift(null);
  4477. return new (Function.prototype.bind.apply(fn, args))();
  4478. }
  4479. }
  4480. function instantiate(Type, locals, serviceName) {
  4481. // Check if Type is annotated and use just the given function at n-1 as parameter
  4482. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4483. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4484. var args = injectionArgs(Type, locals, serviceName);
  4485. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4486. args.unshift(null);
  4487. return new (Function.prototype.bind.apply(ctor, args))();
  4488. }
  4489. return {
  4490. invoke: invoke,
  4491. instantiate: instantiate,
  4492. get: getService,
  4493. annotate: createInjector.$$annotate,
  4494. has: function(name) {
  4495. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4496. }
  4497. };
  4498. }
  4499. }
  4500. createInjector.$$annotate = annotate;
  4501. /**
  4502. * @ngdoc provider
  4503. * @name $anchorScrollProvider
  4504. * @this
  4505. *
  4506. * @description
  4507. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4508. * {@link ng.$location#hash $location.hash()} changes.
  4509. */
  4510. function $AnchorScrollProvider() {
  4511. var autoScrollingEnabled = true;
  4512. /**
  4513. * @ngdoc method
  4514. * @name $anchorScrollProvider#disableAutoScrolling
  4515. *
  4516. * @description
  4517. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4518. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4519. * Use this method to disable automatic scrolling.
  4520. *
  4521. * If automatic scrolling is disabled, one must explicitly call
  4522. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4523. * current hash.
  4524. */
  4525. this.disableAutoScrolling = function() {
  4526. autoScrollingEnabled = false;
  4527. };
  4528. /**
  4529. * @ngdoc service
  4530. * @name $anchorScroll
  4531. * @kind function
  4532. * @requires $window
  4533. * @requires $location
  4534. * @requires $rootScope
  4535. *
  4536. * @description
  4537. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4538. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4539. * in the
  4540. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4541. *
  4542. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4543. * match any anchor whenever it changes. This can be disabled by calling
  4544. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4545. *
  4546. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4547. * vertical scroll-offset (either fixed or dynamic).
  4548. *
  4549. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4550. * {@link ng.$location#hash $location.hash()} will be used.
  4551. *
  4552. * @property {(number|function|jqLite)} yOffset
  4553. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4554. * positioned elements at the top of the page, such as navbars, headers etc.
  4555. *
  4556. * `yOffset` can be specified in various ways:
  4557. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4558. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4559. * a number representing the offset (in pixels).<br /><br />
  4560. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4561. * the top of the page to the element's bottom will be used as offset.<br />
  4562. * **Note**: The element will be taken into account only as long as its `position` is set to
  4563. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4564. * their height and/or positioning according to the viewport's size.
  4565. *
  4566. * <br />
  4567. * <div class="alert alert-warning">
  4568. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4569. * not some child element.
  4570. * </div>
  4571. *
  4572. * @example
  4573. <example module="anchorScrollExample" name="anchor-scroll">
  4574. <file name="index.html">
  4575. <div id="scrollArea" ng-controller="ScrollController">
  4576. <a ng-click="gotoBottom()">Go to bottom</a>
  4577. <a id="bottom"></a> You're at the bottom!
  4578. </div>
  4579. </file>
  4580. <file name="script.js">
  4581. angular.module('anchorScrollExample', [])
  4582. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4583. function($scope, $location, $anchorScroll) {
  4584. $scope.gotoBottom = function() {
  4585. // set the location.hash to the id of
  4586. // the element you wish to scroll to.
  4587. $location.hash('bottom');
  4588. // call $anchorScroll()
  4589. $anchorScroll();
  4590. };
  4591. }]);
  4592. </file>
  4593. <file name="style.css">
  4594. #scrollArea {
  4595. height: 280px;
  4596. overflow: auto;
  4597. }
  4598. #bottom {
  4599. display: block;
  4600. margin-top: 2000px;
  4601. }
  4602. </file>
  4603. </example>
  4604. *
  4605. * <hr />
  4606. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4607. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4608. *
  4609. * @example
  4610. <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
  4611. <file name="index.html">
  4612. <div class="fixed-header" ng-controller="headerCtrl">
  4613. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4614. Go to anchor {{x}}
  4615. </a>
  4616. </div>
  4617. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4618. Anchor {{x}} of 5
  4619. </div>
  4620. </file>
  4621. <file name="script.js">
  4622. angular.module('anchorScrollOffsetExample', [])
  4623. .run(['$anchorScroll', function($anchorScroll) {
  4624. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4625. }])
  4626. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4627. function($anchorScroll, $location, $scope) {
  4628. $scope.gotoAnchor = function(x) {
  4629. var newHash = 'anchor' + x;
  4630. if ($location.hash() !== newHash) {
  4631. // set the $location.hash to `newHash` and
  4632. // $anchorScroll will automatically scroll to it
  4633. $location.hash('anchor' + x);
  4634. } else {
  4635. // call $anchorScroll() explicitly,
  4636. // since $location.hash hasn't changed
  4637. $anchorScroll();
  4638. }
  4639. };
  4640. }
  4641. ]);
  4642. </file>
  4643. <file name="style.css">
  4644. body {
  4645. padding-top: 50px;
  4646. }
  4647. .anchor {
  4648. border: 2px dashed DarkOrchid;
  4649. padding: 10px 10px 200px 10px;
  4650. }
  4651. .fixed-header {
  4652. background-color: rgba(0, 0, 0, 0.2);
  4653. height: 50px;
  4654. position: fixed;
  4655. top: 0; left: 0; right: 0;
  4656. }
  4657. .fixed-header > a {
  4658. display: inline-block;
  4659. margin: 5px 15px;
  4660. }
  4661. </file>
  4662. </example>
  4663. */
  4664. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4665. var document = $window.document;
  4666. // Helper function to get first anchor from a NodeList
  4667. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4668. // and working in all supported browsers.)
  4669. function getFirstAnchor(list) {
  4670. var result = null;
  4671. Array.prototype.some.call(list, function(element) {
  4672. if (nodeName_(element) === 'a') {
  4673. result = element;
  4674. return true;
  4675. }
  4676. });
  4677. return result;
  4678. }
  4679. function getYOffset() {
  4680. var offset = scroll.yOffset;
  4681. if (isFunction(offset)) {
  4682. offset = offset();
  4683. } else if (isElement(offset)) {
  4684. var elem = offset[0];
  4685. var style = $window.getComputedStyle(elem);
  4686. if (style.position !== 'fixed') {
  4687. offset = 0;
  4688. } else {
  4689. offset = elem.getBoundingClientRect().bottom;
  4690. }
  4691. } else if (!isNumber(offset)) {
  4692. offset = 0;
  4693. }
  4694. return offset;
  4695. }
  4696. function scrollTo(elem) {
  4697. if (elem) {
  4698. elem.scrollIntoView();
  4699. var offset = getYOffset();
  4700. if (offset) {
  4701. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4702. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4703. // top of the viewport.
  4704. //
  4705. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4706. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4707. // way down the page.
  4708. //
  4709. // This is often the case for elements near the bottom of the page.
  4710. //
  4711. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4712. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4713. // desired position.
  4714. var elemTop = elem.getBoundingClientRect().top;
  4715. $window.scrollBy(0, elemTop - offset);
  4716. }
  4717. } else {
  4718. $window.scrollTo(0, 0);
  4719. }
  4720. }
  4721. function scroll(hash) {
  4722. // Allow numeric hashes
  4723. hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
  4724. var elm;
  4725. // empty hash, scroll to the top of the page
  4726. if (!hash) scrollTo(null);
  4727. // element with given id
  4728. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4729. // first anchor with given name :-D
  4730. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4731. // no element and hash === 'top', scroll to the top of the page
  4732. else if (hash === 'top') scrollTo(null);
  4733. }
  4734. // does not scroll when user clicks on anchor link that is currently on
  4735. // (no url change, no $location.hash() change), browser native does scroll
  4736. if (autoScrollingEnabled) {
  4737. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4738. function autoScrollWatchAction(newVal, oldVal) {
  4739. // skip the initial scroll if $location.hash is empty
  4740. if (newVal === oldVal && newVal === '') return;
  4741. jqLiteDocumentLoaded(function() {
  4742. $rootScope.$evalAsync(scroll);
  4743. });
  4744. });
  4745. }
  4746. return scroll;
  4747. }];
  4748. }
  4749. var $animateMinErr = minErr('$animate');
  4750. var ELEMENT_NODE = 1;
  4751. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4752. function mergeClasses(a,b) {
  4753. if (!a && !b) return '';
  4754. if (!a) return b;
  4755. if (!b) return a;
  4756. if (isArray(a)) a = a.join(' ');
  4757. if (isArray(b)) b = b.join(' ');
  4758. return a + ' ' + b;
  4759. }
  4760. function extractElementNode(element) {
  4761. for (var i = 0; i < element.length; i++) {
  4762. var elm = element[i];
  4763. if (elm.nodeType === ELEMENT_NODE) {
  4764. return elm;
  4765. }
  4766. }
  4767. }
  4768. function splitClasses(classes) {
  4769. if (isString(classes)) {
  4770. classes = classes.split(' ');
  4771. }
  4772. // Use createMap() to prevent class assumptions involving property names in
  4773. // Object.prototype
  4774. var obj = createMap();
  4775. forEach(classes, function(klass) {
  4776. // sometimes the split leaves empty string values
  4777. // incase extra spaces were applied to the options
  4778. if (klass.length) {
  4779. obj[klass] = true;
  4780. }
  4781. });
  4782. return obj;
  4783. }
  4784. // if any other type of options value besides an Object value is
  4785. // passed into the $animate.method() animation then this helper code
  4786. // will be run which will ignore it. While this patch is not the
  4787. // greatest solution to this, a lot of existing plugins depend on
  4788. // $animate to either call the callback (< 1.2) or return a promise
  4789. // that can be changed. This helper function ensures that the options
  4790. // are wiped clean incase a callback function is provided.
  4791. function prepareAnimateOptions(options) {
  4792. return isObject(options)
  4793. ? options
  4794. : {};
  4795. }
  4796. var $$CoreAnimateJsProvider = /** @this */ function() {
  4797. this.$get = noop;
  4798. };
  4799. // this is prefixed with Core since it conflicts with
  4800. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4801. var $$CoreAnimateQueueProvider = /** @this */ function() {
  4802. var postDigestQueue = new NgMap();
  4803. var postDigestElements = [];
  4804. this.$get = ['$$AnimateRunner', '$rootScope',
  4805. function($$AnimateRunner, $rootScope) {
  4806. return {
  4807. enabled: noop,
  4808. on: noop,
  4809. off: noop,
  4810. pin: noop,
  4811. push: function(element, event, options, domOperation) {
  4812. if (domOperation) {
  4813. domOperation();
  4814. }
  4815. options = options || {};
  4816. if (options.from) {
  4817. element.css(options.from);
  4818. }
  4819. if (options.to) {
  4820. element.css(options.to);
  4821. }
  4822. if (options.addClass || options.removeClass) {
  4823. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4824. }
  4825. var runner = new $$AnimateRunner();
  4826. // since there are no animations to run the runner needs to be
  4827. // notified that the animation call is complete.
  4828. runner.complete();
  4829. return runner;
  4830. }
  4831. };
  4832. function updateData(data, classes, value) {
  4833. var changed = false;
  4834. if (classes) {
  4835. classes = isString(classes) ? classes.split(' ') :
  4836. isArray(classes) ? classes : [];
  4837. forEach(classes, function(className) {
  4838. if (className) {
  4839. changed = true;
  4840. data[className] = value;
  4841. }
  4842. });
  4843. }
  4844. return changed;
  4845. }
  4846. function handleCSSClassChanges() {
  4847. forEach(postDigestElements, function(element) {
  4848. var data = postDigestQueue.get(element);
  4849. if (data) {
  4850. var existing = splitClasses(element.attr('class'));
  4851. var toAdd = '';
  4852. var toRemove = '';
  4853. forEach(data, function(status, className) {
  4854. var hasClass = !!existing[className];
  4855. if (status !== hasClass) {
  4856. if (status) {
  4857. toAdd += (toAdd.length ? ' ' : '') + className;
  4858. } else {
  4859. toRemove += (toRemove.length ? ' ' : '') + className;
  4860. }
  4861. }
  4862. });
  4863. forEach(element, function(elm) {
  4864. if (toAdd) {
  4865. jqLiteAddClass(elm, toAdd);
  4866. }
  4867. if (toRemove) {
  4868. jqLiteRemoveClass(elm, toRemove);
  4869. }
  4870. });
  4871. postDigestQueue.delete(element);
  4872. }
  4873. });
  4874. postDigestElements.length = 0;
  4875. }
  4876. function addRemoveClassesPostDigest(element, add, remove) {
  4877. var data = postDigestQueue.get(element) || {};
  4878. var classesAdded = updateData(data, add, true);
  4879. var classesRemoved = updateData(data, remove, false);
  4880. if (classesAdded || classesRemoved) {
  4881. postDigestQueue.set(element, data);
  4882. postDigestElements.push(element);
  4883. if (postDigestElements.length === 1) {
  4884. $rootScope.$$postDigest(handleCSSClassChanges);
  4885. }
  4886. }
  4887. }
  4888. }];
  4889. };
  4890. /**
  4891. * @ngdoc provider
  4892. * @name $animateProvider
  4893. *
  4894. * @description
  4895. * Default implementation of $animate that doesn't perform any animations, instead just
  4896. * synchronously performs DOM updates and resolves the returned runner promise.
  4897. *
  4898. * In order to enable animations the `ngAnimate` module has to be loaded.
  4899. *
  4900. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4901. */
  4902. var $AnimateProvider = ['$provide', /** @this */ function($provide) {
  4903. var provider = this;
  4904. var classNameFilter = null;
  4905. this.$$registeredAnimations = Object.create(null);
  4906. /**
  4907. * @ngdoc method
  4908. * @name $animateProvider#register
  4909. *
  4910. * @description
  4911. * Registers a new injectable animation factory function. The factory function produces the
  4912. * animation object which contains callback functions for each event that is expected to be
  4913. * animated.
  4914. *
  4915. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4916. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4917. * on the type of animation additional arguments will be injected into the animation function. The
  4918. * list below explains the function signatures for the different animation methods:
  4919. *
  4920. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4921. * - addClass: function(element, addedClasses, doneFunction, options)
  4922. * - removeClass: function(element, removedClasses, doneFunction, options)
  4923. * - enter, leave, move: function(element, doneFunction, options)
  4924. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4925. *
  4926. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4927. *
  4928. * ```js
  4929. * return {
  4930. * //enter, leave, move signature
  4931. * eventFn : function(element, done, options) {
  4932. * //code to run the animation
  4933. * //once complete, then run done()
  4934. * return function endFunction(wasCancelled) {
  4935. * //code to cancel the animation
  4936. * }
  4937. * }
  4938. * }
  4939. * ```
  4940. *
  4941. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4942. * @param {Function} factory The factory function that will be executed to return the animation
  4943. * object.
  4944. */
  4945. this.register = function(name, factory) {
  4946. if (name && name.charAt(0) !== '.') {
  4947. throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
  4948. }
  4949. var key = name + '-animation';
  4950. provider.$$registeredAnimations[name.substr(1)] = key;
  4951. $provide.factory(key, factory);
  4952. };
  4953. /**
  4954. * @ngdoc method
  4955. * @name $animateProvider#classNameFilter
  4956. *
  4957. * @description
  4958. * Sets and/or returns the CSS class regular expression that is checked when performing
  4959. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4960. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4961. * When setting the `classNameFilter` value, animations will only be performed on elements
  4962. * that successfully match the filter expression. This in turn can boost performance
  4963. * for low-powered devices as well as applications containing a lot of structural operations.
  4964. * @param {RegExp=} expression The className expression which will be checked against all animations
  4965. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4966. */
  4967. this.classNameFilter = function(expression) {
  4968. if (arguments.length === 1) {
  4969. classNameFilter = (expression instanceof RegExp) ? expression : null;
  4970. if (classNameFilter) {
  4971. var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]');
  4972. if (reservedRegex.test(classNameFilter.toString())) {
  4973. classNameFilter = null;
  4974. throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4975. }
  4976. }
  4977. }
  4978. return classNameFilter;
  4979. };
  4980. this.$get = ['$$animateQueue', function($$animateQueue) {
  4981. function domInsert(element, parentElement, afterElement) {
  4982. // if for some reason the previous element was removed
  4983. // from the dom sometime before this code runs then let's
  4984. // just stick to using the parent element as the anchor
  4985. if (afterElement) {
  4986. var afterNode = extractElementNode(afterElement);
  4987. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4988. afterElement = null;
  4989. }
  4990. }
  4991. if (afterElement) {
  4992. afterElement.after(element);
  4993. } else {
  4994. parentElement.prepend(element);
  4995. }
  4996. }
  4997. /**
  4998. * @ngdoc service
  4999. * @name $animate
  5000. * @description The $animate service exposes a series of DOM utility methods that provide support
  5001. * for animation hooks. The default behavior is the application of DOM operations, however,
  5002. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  5003. * to ensure that animation runs with the triggered DOM operation.
  5004. *
  5005. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  5006. * included and only when it is active then the animation hooks that `$animate` triggers will be
  5007. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  5008. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  5009. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  5010. *
  5011. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  5012. *
  5013. * To learn more about enabling animation support, click here to visit the
  5014. * {@link ngAnimate ngAnimate module page}.
  5015. */
  5016. return {
  5017. // we don't call it directly since non-existant arguments may
  5018. // be interpreted as null within the sub enabled function
  5019. /**
  5020. *
  5021. * @ngdoc method
  5022. * @name $animate#on
  5023. * @kind function
  5024. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  5025. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  5026. * is fired with the following params:
  5027. *
  5028. * ```js
  5029. * $animate.on('enter', container,
  5030. * function callback(element, phase) {
  5031. * // cool we detected an enter animation within the container
  5032. * }
  5033. * );
  5034. * ```
  5035. *
  5036. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  5037. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  5038. * as well as among its children
  5039. * @param {Function} callback the callback function that will be fired when the listener is triggered
  5040. *
  5041. * The arguments present in the callback function are:
  5042. * * `element` - The captured DOM element that the animation was fired on.
  5043. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  5044. */
  5045. on: $$animateQueue.on,
  5046. /**
  5047. *
  5048. * @ngdoc method
  5049. * @name $animate#off
  5050. * @kind function
  5051. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  5052. * can be used in three different ways depending on the arguments:
  5053. *
  5054. * ```js
  5055. * // remove all the animation event listeners listening for `enter`
  5056. * $animate.off('enter');
  5057. *
  5058. * // remove listeners for all animation events from the container element
  5059. * $animate.off(container);
  5060. *
  5061. * // remove all the animation event listeners listening for `enter` on the given element and its children
  5062. * $animate.off('enter', container);
  5063. *
  5064. * // remove the event listener function provided by `callback` that is set
  5065. * // to listen for `enter` on the given `container` as well as its children
  5066. * $animate.off('enter', container, callback);
  5067. * ```
  5068. *
  5069. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  5070. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  5071. * arguments are ignored.
  5072. * @param {DOMElement=} container the container element the event listener was placed on
  5073. * @param {Function=} callback the callback function that was registered as the listener
  5074. */
  5075. off: $$animateQueue.off,
  5076. /**
  5077. * @ngdoc method
  5078. * @name $animate#pin
  5079. * @kind function
  5080. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  5081. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  5082. * element despite being outside the realm of the application or within another application. Say for example if the application
  5083. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  5084. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  5085. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  5086. *
  5087. * Note that this feature is only active when the `ngAnimate` module is used.
  5088. *
  5089. * @param {DOMElement} element the external element that will be pinned
  5090. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  5091. */
  5092. pin: $$animateQueue.pin,
  5093. /**
  5094. *
  5095. * @ngdoc method
  5096. * @name $animate#enabled
  5097. * @kind function
  5098. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  5099. * function can be called in four ways:
  5100. *
  5101. * ```js
  5102. * // returns true or false
  5103. * $animate.enabled();
  5104. *
  5105. * // changes the enabled state for all animations
  5106. * $animate.enabled(false);
  5107. * $animate.enabled(true);
  5108. *
  5109. * // returns true or false if animations are enabled for an element
  5110. * $animate.enabled(element);
  5111. *
  5112. * // changes the enabled state for an element and its children
  5113. * $animate.enabled(element, true);
  5114. * $animate.enabled(element, false);
  5115. * ```
  5116. *
  5117. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  5118. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  5119. *
  5120. * @return {boolean} whether or not animations are enabled
  5121. */
  5122. enabled: $$animateQueue.enabled,
  5123. /**
  5124. * @ngdoc method
  5125. * @name $animate#cancel
  5126. * @kind function
  5127. * @description Cancels the provided animation.
  5128. *
  5129. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  5130. */
  5131. cancel: function(runner) {
  5132. if (runner.end) {
  5133. runner.end();
  5134. }
  5135. },
  5136. /**
  5137. *
  5138. * @ngdoc method
  5139. * @name $animate#enter
  5140. * @kind function
  5141. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  5142. * as the first child within the `parent` element and then triggers an animation.
  5143. * A promise is returned that will be resolved during the next digest once the animation
  5144. * has completed.
  5145. *
  5146. * @param {DOMElement} element the element which will be inserted into the DOM
  5147. * @param {DOMElement} parent the parent element which will append the element as
  5148. * a child (so long as the after element is not present)
  5149. * @param {DOMElement=} after the sibling element after which the element will be appended
  5150. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5151. * The object can have the following properties:
  5152. *
  5153. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5154. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5155. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5156. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5157. *
  5158. * @return {Promise} the animation callback promise
  5159. */
  5160. enter: function(element, parent, after, options) {
  5161. parent = parent && jqLite(parent);
  5162. after = after && jqLite(after);
  5163. parent = parent || after.parent();
  5164. domInsert(element, parent, after);
  5165. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  5166. },
  5167. /**
  5168. *
  5169. * @ngdoc method
  5170. * @name $animate#move
  5171. * @kind function
  5172. * @description Inserts (moves) the element into its new position in the DOM either after
  5173. * the `after` element (if provided) or as the first child within the `parent` element
  5174. * and then triggers an animation. A promise is returned that will be resolved
  5175. * during the next digest once the animation has completed.
  5176. *
  5177. * @param {DOMElement} element the element which will be moved into the new DOM position
  5178. * @param {DOMElement} parent the parent element which will append the element as
  5179. * a child (so long as the after element is not present)
  5180. * @param {DOMElement=} after the sibling element after which the element will be appended
  5181. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5182. * The object can have the following properties:
  5183. *
  5184. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5185. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5186. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5187. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5188. *
  5189. * @return {Promise} the animation callback promise
  5190. */
  5191. move: function(element, parent, after, options) {
  5192. parent = parent && jqLite(parent);
  5193. after = after && jqLite(after);
  5194. parent = parent || after.parent();
  5195. domInsert(element, parent, after);
  5196. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  5197. },
  5198. /**
  5199. * @ngdoc method
  5200. * @name $animate#leave
  5201. * @kind function
  5202. * @description Triggers an animation and then removes the element from the DOM.
  5203. * When the function is called a promise is returned that will be resolved during the next
  5204. * digest once the animation has completed.
  5205. *
  5206. * @param {DOMElement} element the element which will be removed from the DOM
  5207. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5208. * The object can have the following properties:
  5209. *
  5210. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5211. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5212. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5213. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5214. *
  5215. * @return {Promise} the animation callback promise
  5216. */
  5217. leave: function(element, options) {
  5218. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  5219. element.remove();
  5220. });
  5221. },
  5222. /**
  5223. * @ngdoc method
  5224. * @name $animate#addClass
  5225. * @kind function
  5226. *
  5227. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  5228. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  5229. * animation if element already contains the CSS class or if the class is removed at a later step.
  5230. * Note that class-based animations are treated differently compared to structural animations
  5231. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5232. * depending if CSS or JavaScript animations are used.
  5233. *
  5234. * @param {DOMElement} element the element which the CSS classes will be applied to
  5235. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  5236. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5237. * The object can have the following properties:
  5238. *
  5239. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5240. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5241. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5242. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5243. *
  5244. * @return {Promise} the animation callback promise
  5245. */
  5246. addClass: function(element, className, options) {
  5247. options = prepareAnimateOptions(options);
  5248. options.addClass = mergeClasses(options.addclass, className);
  5249. return $$animateQueue.push(element, 'addClass', options);
  5250. },
  5251. /**
  5252. * @ngdoc method
  5253. * @name $animate#removeClass
  5254. * @kind function
  5255. *
  5256. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  5257. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  5258. * animation if element does not contain the CSS class or if the class is added at a later step.
  5259. * Note that class-based animations are treated differently compared to structural animations
  5260. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5261. * depending if CSS or JavaScript animations are used.
  5262. *
  5263. * @param {DOMElement} element the element which the CSS classes will be applied to
  5264. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5265. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5266. * The object can have the following properties:
  5267. *
  5268. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5269. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5270. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5271. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5272. *
  5273. * @return {Promise} the animation callback promise
  5274. */
  5275. removeClass: function(element, className, options) {
  5276. options = prepareAnimateOptions(options);
  5277. options.removeClass = mergeClasses(options.removeClass, className);
  5278. return $$animateQueue.push(element, 'removeClass', options);
  5279. },
  5280. /**
  5281. * @ngdoc method
  5282. * @name $animate#setClass
  5283. * @kind function
  5284. *
  5285. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5286. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5287. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5288. * passed. Note that class-based animations are treated differently compared to structural animations
  5289. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5290. * depending if CSS or JavaScript animations are used.
  5291. *
  5292. * @param {DOMElement} element the element which the CSS classes will be applied to
  5293. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5294. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5295. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5296. * The object can have the following properties:
  5297. *
  5298. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5299. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5300. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5301. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5302. *
  5303. * @return {Promise} the animation callback promise
  5304. */
  5305. setClass: function(element, add, remove, options) {
  5306. options = prepareAnimateOptions(options);
  5307. options.addClass = mergeClasses(options.addClass, add);
  5308. options.removeClass = mergeClasses(options.removeClass, remove);
  5309. return $$animateQueue.push(element, 'setClass', options);
  5310. },
  5311. /**
  5312. * @ngdoc method
  5313. * @name $animate#animate
  5314. * @kind function
  5315. *
  5316. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5317. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5318. * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
  5319. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5320. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5321. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5322. * method (or as part of the `options` parameter):
  5323. *
  5324. * ```js
  5325. * ngModule.animation('.my-inline-animation', function() {
  5326. * return {
  5327. * animate : function(element, from, to, done, options) {
  5328. * //animation
  5329. * done();
  5330. * }
  5331. * }
  5332. * });
  5333. * ```
  5334. *
  5335. * @param {DOMElement} element the element which the CSS styles will be applied to
  5336. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5337. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5338. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5339. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5340. * (Note that if no animation is detected then this value will not be applied to the element.)
  5341. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5342. * The object can have the following properties:
  5343. *
  5344. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5345. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5346. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5347. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5348. *
  5349. * @return {Promise} the animation callback promise
  5350. */
  5351. animate: function(element, from, to, className, options) {
  5352. options = prepareAnimateOptions(options);
  5353. options.from = options.from ? extend(options.from, from) : from;
  5354. options.to = options.to ? extend(options.to, to) : to;
  5355. className = className || 'ng-inline-animate';
  5356. options.tempClasses = mergeClasses(options.tempClasses, className);
  5357. return $$animateQueue.push(element, 'animate', options);
  5358. }
  5359. };
  5360. }];
  5361. }];
  5362. var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
  5363. this.$get = ['$$rAF', function($$rAF) {
  5364. var waitQueue = [];
  5365. function waitForTick(fn) {
  5366. waitQueue.push(fn);
  5367. if (waitQueue.length > 1) return;
  5368. $$rAF(function() {
  5369. for (var i = 0; i < waitQueue.length; i++) {
  5370. waitQueue[i]();
  5371. }
  5372. waitQueue = [];
  5373. });
  5374. }
  5375. return function() {
  5376. var passed = false;
  5377. waitForTick(function() {
  5378. passed = true;
  5379. });
  5380. return function(callback) {
  5381. if (passed) {
  5382. callback();
  5383. } else {
  5384. waitForTick(callback);
  5385. }
  5386. };
  5387. };
  5388. }];
  5389. };
  5390. var $$AnimateRunnerFactoryProvider = /** @this */ function() {
  5391. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
  5392. function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
  5393. var INITIAL_STATE = 0;
  5394. var DONE_PENDING_STATE = 1;
  5395. var DONE_COMPLETE_STATE = 2;
  5396. AnimateRunner.chain = function(chain, callback) {
  5397. var index = 0;
  5398. next();
  5399. function next() {
  5400. if (index === chain.length) {
  5401. callback(true);
  5402. return;
  5403. }
  5404. chain[index](function(response) {
  5405. if (response === false) {
  5406. callback(false);
  5407. return;
  5408. }
  5409. index++;
  5410. next();
  5411. });
  5412. }
  5413. };
  5414. AnimateRunner.all = function(runners, callback) {
  5415. var count = 0;
  5416. var status = true;
  5417. forEach(runners, function(runner) {
  5418. runner.done(onProgress);
  5419. });
  5420. function onProgress(response) {
  5421. status = status && response;
  5422. if (++count === runners.length) {
  5423. callback(status);
  5424. }
  5425. }
  5426. };
  5427. function AnimateRunner(host) {
  5428. this.setHost(host);
  5429. var rafTick = $$animateAsyncRun();
  5430. var timeoutTick = function(fn) {
  5431. $timeout(fn, 0, false);
  5432. };
  5433. this._doneCallbacks = [];
  5434. this._tick = function(fn) {
  5435. if ($$isDocumentHidden()) {
  5436. timeoutTick(fn);
  5437. } else {
  5438. rafTick(fn);
  5439. }
  5440. };
  5441. this._state = 0;
  5442. }
  5443. AnimateRunner.prototype = {
  5444. setHost: function(host) {
  5445. this.host = host || {};
  5446. },
  5447. done: function(fn) {
  5448. if (this._state === DONE_COMPLETE_STATE) {
  5449. fn();
  5450. } else {
  5451. this._doneCallbacks.push(fn);
  5452. }
  5453. },
  5454. progress: noop,
  5455. getPromise: function() {
  5456. if (!this.promise) {
  5457. var self = this;
  5458. this.promise = $q(function(resolve, reject) {
  5459. self.done(function(status) {
  5460. if (status === false) {
  5461. reject();
  5462. } else {
  5463. resolve();
  5464. }
  5465. });
  5466. });
  5467. }
  5468. return this.promise;
  5469. },
  5470. then: function(resolveHandler, rejectHandler) {
  5471. return this.getPromise().then(resolveHandler, rejectHandler);
  5472. },
  5473. 'catch': function(handler) {
  5474. return this.getPromise()['catch'](handler);
  5475. },
  5476. 'finally': function(handler) {
  5477. return this.getPromise()['finally'](handler);
  5478. },
  5479. pause: function() {
  5480. if (this.host.pause) {
  5481. this.host.pause();
  5482. }
  5483. },
  5484. resume: function() {
  5485. if (this.host.resume) {
  5486. this.host.resume();
  5487. }
  5488. },
  5489. end: function() {
  5490. if (this.host.end) {
  5491. this.host.end();
  5492. }
  5493. this._resolve(true);
  5494. },
  5495. cancel: function() {
  5496. if (this.host.cancel) {
  5497. this.host.cancel();
  5498. }
  5499. this._resolve(false);
  5500. },
  5501. complete: function(response) {
  5502. var self = this;
  5503. if (self._state === INITIAL_STATE) {
  5504. self._state = DONE_PENDING_STATE;
  5505. self._tick(function() {
  5506. self._resolve(response);
  5507. });
  5508. }
  5509. },
  5510. _resolve: function(response) {
  5511. if (this._state !== DONE_COMPLETE_STATE) {
  5512. forEach(this._doneCallbacks, function(fn) {
  5513. fn(response);
  5514. });
  5515. this._doneCallbacks.length = 0;
  5516. this._state = DONE_COMPLETE_STATE;
  5517. }
  5518. }
  5519. };
  5520. return AnimateRunner;
  5521. }];
  5522. };
  5523. /* exported $CoreAnimateCssProvider */
  5524. /**
  5525. * @ngdoc service
  5526. * @name $animateCss
  5527. * @kind object
  5528. * @this
  5529. *
  5530. * @description
  5531. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5532. * then the `$animateCss` service will actually perform animations.
  5533. *
  5534. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5535. */
  5536. var $CoreAnimateCssProvider = function() {
  5537. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5538. return function(element, initialOptions) {
  5539. // all of the animation functions should create
  5540. // a copy of the options data, however, if a
  5541. // parent service has already created a copy then
  5542. // we should stick to using that
  5543. var options = initialOptions || {};
  5544. if (!options.$$prepared) {
  5545. options = copy(options);
  5546. }
  5547. // there is no point in applying the styles since
  5548. // there is no animation that goes on at all in
  5549. // this version of $animateCss.
  5550. if (options.cleanupStyles) {
  5551. options.from = options.to = null;
  5552. }
  5553. if (options.from) {
  5554. element.css(options.from);
  5555. options.from = null;
  5556. }
  5557. var closed, runner = new $$AnimateRunner();
  5558. return {
  5559. start: run,
  5560. end: run
  5561. };
  5562. function run() {
  5563. $$rAF(function() {
  5564. applyAnimationContents();
  5565. if (!closed) {
  5566. runner.complete();
  5567. }
  5568. closed = true;
  5569. });
  5570. return runner;
  5571. }
  5572. function applyAnimationContents() {
  5573. if (options.addClass) {
  5574. element.addClass(options.addClass);
  5575. options.addClass = null;
  5576. }
  5577. if (options.removeClass) {
  5578. element.removeClass(options.removeClass);
  5579. options.removeClass = null;
  5580. }
  5581. if (options.to) {
  5582. element.css(options.to);
  5583. options.to = null;
  5584. }
  5585. }
  5586. };
  5587. }];
  5588. };
  5589. /* global stripHash: true */
  5590. /**
  5591. * ! This is a private undocumented service !
  5592. *
  5593. * @name $browser
  5594. * @requires $log
  5595. * @description
  5596. * This object has two goals:
  5597. *
  5598. * - hide all the global state in the browser caused by the window object
  5599. * - abstract away all the browser specific features and inconsistencies
  5600. *
  5601. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5602. * service, which can be used for convenient testing of the application without the interaction with
  5603. * the real browser apis.
  5604. */
  5605. /**
  5606. * @param {object} window The global window object.
  5607. * @param {object} document jQuery wrapped document.
  5608. * @param {object} $log window.console or an object with the same interface.
  5609. * @param {object} $sniffer $sniffer service
  5610. */
  5611. function Browser(window, document, $log, $sniffer) {
  5612. var self = this,
  5613. location = window.location,
  5614. history = window.history,
  5615. setTimeout = window.setTimeout,
  5616. clearTimeout = window.clearTimeout,
  5617. pendingDeferIds = {};
  5618. self.isMock = false;
  5619. var outstandingRequestCount = 0;
  5620. var outstandingRequestCallbacks = [];
  5621. // TODO(vojta): remove this temporary api
  5622. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5623. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5624. /**
  5625. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5626. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5627. */
  5628. function completeOutstandingRequest(fn) {
  5629. try {
  5630. fn.apply(null, sliceArgs(arguments, 1));
  5631. } finally {
  5632. outstandingRequestCount--;
  5633. if (outstandingRequestCount === 0) {
  5634. while (outstandingRequestCallbacks.length) {
  5635. try {
  5636. outstandingRequestCallbacks.pop()();
  5637. } catch (e) {
  5638. $log.error(e);
  5639. }
  5640. }
  5641. }
  5642. }
  5643. }
  5644. function getHash(url) {
  5645. var index = url.indexOf('#');
  5646. return index === -1 ? '' : url.substr(index);
  5647. }
  5648. /**
  5649. * @private
  5650. * Note: this method is used only by scenario runner
  5651. * TODO(vojta): prefix this method with $$ ?
  5652. * @param {function()} callback Function that will be called when no outstanding request
  5653. */
  5654. self.notifyWhenNoOutstandingRequests = function(callback) {
  5655. if (outstandingRequestCount === 0) {
  5656. callback();
  5657. } else {
  5658. outstandingRequestCallbacks.push(callback);
  5659. }
  5660. };
  5661. //////////////////////////////////////////////////////////////
  5662. // URL API
  5663. //////////////////////////////////////////////////////////////
  5664. var cachedState, lastHistoryState,
  5665. lastBrowserUrl = location.href,
  5666. baseElement = document.find('base'),
  5667. pendingLocation = null,
  5668. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5669. try {
  5670. return history.state;
  5671. } catch (e) {
  5672. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5673. }
  5674. };
  5675. cacheState();
  5676. /**
  5677. * @name $browser#url
  5678. *
  5679. * @description
  5680. * GETTER:
  5681. * Without any argument, this method just returns current value of location.href.
  5682. *
  5683. * SETTER:
  5684. * With at least one argument, this method sets url to new value.
  5685. * If html5 history api supported, pushState/replaceState is used, otherwise
  5686. * location.href/location.replace is used.
  5687. * Returns its own instance to allow chaining
  5688. *
  5689. * NOTE: this api is intended for use only by the $location service. Please use the
  5690. * {@link ng.$location $location service} to change url.
  5691. *
  5692. * @param {string} url New url (when used as setter)
  5693. * @param {boolean=} replace Should new url replace current history record?
  5694. * @param {object=} state object to use with pushState/replaceState
  5695. */
  5696. self.url = function(url, replace, state) {
  5697. // In modern browsers `history.state` is `null` by default; treating it separately
  5698. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5699. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5700. if (isUndefined(state)) {
  5701. state = null;
  5702. }
  5703. // Android Browser BFCache causes location, history reference to become stale.
  5704. if (location !== window.location) location = window.location;
  5705. if (history !== window.history) history = window.history;
  5706. // setter
  5707. if (url) {
  5708. var sameState = lastHistoryState === state;
  5709. // Don't change anything if previous and current URLs and states match. This also prevents
  5710. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5711. // See https://github.com/angular/angular.js/commit/ffb2701
  5712. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5713. return self;
  5714. }
  5715. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5716. lastBrowserUrl = url;
  5717. lastHistoryState = state;
  5718. // Don't use history API if only the hash changed
  5719. // due to a bug in IE10/IE11 which leads
  5720. // to not firing a `hashchange` nor `popstate` event
  5721. // in some cases (see #9143).
  5722. if ($sniffer.history && (!sameBase || !sameState)) {
  5723. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5724. cacheState();
  5725. } else {
  5726. if (!sameBase) {
  5727. pendingLocation = url;
  5728. }
  5729. if (replace) {
  5730. location.replace(url);
  5731. } else if (!sameBase) {
  5732. location.href = url;
  5733. } else {
  5734. location.hash = getHash(url);
  5735. }
  5736. if (location.href !== url) {
  5737. pendingLocation = url;
  5738. }
  5739. }
  5740. if (pendingLocation) {
  5741. pendingLocation = url;
  5742. }
  5743. return self;
  5744. // getter
  5745. } else {
  5746. // - pendingLocation is needed as browsers don't allow to read out
  5747. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5748. // https://openradar.appspot.com/22186109).
  5749. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5750. return pendingLocation || location.href.replace(/%27/g,'\'');
  5751. }
  5752. };
  5753. /**
  5754. * @name $browser#state
  5755. *
  5756. * @description
  5757. * This method is a getter.
  5758. *
  5759. * Return history.state or null if history.state is undefined.
  5760. *
  5761. * @returns {object} state
  5762. */
  5763. self.state = function() {
  5764. return cachedState;
  5765. };
  5766. var urlChangeListeners = [],
  5767. urlChangeInit = false;
  5768. function cacheStateAndFireUrlChange() {
  5769. pendingLocation = null;
  5770. fireStateOrUrlChange();
  5771. }
  5772. // This variable should be used *only* inside the cacheState function.
  5773. var lastCachedState = null;
  5774. function cacheState() {
  5775. // This should be the only place in $browser where `history.state` is read.
  5776. cachedState = getCurrentState();
  5777. cachedState = isUndefined(cachedState) ? null : cachedState;
  5778. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5779. if (equals(cachedState, lastCachedState)) {
  5780. cachedState = lastCachedState;
  5781. }
  5782. lastCachedState = cachedState;
  5783. lastHistoryState = cachedState;
  5784. }
  5785. function fireStateOrUrlChange() {
  5786. var prevLastHistoryState = lastHistoryState;
  5787. cacheState();
  5788. if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {
  5789. return;
  5790. }
  5791. lastBrowserUrl = self.url();
  5792. lastHistoryState = cachedState;
  5793. forEach(urlChangeListeners, function(listener) {
  5794. listener(self.url(), cachedState);
  5795. });
  5796. }
  5797. /**
  5798. * @name $browser#onUrlChange
  5799. *
  5800. * @description
  5801. * Register callback function that will be called, when url changes.
  5802. *
  5803. * It's only called when the url is changed from outside of angular:
  5804. * - user types different url into address bar
  5805. * - user clicks on history (forward/back) button
  5806. * - user clicks on a link
  5807. *
  5808. * It's not called when url is changed by $browser.url() method
  5809. *
  5810. * The listener gets called with new url as parameter.
  5811. *
  5812. * NOTE: this api is intended for use only by the $location service. Please use the
  5813. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5814. *
  5815. * @param {function(string)} listener Listener function to be called when url changes.
  5816. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5817. */
  5818. self.onUrlChange = function(callback) {
  5819. // TODO(vojta): refactor to use node's syntax for events
  5820. if (!urlChangeInit) {
  5821. // We listen on both (hashchange/popstate) when available, as some browsers don't
  5822. // fire popstate when user changes the address bar and don't fire hashchange when url
  5823. // changed by push/replaceState
  5824. // html5 history api - popstate event
  5825. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5826. // hashchange event
  5827. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5828. urlChangeInit = true;
  5829. }
  5830. urlChangeListeners.push(callback);
  5831. return callback;
  5832. };
  5833. /**
  5834. * @private
  5835. * Remove popstate and hashchange handler from window.
  5836. *
  5837. * NOTE: this api is intended for use only by $rootScope.
  5838. */
  5839. self.$$applicationDestroyed = function() {
  5840. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5841. };
  5842. /**
  5843. * Checks whether the url has changed outside of Angular.
  5844. * Needs to be exported to be able to check for changes that have been done in sync,
  5845. * as hashchange/popstate events fire in async.
  5846. */
  5847. self.$$checkUrlChange = fireStateOrUrlChange;
  5848. //////////////////////////////////////////////////////////////
  5849. // Misc API
  5850. //////////////////////////////////////////////////////////////
  5851. /**
  5852. * @name $browser#baseHref
  5853. *
  5854. * @description
  5855. * Returns current <base href>
  5856. * (always relative - without domain)
  5857. *
  5858. * @returns {string} The current base href
  5859. */
  5860. self.baseHref = function() {
  5861. var href = baseElement.attr('href');
  5862. return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
  5863. };
  5864. /**
  5865. * @name $browser#defer
  5866. * @param {function()} fn A function, who's execution should be deferred.
  5867. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5868. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5869. *
  5870. * @description
  5871. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5872. *
  5873. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5874. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5875. * via `$browser.defer.flush()`.
  5876. *
  5877. */
  5878. self.defer = function(fn, delay) {
  5879. var timeoutId;
  5880. outstandingRequestCount++;
  5881. timeoutId = setTimeout(function() {
  5882. delete pendingDeferIds[timeoutId];
  5883. completeOutstandingRequest(fn);
  5884. }, delay || 0);
  5885. pendingDeferIds[timeoutId] = true;
  5886. return timeoutId;
  5887. };
  5888. /**
  5889. * @name $browser#defer.cancel
  5890. *
  5891. * @description
  5892. * Cancels a deferred task identified with `deferId`.
  5893. *
  5894. * @param {*} deferId Token returned by the `$browser.defer` function.
  5895. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5896. * canceled.
  5897. */
  5898. self.defer.cancel = function(deferId) {
  5899. if (pendingDeferIds[deferId]) {
  5900. delete pendingDeferIds[deferId];
  5901. clearTimeout(deferId);
  5902. completeOutstandingRequest(noop);
  5903. return true;
  5904. }
  5905. return false;
  5906. };
  5907. }
  5908. /** @this */
  5909. function $BrowserProvider() {
  5910. this.$get = ['$window', '$log', '$sniffer', '$document',
  5911. function($window, $log, $sniffer, $document) {
  5912. return new Browser($window, $document, $log, $sniffer);
  5913. }];
  5914. }
  5915. /**
  5916. * @ngdoc service
  5917. * @name $cacheFactory
  5918. * @this
  5919. *
  5920. * @description
  5921. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5922. * them.
  5923. *
  5924. * ```js
  5925. *
  5926. * var cache = $cacheFactory('cacheId');
  5927. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5928. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5929. *
  5930. * cache.put("key", "value");
  5931. * cache.put("another key", "another value");
  5932. *
  5933. * // We've specified no options on creation
  5934. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5935. *
  5936. * ```
  5937. *
  5938. *
  5939. * @param {string} cacheId Name or id of the newly created cache.
  5940. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5941. *
  5942. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5943. *
  5944. * @returns {object} Newly created cache object with the following set of methods:
  5945. *
  5946. * - `{object}` `info()` — Returns id, size, and options of cache.
  5947. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5948. * it.
  5949. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5950. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5951. * - `{void}` `removeAll()` — Removes all cached values.
  5952. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5953. *
  5954. * @example
  5955. <example module="cacheExampleApp" name="cache-factory">
  5956. <file name="index.html">
  5957. <div ng-controller="CacheController">
  5958. <input ng-model="newCacheKey" placeholder="Key">
  5959. <input ng-model="newCacheValue" placeholder="Value">
  5960. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5961. <p ng-if="keys.length">Cached Values</p>
  5962. <div ng-repeat="key in keys">
  5963. <span ng-bind="key"></span>
  5964. <span>: </span>
  5965. <b ng-bind="cache.get(key)"></b>
  5966. </div>
  5967. <p>Cache Info</p>
  5968. <div ng-repeat="(key, value) in cache.info()">
  5969. <span ng-bind="key"></span>
  5970. <span>: </span>
  5971. <b ng-bind="value"></b>
  5972. </div>
  5973. </div>
  5974. </file>
  5975. <file name="script.js">
  5976. angular.module('cacheExampleApp', []).
  5977. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5978. $scope.keys = [];
  5979. $scope.cache = $cacheFactory('cacheId');
  5980. $scope.put = function(key, value) {
  5981. if (angular.isUndefined($scope.cache.get(key))) {
  5982. $scope.keys.push(key);
  5983. }
  5984. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  5985. };
  5986. }]);
  5987. </file>
  5988. <file name="style.css">
  5989. p {
  5990. margin: 10px 0 3px;
  5991. }
  5992. </file>
  5993. </example>
  5994. */
  5995. function $CacheFactoryProvider() {
  5996. this.$get = function() {
  5997. var caches = {};
  5998. function cacheFactory(cacheId, options) {
  5999. if (cacheId in caches) {
  6000. throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
  6001. }
  6002. var size = 0,
  6003. stats = extend({}, options, {id: cacheId}),
  6004. data = createMap(),
  6005. capacity = (options && options.capacity) || Number.MAX_VALUE,
  6006. lruHash = createMap(),
  6007. freshEnd = null,
  6008. staleEnd = null;
  6009. /**
  6010. * @ngdoc type
  6011. * @name $cacheFactory.Cache
  6012. *
  6013. * @description
  6014. * A cache object used to store and retrieve data, primarily used by
  6015. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  6016. * templates and other data.
  6017. *
  6018. * ```js
  6019. * angular.module('superCache')
  6020. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  6021. * return $cacheFactory('super-cache');
  6022. * }]);
  6023. * ```
  6024. *
  6025. * Example test:
  6026. *
  6027. * ```js
  6028. * it('should behave like a cache', inject(function(superCache) {
  6029. * superCache.put('key', 'value');
  6030. * superCache.put('another key', 'another value');
  6031. *
  6032. * expect(superCache.info()).toEqual({
  6033. * id: 'super-cache',
  6034. * size: 2
  6035. * });
  6036. *
  6037. * superCache.remove('another key');
  6038. * expect(superCache.get('another key')).toBeUndefined();
  6039. *
  6040. * superCache.removeAll();
  6041. * expect(superCache.info()).toEqual({
  6042. * id: 'super-cache',
  6043. * size: 0
  6044. * });
  6045. * }));
  6046. * ```
  6047. */
  6048. return (caches[cacheId] = {
  6049. /**
  6050. * @ngdoc method
  6051. * @name $cacheFactory.Cache#put
  6052. * @kind function
  6053. *
  6054. * @description
  6055. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  6056. * retrieved later, and incrementing the size of the cache if the key was not already
  6057. * present in the cache. If behaving like an LRU cache, it will also remove stale
  6058. * entries from the set.
  6059. *
  6060. * It will not insert undefined values into the cache.
  6061. *
  6062. * @param {string} key the key under which the cached data is stored.
  6063. * @param {*} value the value to store alongside the key. If it is undefined, the key
  6064. * will not be stored.
  6065. * @returns {*} the value stored.
  6066. */
  6067. put: function(key, value) {
  6068. if (isUndefined(value)) return;
  6069. if (capacity < Number.MAX_VALUE) {
  6070. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  6071. refresh(lruEntry);
  6072. }
  6073. if (!(key in data)) size++;
  6074. data[key] = value;
  6075. if (size > capacity) {
  6076. this.remove(staleEnd.key);
  6077. }
  6078. return value;
  6079. },
  6080. /**
  6081. * @ngdoc method
  6082. * @name $cacheFactory.Cache#get
  6083. * @kind function
  6084. *
  6085. * @description
  6086. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  6087. *
  6088. * @param {string} key the key of the data to be retrieved
  6089. * @returns {*} the value stored.
  6090. */
  6091. get: function(key) {
  6092. if (capacity < Number.MAX_VALUE) {
  6093. var lruEntry = lruHash[key];
  6094. if (!lruEntry) return;
  6095. refresh(lruEntry);
  6096. }
  6097. return data[key];
  6098. },
  6099. /**
  6100. * @ngdoc method
  6101. * @name $cacheFactory.Cache#remove
  6102. * @kind function
  6103. *
  6104. * @description
  6105. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  6106. *
  6107. * @param {string} key the key of the entry to be removed
  6108. */
  6109. remove: function(key) {
  6110. if (capacity < Number.MAX_VALUE) {
  6111. var lruEntry = lruHash[key];
  6112. if (!lruEntry) return;
  6113. if (lruEntry === freshEnd) freshEnd = lruEntry.p;
  6114. if (lruEntry === staleEnd) staleEnd = lruEntry.n;
  6115. link(lruEntry.n,lruEntry.p);
  6116. delete lruHash[key];
  6117. }
  6118. if (!(key in data)) return;
  6119. delete data[key];
  6120. size--;
  6121. },
  6122. /**
  6123. * @ngdoc method
  6124. * @name $cacheFactory.Cache#removeAll
  6125. * @kind function
  6126. *
  6127. * @description
  6128. * Clears the cache object of any entries.
  6129. */
  6130. removeAll: function() {
  6131. data = createMap();
  6132. size = 0;
  6133. lruHash = createMap();
  6134. freshEnd = staleEnd = null;
  6135. },
  6136. /**
  6137. * @ngdoc method
  6138. * @name $cacheFactory.Cache#destroy
  6139. * @kind function
  6140. *
  6141. * @description
  6142. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  6143. * removing it from the {@link $cacheFactory $cacheFactory} set.
  6144. */
  6145. destroy: function() {
  6146. data = null;
  6147. stats = null;
  6148. lruHash = null;
  6149. delete caches[cacheId];
  6150. },
  6151. /**
  6152. * @ngdoc method
  6153. * @name $cacheFactory.Cache#info
  6154. * @kind function
  6155. *
  6156. * @description
  6157. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  6158. *
  6159. * @returns {object} an object with the following properties:
  6160. * <ul>
  6161. * <li>**id**: the id of the cache instance</li>
  6162. * <li>**size**: the number of entries kept in the cache instance</li>
  6163. * <li>**...**: any additional properties from the options object when creating the
  6164. * cache.</li>
  6165. * </ul>
  6166. */
  6167. info: function() {
  6168. return extend({}, stats, {size: size});
  6169. }
  6170. });
  6171. /**
  6172. * makes the `entry` the freshEnd of the LRU linked list
  6173. */
  6174. function refresh(entry) {
  6175. if (entry !== freshEnd) {
  6176. if (!staleEnd) {
  6177. staleEnd = entry;
  6178. } else if (staleEnd === entry) {
  6179. staleEnd = entry.n;
  6180. }
  6181. link(entry.n, entry.p);
  6182. link(entry, freshEnd);
  6183. freshEnd = entry;
  6184. freshEnd.n = null;
  6185. }
  6186. }
  6187. /**
  6188. * bidirectionally links two entries of the LRU linked list
  6189. */
  6190. function link(nextEntry, prevEntry) {
  6191. if (nextEntry !== prevEntry) {
  6192. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  6193. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  6194. }
  6195. }
  6196. }
  6197. /**
  6198. * @ngdoc method
  6199. * @name $cacheFactory#info
  6200. *
  6201. * @description
  6202. * Get information about all the caches that have been created
  6203. *
  6204. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  6205. */
  6206. cacheFactory.info = function() {
  6207. var info = {};
  6208. forEach(caches, function(cache, cacheId) {
  6209. info[cacheId] = cache.info();
  6210. });
  6211. return info;
  6212. };
  6213. /**
  6214. * @ngdoc method
  6215. * @name $cacheFactory#get
  6216. *
  6217. * @description
  6218. * Get access to a cache object by the `cacheId` used when it was created.
  6219. *
  6220. * @param {string} cacheId Name or id of a cache to access.
  6221. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  6222. */
  6223. cacheFactory.get = function(cacheId) {
  6224. return caches[cacheId];
  6225. };
  6226. return cacheFactory;
  6227. };
  6228. }
  6229. /**
  6230. * @ngdoc service
  6231. * @name $templateCache
  6232. * @this
  6233. *
  6234. * @description
  6235. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  6236. * can load templates directly into the cache in a `script` tag, or by consuming the
  6237. * `$templateCache` service directly.
  6238. *
  6239. * Adding via the `script` tag:
  6240. *
  6241. * ```html
  6242. * <script type="text/ng-template" id="templateId.html">
  6243. * <p>This is the content of the template</p>
  6244. * </script>
  6245. * ```
  6246. *
  6247. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  6248. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  6249. * element with ng-app attribute), otherwise the template will be ignored.
  6250. *
  6251. * Adding via the `$templateCache` service:
  6252. *
  6253. * ```js
  6254. * var myApp = angular.module('myApp', []);
  6255. * myApp.run(function($templateCache) {
  6256. * $templateCache.put('templateId.html', 'This is the content of the template');
  6257. * });
  6258. * ```
  6259. *
  6260. * To retrieve the template later, simply use it in your component:
  6261. * ```js
  6262. * myApp.component('myComponent', {
  6263. * templateUrl: 'templateId.html'
  6264. * });
  6265. * ```
  6266. *
  6267. * or get it via the `$templateCache` service:
  6268. * ```js
  6269. * $templateCache.get('templateId.html')
  6270. * ```
  6271. *
  6272. * See {@link ng.$cacheFactory $cacheFactory}.
  6273. *
  6274. */
  6275. function $TemplateCacheProvider() {
  6276. this.$get = ['$cacheFactory', function($cacheFactory) {
  6277. return $cacheFactory('templates');
  6278. }];
  6279. }
  6280. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  6281. * Any commits to this file should be reviewed with security in mind. *
  6282. * Changes to this file can potentially create security vulnerabilities. *
  6283. * An approval from 2 Core members with history of modifying *
  6284. * this file is required. *
  6285. * *
  6286. * Does the change somehow allow for arbitrary javascript to be executed? *
  6287. * Or allows for someone to change the prototype of built-in objects? *
  6288. * Or gives undesired access to variables like document or window? *
  6289. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  6290. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  6291. *
  6292. * DOM-related variables:
  6293. *
  6294. * - "node" - DOM Node
  6295. * - "element" - DOM Element or Node
  6296. * - "$node" or "$element" - jqLite-wrapped node or element
  6297. *
  6298. *
  6299. * Compiler related stuff:
  6300. *
  6301. * - "linkFn" - linking fn of a single directive
  6302. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6303. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6304. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6305. */
  6306. /**
  6307. * @ngdoc service
  6308. * @name $compile
  6309. * @kind function
  6310. *
  6311. * @description
  6312. * Compiles an HTML string or DOM into a template and produces a template function, which
  6313. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6314. *
  6315. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6316. * {@link ng.$compileProvider#directive directives}.
  6317. *
  6318. * <div class="alert alert-warning">
  6319. * **Note:** This document is an in-depth reference of all directive options.
  6320. * For a gentle introduction to directives with examples of common use cases,
  6321. * see the {@link guide/directive directive guide}.
  6322. * </div>
  6323. *
  6324. * ## Comprehensive Directive API
  6325. *
  6326. * There are many different options for a directive.
  6327. *
  6328. * The difference resides in the return value of the factory function.
  6329. * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
  6330. * that defines the directive properties, or just the `postLink` function (all other properties will have
  6331. * the default values).
  6332. *
  6333. * <div class="alert alert-success">
  6334. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6335. * </div>
  6336. *
  6337. * Here's an example directive declared with a Directive Definition Object:
  6338. *
  6339. * ```js
  6340. * var myModule = angular.module(...);
  6341. *
  6342. * myModule.directive('directiveName', function factory(injectables) {
  6343. * var directiveDefinitionObject = {
  6344. * {@link $compile#-priority- priority}: 0,
  6345. * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6346. * // or
  6347. * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6348. * {@link $compile#-transclude- transclude}: false,
  6349. * {@link $compile#-restrict- restrict}: 'A',
  6350. * {@link $compile#-templatenamespace- templateNamespace}: 'html',
  6351. * {@link $compile#-scope- scope}: false,
  6352. * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6353. * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
  6354. * {@link $compile#-bindtocontroller- bindToController}: false,
  6355. * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6356. * {@link $compile#-multielement- multiElement}: false,
  6357. * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
  6358. * return {
  6359. * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6360. * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6361. * }
  6362. * // or
  6363. * // return function postLink( ... ) { ... }
  6364. * },
  6365. * // or
  6366. * // {@link $compile#-link- link}: {
  6367. * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6368. * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6369. * // }
  6370. * // or
  6371. * // {@link $compile#-link- link}: function postLink( ... ) { ... }
  6372. * };
  6373. * return directiveDefinitionObject;
  6374. * });
  6375. * ```
  6376. *
  6377. * <div class="alert alert-warning">
  6378. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6379. * </div>
  6380. *
  6381. * Therefore the above can be simplified as:
  6382. *
  6383. * ```js
  6384. * var myModule = angular.module(...);
  6385. *
  6386. * myModule.directive('directiveName', function factory(injectables) {
  6387. * var directiveDefinitionObject = {
  6388. * link: function postLink(scope, iElement, iAttrs) { ... }
  6389. * };
  6390. * return directiveDefinitionObject;
  6391. * // or
  6392. * // return function postLink(scope, iElement, iAttrs) { ... }
  6393. * });
  6394. * ```
  6395. *
  6396. * ### Life-cycle hooks
  6397. * Directive controllers can provide the following methods that are called by Angular at points in the life-cycle of the
  6398. * directive:
  6399. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6400. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6401. * this element). This is a good place to put initialization code for your controller.
  6402. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6403. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6404. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6405. * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will
  6406. * also be called when your bindings are initialized.
  6407. * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
  6408. * changes. Any actions that you wish to take in response to the changes that you detect must be
  6409. * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
  6410. * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
  6411. * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
  6412. * if detecting changes, you must store the previous value(s) for comparison to the current values.
  6413. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6414. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6415. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6416. * components will have their `$onDestroy()` hook called before child components.
  6417. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6418. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6419. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6420. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6421. * suspended until that occurs.
  6422. *
  6423. * #### Comparison with Angular 2 life-cycle hooks
  6424. * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are
  6425. * some differences that you should be aware of, especially when it comes to moving your code from Angular 1 to Angular 2:
  6426. *
  6427. * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`.
  6428. * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor.
  6429. * In Angular 2 you can only define hooks on the prototype of the Component class.
  6430. * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to
  6431. * `ngDoCheck` in Angular 2
  6432. * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
  6433. * propagated throughout the application.
  6434. * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
  6435. * error or do nothing depending upon the state of `enableProdMode()`.
  6436. *
  6437. * #### Life-cycle hook examples
  6438. *
  6439. * This example shows how you can check for mutations to a Date object even though the identity of the object
  6440. * has not changed.
  6441. *
  6442. * <example name="doCheckDateExample" module="do-check-module">
  6443. * <file name="app.js">
  6444. * angular.module('do-check-module', [])
  6445. * .component('app', {
  6446. * template:
  6447. * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
  6448. * 'Date: {{ $ctrl.date }}' +
  6449. * '<test date="$ctrl.date"></test>',
  6450. * controller: function() {
  6451. * this.date = new Date();
  6452. * this.month = this.date.getMonth();
  6453. * this.updateDate = function() {
  6454. * this.date.setMonth(this.month);
  6455. * };
  6456. * }
  6457. * })
  6458. * .component('test', {
  6459. * bindings: { date: '<' },
  6460. * template:
  6461. * '<pre>{{ $ctrl.log | json }}</pre>',
  6462. * controller: function() {
  6463. * var previousValue;
  6464. * this.log = [];
  6465. * this.$doCheck = function() {
  6466. * var currentValue = this.date && this.date.valueOf();
  6467. * if (previousValue !== currentValue) {
  6468. * this.log.push('doCheck: date mutated: ' + this.date);
  6469. * previousValue = currentValue;
  6470. * }
  6471. * };
  6472. * }
  6473. * });
  6474. * </file>
  6475. * <file name="index.html">
  6476. * <app></app>
  6477. * </file>
  6478. * </example>
  6479. *
  6480. * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
  6481. * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
  6482. * arrays or objects can have a negative impact on your application performance)
  6483. *
  6484. * <example name="doCheckArrayExample" module="do-check-module">
  6485. * <file name="index.html">
  6486. * <div ng-init="items = []">
  6487. * <button ng-click="items.push(items.length)">Add Item</button>
  6488. * <button ng-click="items = []">Reset Items</button>
  6489. * <pre>{{ items }}</pre>
  6490. * <test items="items"></test>
  6491. * </div>
  6492. * </file>
  6493. * <file name="app.js">
  6494. * angular.module('do-check-module', [])
  6495. * .component('test', {
  6496. * bindings: { items: '<' },
  6497. * template:
  6498. * '<pre>{{ $ctrl.log | json }}</pre>',
  6499. * controller: function() {
  6500. * this.log = [];
  6501. *
  6502. * this.$doCheck = function() {
  6503. * if (this.items_ref !== this.items) {
  6504. * this.log.push('doCheck: items changed');
  6505. * this.items_ref = this.items;
  6506. * }
  6507. * if (!angular.equals(this.items_clone, this.items)) {
  6508. * this.log.push('doCheck: items mutated');
  6509. * this.items_clone = angular.copy(this.items);
  6510. * }
  6511. * };
  6512. * }
  6513. * });
  6514. * </file>
  6515. * </example>
  6516. *
  6517. *
  6518. * ### Directive Definition Object
  6519. *
  6520. * The directive definition object provides instructions to the {@link ng.$compile
  6521. * compiler}. The attributes are:
  6522. *
  6523. * #### `multiElement`
  6524. * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
  6525. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6526. * together as the directive elements. It is recommended that this feature be used on directives
  6527. * which are not strictly behavioral (such as {@link ngClick}), and which
  6528. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6529. *
  6530. * #### `priority`
  6531. * When there are multiple directives defined on a single DOM element, sometimes it
  6532. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6533. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6534. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6535. * are also run in priority order, but post-link functions are run in reverse order. The order
  6536. * of directives with the same priority is undefined. The default priority is `0`.
  6537. *
  6538. * #### `terminal`
  6539. * If set to true then the current `priority` will be the last set of directives
  6540. * which will execute (any directives at the current priority will still execute
  6541. * as the order of execution on same `priority` is undefined). Note that expressions
  6542. * and other directives used in the directive's template will also be excluded from execution.
  6543. *
  6544. * #### `scope`
  6545. * The scope property can be `false`, `true`, or an object:
  6546. *
  6547. * * **`false` (default):** No scope will be created for the directive. The directive will use its
  6548. * parent's scope.
  6549. *
  6550. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6551. * the directive's element. If multiple directives on the same element request a new scope,
  6552. * only one new scope is created.
  6553. *
  6554. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template.
  6555. * The 'isolate' scope differs from normal scope in that it does not prototypically
  6556. * inherit from its parent scope. This is useful when creating reusable components, which should not
  6557. * accidentally read or modify data in the parent scope. Note that an isolate scope
  6558. * directive without a `template` or `templateUrl` will not apply the isolate scope
  6559. * to its children elements.
  6560. *
  6561. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6562. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6563. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6564. * is bound to the parent scope, via matching attributes on the directive's element:
  6565. *
  6566. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6567. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6568. * attribute name is assumed to be the same as the local name. Given `<my-component
  6569. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6570. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6571. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6572. * scope. The `name` is read from the parent scope (not the directive's scope).
  6573. *
  6574. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6575. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6576. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6577. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6578. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6579. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6580. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6581. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6582. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6583. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6584. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6585. * method is used for tracking changes, and the equality check is based on object identity.
  6586. * However, if an object literal or an array literal is passed as the binding expression, the
  6587. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6588. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6589. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6590. *
  6591. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6592. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6593. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6594. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6595. *
  6596. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6597. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6598. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6599. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6600. * two caveats:
  6601. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6602. * sets the same value. That means if your bound value is an object, changes to its properties
  6603. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6604. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6605. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6606. * to the value has changed. In most cases, this should not be of concern, but can be important
  6607. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6608. * If you now change a property of the object in your parent scope, the change will not be
  6609. * propagated to the isolated scope, because the identity of the object on the parent scope
  6610. * has not changed. Instead you must assign a new object.
  6611. *
  6612. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6613. * back to the parent. However, it does not make this completely impossible.
  6614. *
  6615. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6616. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6617. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6618. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6619. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6620. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6621. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6622. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6623. *
  6624. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6625. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6626. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6627. *
  6628. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6629. * * **child scope** + **no scope** => Both directives will share one single child scope
  6630. * * **child scope** + **child scope** => Both directives will share one single child scope
  6631. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6632. * its parent's scope
  6633. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6634. * be applied to the same element.
  6635. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6636. * cannot be applied to the same element.
  6637. *
  6638. *
  6639. * #### `bindToController`
  6640. * This property is used to bind scope properties directly to the controller. It can be either
  6641. * `true` or an object hash with the same format as the `scope` property.
  6642. *
  6643. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6644. * allow a component to have its properties bound to the controller, rather than to scope.
  6645. *
  6646. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6647. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6648. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6649. * initialized.
  6650. *
  6651. * <div class="alert alert-warning">
  6652. * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
  6653. * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
  6654. * code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6655. * </div>
  6656. *
  6657. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6658. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6659. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6660. * scope (useful for component directives).
  6661. *
  6662. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6663. *
  6664. *
  6665. * #### `controller`
  6666. * Controller constructor function. The controller is instantiated before the
  6667. * pre-linking phase and can be accessed by other directives (see
  6668. * `require` attribute). This allows the directives to communicate with each other and augment
  6669. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6670. *
  6671. * * `$scope` - Current scope associated with the element
  6672. * * `$element` - Current element
  6673. * * `$attrs` - Current attributes object for the element
  6674. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6675. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6676. * * `scope`: (optional) override the scope.
  6677. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6678. * * `futureParentElement` (optional):
  6679. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6680. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6681. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6682. * and when the `cloneLinkingFn` is passed,
  6683. * as those elements need to created and cloned in a special way when they are defined outside their
  6684. * usual containers (e.g. like `<svg>`).
  6685. * * See also the `directive.templateNamespace` property.
  6686. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6687. * then the default transclusion is provided.
  6688. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6689. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6690. *
  6691. * #### `require`
  6692. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6693. * `require` property can be a string, an array or an object:
  6694. * * a **string** containing the name of the directive to pass to the linking function
  6695. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6696. * linking function will be an array of controllers in the same order as the names in the `require` property
  6697. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6698. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6699. * controllers.
  6700. *
  6701. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6702. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6703. * have been constructed but before `$onInit` is called.
  6704. * If the name of the required controller is the same as the local name (the key), the name can be
  6705. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  6706. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6707. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6708. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6709. * controller, in which case error checking is skipped). The name can be prefixed with:
  6710. *
  6711. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6712. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6713. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6714. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6715. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6716. * `null` to the `link` fn if not found.
  6717. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6718. * `null` to the `link` fn if not found.
  6719. *
  6720. *
  6721. * #### `controllerAs`
  6722. * Identifier name for a reference to the controller in the directive's scope.
  6723. * This allows the controller to be referenced from the directive template. This is especially
  6724. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6725. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6726. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6727. *
  6728. *
  6729. * #### `restrict`
  6730. * String of subset of `EACM` which restricts the directive to a specific directive
  6731. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6732. *
  6733. * * `E` - Element name (default): `<my-directive></my-directive>`
  6734. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6735. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6736. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6737. *
  6738. *
  6739. * #### `templateNamespace`
  6740. * String representing the document type used by the markup in the template.
  6741. * AngularJS needs this information as those elements need to be created and cloned
  6742. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6743. *
  6744. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6745. * top-level elements such as `<svg>` or `<math>`.
  6746. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6747. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6748. *
  6749. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6750. *
  6751. * #### `template`
  6752. * HTML markup that may:
  6753. * * Replace the contents of the directive's element (default).
  6754. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6755. * * Wrap the contents of the directive's element (if `transclude` is true).
  6756. *
  6757. * Value may be:
  6758. *
  6759. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6760. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6761. * function api below) and returns a string value.
  6762. *
  6763. *
  6764. * #### `templateUrl`
  6765. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6766. *
  6767. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6768. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6769. * sibling and parent elements as though this element had not contained any directives.
  6770. *
  6771. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6772. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6773. * case when only one deeply nested directive has `templateUrl`.
  6774. *
  6775. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6776. *
  6777. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6778. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6779. * a string value representing the url. In either case, the template URL is passed through {@link
  6780. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6781. *
  6782. *
  6783. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  6784. * specify what the template should replace. Defaults to `false`.
  6785. *
  6786. * * `true` - the template will replace the directive's element.
  6787. * * `false` - the template will replace the contents of the directive's element.
  6788. *
  6789. * The replacement process migrates all of the attributes / classes from the old element to the new
  6790. * one. See the {@link guide/directive#template-expanding-directive
  6791. * Directives Guide} for an example.
  6792. *
  6793. * There are very few scenarios where element replacement is required for the application function,
  6794. * the main one being reusable custom components that are used within SVG contexts
  6795. * (because SVG doesn't work with custom elements in the DOM tree).
  6796. *
  6797. * #### `transclude`
  6798. * Extract the contents of the element where the directive appears and make it available to the directive.
  6799. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6800. * {@link $compile#transclusion Transclusion} section below.
  6801. *
  6802. *
  6803. * #### `compile`
  6804. *
  6805. * ```js
  6806. * function compile(tElement, tAttrs, transclude) { ... }
  6807. * ```
  6808. *
  6809. * The compile function deals with transforming the template DOM. Since most directives do not do
  6810. * template transformation, it is not used often. The compile function takes the following arguments:
  6811. *
  6812. * * `tElement` - template element - The element where the directive has been declared. It is
  6813. * safe to do template transformation on the element and child elements only.
  6814. *
  6815. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6816. * between all directive compile functions.
  6817. *
  6818. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6819. *
  6820. * <div class="alert alert-warning">
  6821. * **Note:** The template instance and the link instance may be different objects if the template has
  6822. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6823. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6824. * should be done in a linking function rather than in a compile function.
  6825. * </div>
  6826. * <div class="alert alert-warning">
  6827. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6828. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6829. * stack overflow errors.
  6830. *
  6831. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6832. * a directive's template instead of relying on automatic template compilation via `template` or
  6833. * `templateUrl` declaration or manual compilation inside the compile function.
  6834. * </div>
  6835. *
  6836. * <div class="alert alert-danger">
  6837. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6838. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6839. * to the link function instead.
  6840. * </div>
  6841. * A compile function can have a return value which can be either a function or an object.
  6842. *
  6843. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6844. * `link` property of the config object when the compile function is empty.
  6845. *
  6846. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6847. * control when a linking function should be called during the linking phase. See info about
  6848. * pre-linking and post-linking functions below.
  6849. *
  6850. *
  6851. * #### `link`
  6852. * This property is used only if the `compile` property is not defined.
  6853. *
  6854. * ```js
  6855. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6856. * ```
  6857. *
  6858. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6859. * executed after the template has been cloned. This is where most of the directive logic will be
  6860. * put.
  6861. *
  6862. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6863. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6864. *
  6865. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6866. * manipulate the children of the element only in `postLink` function since the children have
  6867. * already been linked.
  6868. *
  6869. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6870. * between all directive linking functions.
  6871. *
  6872. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6873. * among all directives, which allows the directives to use the controllers as a communication
  6874. * channel. The exact value depends on the directive's `require` property:
  6875. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6876. * * `string`: the controller instance
  6877. * * `array`: array of controller instances
  6878. *
  6879. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6880. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6881. *
  6882. * Note that you can also require the directive's own controller - it will be made available like
  6883. * any other controller.
  6884. *
  6885. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6886. * This is the same as the `$transclude` parameter of directive controllers,
  6887. * see {@link ng.$compile#-controller- the controller section for details}.
  6888. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6889. *
  6890. * #### Pre-linking function
  6891. *
  6892. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6893. * compiler linking function will fail to locate the correct elements for linking.
  6894. *
  6895. * #### Post-linking function
  6896. *
  6897. * Executed after the child elements are linked.
  6898. *
  6899. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6900. * and linked since they are waiting for their template to load asynchronously and their own
  6901. * compilation and linking has been suspended until that occurs.
  6902. *
  6903. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6904. * for their async templates to be resolved.
  6905. *
  6906. *
  6907. * ### Transclusion
  6908. *
  6909. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6910. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6911. * scope from where they were taken.
  6912. *
  6913. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6914. * original contents of a directive's element into a specified place in the template of the directive.
  6915. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6916. * content has access to the properties on the scope from which it was taken, even if the directive
  6917. * has isolated scope.
  6918. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6919. *
  6920. * This makes it possible for the widget to have private state for its template, while the transcluded
  6921. * content has access to its originating scope.
  6922. *
  6923. * <div class="alert alert-warning">
  6924. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6925. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6926. * Testing Transclusion Directives}.
  6927. * </div>
  6928. *
  6929. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  6930. * directive's element, the entire element or multiple parts of the element contents:
  6931. *
  6932. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  6933. * * `'element'` - transclude the whole of the directive's element including any directives on this
  6934. * element that defined at a lower priority than this directive. When used, the `template`
  6935. * property is ignored.
  6936. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  6937. *
  6938. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  6939. *
  6940. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  6941. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  6942. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  6943. *
  6944. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6945. *
  6946. * If the element selector is prefixed with a `?` then that slot is optional.
  6947. *
  6948. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  6949. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  6950. *
  6951. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  6952. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  6953. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  6954. * injectable into the directive's controller.
  6955. *
  6956. *
  6957. * #### Transclusion Functions
  6958. *
  6959. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6960. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6961. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6962. *
  6963. * <div class="alert alert-info">
  6964. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6965. * ngTransclude will deal with it for us.
  6966. * </div>
  6967. *
  6968. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6969. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6970. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6971. *
  6972. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6973. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6974. * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
  6975. *
  6976. * <div class="alert alert-info">
  6977. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  6978. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6979. * </div>
  6980. *
  6981. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6982. * attach function**:
  6983. *
  6984. * ```js
  6985. * var transcludedContent, transclusionScope;
  6986. *
  6987. * $transclude(function(clone, scope) {
  6988. * element.append(clone);
  6989. * transcludedContent = clone;
  6990. * transclusionScope = scope;
  6991. * });
  6992. * ```
  6993. *
  6994. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6995. * associated transclusion scope:
  6996. *
  6997. * ```js
  6998. * transcludedContent.remove();
  6999. * transclusionScope.$destroy();
  7000. * ```
  7001. *
  7002. * <div class="alert alert-info">
  7003. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  7004. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  7005. * then you are also responsible for calling `$destroy` on the transclusion scope.
  7006. * </div>
  7007. *
  7008. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  7009. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  7010. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  7011. *
  7012. *
  7013. * #### Transclusion Scopes
  7014. *
  7015. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  7016. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  7017. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  7018. * was taken.
  7019. *
  7020. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  7021. * like this:
  7022. *
  7023. * ```html
  7024. * <div ng-app>
  7025. * <div isolate>
  7026. * <div transclusion>
  7027. * </div>
  7028. * </div>
  7029. * </div>
  7030. * ```
  7031. *
  7032. * The `$parent` scope hierarchy will look like this:
  7033. *
  7034. ```
  7035. - $rootScope
  7036. - isolate
  7037. - transclusion
  7038. ```
  7039. *
  7040. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  7041. *
  7042. ```
  7043. - $rootScope
  7044. - transclusion
  7045. - isolate
  7046. ```
  7047. *
  7048. *
  7049. * ### Attributes
  7050. *
  7051. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  7052. * `link()` or `compile()` functions. It has a variety of uses.
  7053. *
  7054. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  7055. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  7056. * to the attributes.
  7057. *
  7058. * * *Directive inter-communication:* All directives share the same instance of the attributes
  7059. * object which allows the directives to use the attributes object as inter directive
  7060. * communication.
  7061. *
  7062. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  7063. * allowing other directives to read the interpolated value.
  7064. *
  7065. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  7066. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  7067. * the only way to easily get the actual value because during the linking phase the interpolation
  7068. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  7069. *
  7070. * ```js
  7071. * function linkingFn(scope, elm, attrs, ctrl) {
  7072. * // get the attribute value
  7073. * console.log(attrs.ngModel);
  7074. *
  7075. * // change the attribute
  7076. * attrs.$set('ngModel', 'new value');
  7077. *
  7078. * // observe changes to interpolated attribute
  7079. * attrs.$observe('ngModel', function(value) {
  7080. * console.log('ngModel has changed value to ' + value);
  7081. * });
  7082. * }
  7083. * ```
  7084. *
  7085. * ## Example
  7086. *
  7087. * <div class="alert alert-warning">
  7088. * **Note**: Typically directives are registered with `module.directive`. The example below is
  7089. * to illustrate how `$compile` works.
  7090. * </div>
  7091. *
  7092. <example module="compileExample" name="compile">
  7093. <file name="index.html">
  7094. <script>
  7095. angular.module('compileExample', [], function($compileProvider) {
  7096. // configure new 'compile' directive by passing a directive
  7097. // factory function. The factory function injects the '$compile'
  7098. $compileProvider.directive('compile', function($compile) {
  7099. // directive factory creates a link function
  7100. return function(scope, element, attrs) {
  7101. scope.$watch(
  7102. function(scope) {
  7103. // watch the 'compile' expression for changes
  7104. return scope.$eval(attrs.compile);
  7105. },
  7106. function(value) {
  7107. // when the 'compile' expression changes
  7108. // assign it into the current DOM
  7109. element.html(value);
  7110. // compile the new DOM and link it to the current
  7111. // scope.
  7112. // NOTE: we only compile .childNodes so that
  7113. // we don't get into infinite loop compiling ourselves
  7114. $compile(element.contents())(scope);
  7115. }
  7116. );
  7117. };
  7118. });
  7119. })
  7120. .controller('GreeterController', ['$scope', function($scope) {
  7121. $scope.name = 'Angular';
  7122. $scope.html = 'Hello {{name}}';
  7123. }]);
  7124. </script>
  7125. <div ng-controller="GreeterController">
  7126. <input ng-model="name"> <br/>
  7127. <textarea ng-model="html"></textarea> <br/>
  7128. <div compile="html"></div>
  7129. </div>
  7130. </file>
  7131. <file name="protractor.js" type="protractor">
  7132. it('should auto compile', function() {
  7133. var textarea = $('textarea');
  7134. var output = $('div[compile]');
  7135. // The initial state reads 'Hello Angular'.
  7136. expect(output.getText()).toBe('Hello Angular');
  7137. textarea.clear();
  7138. textarea.sendKeys('{{name}}!');
  7139. expect(output.getText()).toBe('Angular!');
  7140. });
  7141. </file>
  7142. </example>
  7143. *
  7144. *
  7145. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  7146. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  7147. *
  7148. * <div class="alert alert-danger">
  7149. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  7150. * e.g. will not use the right outer scope. Please pass the transclude function as a
  7151. * `parentBoundTranscludeFn` to the link function instead.
  7152. * </div>
  7153. *
  7154. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  7155. * root element(s), not their children)
  7156. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  7157. * (a DOM element/tree) to a scope. Where:
  7158. *
  7159. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  7160. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  7161. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  7162. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  7163. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  7164. *
  7165. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  7166. * * `scope` - is the current scope with which the linking function is working with.
  7167. *
  7168. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  7169. * keys may be used to control linking behavior:
  7170. *
  7171. * * `parentBoundTranscludeFn` - the transclude function made available to
  7172. * directives; if given, it will be passed through to the link functions of
  7173. * directives found in `element` during compilation.
  7174. * * `transcludeControllers` - an object hash with keys that map controller names
  7175. * to a hash with the key `instance`, which maps to the controller instance;
  7176. * if given, it will make the controllers available to directives on the compileNode:
  7177. * ```
  7178. * {
  7179. * parent: {
  7180. * instance: parentControllerInstance
  7181. * }
  7182. * }
  7183. * ```
  7184. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  7185. * the cloned elements; only needed for transcludes that are allowed to contain non html
  7186. * elements (e.g. SVG elements). See also the directive.controller property.
  7187. *
  7188. * Calling the linking function returns the element of the template. It is either the original
  7189. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  7190. *
  7191. * After linking the view is not updated until after a call to $digest which typically is done by
  7192. * Angular automatically.
  7193. *
  7194. * If you need access to the bound view, there are two ways to do it:
  7195. *
  7196. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  7197. * before you send them to the compiler and keep this reference around.
  7198. * ```js
  7199. * var element = $compile('<p>{{total}}</p>')(scope);
  7200. * ```
  7201. *
  7202. * - if on the other hand, you need the element to be cloned, the view reference from the original
  7203. * example would not point to the clone, but rather to the original template that was cloned. In
  7204. * this case, you can access the clone via the cloneAttachFn:
  7205. * ```js
  7206. * var templateElement = angular.element('<p>{{total}}</p>'),
  7207. * scope = ....;
  7208. *
  7209. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  7210. * //attach the clone to DOM document at the right place
  7211. * });
  7212. *
  7213. * //now we have reference to the cloned DOM via `clonedElement`
  7214. * ```
  7215. *
  7216. *
  7217. * For information on how the compiler works, see the
  7218. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  7219. *
  7220. * @knownIssue
  7221. *
  7222. * ### Double Compilation
  7223. *
  7224. Double compilation occurs when an already compiled part of the DOM gets
  7225. compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,
  7226. and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it
  7227. section on double compilation} for an in-depth explanation and ways to avoid it.
  7228. *
  7229. */
  7230. var $compileMinErr = minErr('$compile');
  7231. function UNINITIALIZED_VALUE() {}
  7232. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  7233. /**
  7234. * @ngdoc provider
  7235. * @name $compileProvider
  7236. *
  7237. * @description
  7238. */
  7239. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  7240. /** @this */
  7241. function $CompileProvider($provide, $$sanitizeUriProvider) {
  7242. var hasDirectives = {},
  7243. Suffix = 'Directive',
  7244. COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/,
  7245. CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,
  7246. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  7247. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  7248. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  7249. // The assumption is that future DOM event attribute names will begin with
  7250. // 'on' and be composed of only English letters.
  7251. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  7252. var bindingCache = createMap();
  7253. function parseIsolateBindings(scope, directiveName, isController) {
  7254. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*([\w$]*)\s*$/;
  7255. var bindings = createMap();
  7256. forEach(scope, function(definition, scopeName) {
  7257. if (definition in bindingCache) {
  7258. bindings[scopeName] = bindingCache[definition];
  7259. return;
  7260. }
  7261. var match = definition.match(LOCAL_REGEXP);
  7262. if (!match) {
  7263. throw $compileMinErr('iscp',
  7264. 'Invalid {3} for directive \'{0}\'.' +
  7265. ' Definition: {... {1}: \'{2}\' ...}',
  7266. directiveName, scopeName, definition,
  7267. (isController ? 'controller bindings definition' :
  7268. 'isolate scope definition'));
  7269. }
  7270. bindings[scopeName] = {
  7271. mode: match[1][0],
  7272. collection: match[2] === '*',
  7273. optional: match[3] === '?',
  7274. attrName: match[4] || scopeName
  7275. };
  7276. if (match[4]) {
  7277. bindingCache[definition] = bindings[scopeName];
  7278. }
  7279. });
  7280. return bindings;
  7281. }
  7282. function parseDirectiveBindings(directive, directiveName) {
  7283. var bindings = {
  7284. isolateScope: null,
  7285. bindToController: null
  7286. };
  7287. if (isObject(directive.scope)) {
  7288. if (directive.bindToController === true) {
  7289. bindings.bindToController = parseIsolateBindings(directive.scope,
  7290. directiveName, true);
  7291. bindings.isolateScope = {};
  7292. } else {
  7293. bindings.isolateScope = parseIsolateBindings(directive.scope,
  7294. directiveName, false);
  7295. }
  7296. }
  7297. if (isObject(directive.bindToController)) {
  7298. bindings.bindToController =
  7299. parseIsolateBindings(directive.bindToController, directiveName, true);
  7300. }
  7301. if (bindings.bindToController && !directive.controller) {
  7302. // There is no controller
  7303. throw $compileMinErr('noctrl',
  7304. 'Cannot bind to controller without directive \'{0}\'s controller.',
  7305. directiveName);
  7306. }
  7307. return bindings;
  7308. }
  7309. function assertValidDirectiveName(name) {
  7310. var letter = name.charAt(0);
  7311. if (!letter || letter !== lowercase(letter)) {
  7312. throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
  7313. }
  7314. if (name !== name.trim()) {
  7315. throw $compileMinErr('baddir',
  7316. 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
  7317. name);
  7318. }
  7319. }
  7320. function getDirectiveRequire(directive) {
  7321. var require = directive.require || (directive.controller && directive.name);
  7322. if (!isArray(require) && isObject(require)) {
  7323. forEach(require, function(value, key) {
  7324. var match = value.match(REQUIRE_PREFIX_REGEXP);
  7325. var name = value.substring(match[0].length);
  7326. if (!name) require[key] = match[0] + key;
  7327. });
  7328. }
  7329. return require;
  7330. }
  7331. function getDirectiveRestrict(restrict, name) {
  7332. if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
  7333. throw $compileMinErr('badrestrict',
  7334. 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
  7335. restrict,
  7336. name);
  7337. }
  7338. return restrict || 'EA';
  7339. }
  7340. /**
  7341. * @ngdoc method
  7342. * @name $compileProvider#directive
  7343. * @kind function
  7344. *
  7345. * @description
  7346. * Register a new directive with the compiler.
  7347. *
  7348. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  7349. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  7350. * names and the values are the factories.
  7351. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  7352. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  7353. * @returns {ng.$compileProvider} Self for chaining.
  7354. */
  7355. this.directive = function registerDirective(name, directiveFactory) {
  7356. assertArg(name, 'name');
  7357. assertNotHasOwnProperty(name, 'directive');
  7358. if (isString(name)) {
  7359. assertValidDirectiveName(name);
  7360. assertArg(directiveFactory, 'directiveFactory');
  7361. if (!hasDirectives.hasOwnProperty(name)) {
  7362. hasDirectives[name] = [];
  7363. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  7364. function($injector, $exceptionHandler) {
  7365. var directives = [];
  7366. forEach(hasDirectives[name], function(directiveFactory, index) {
  7367. try {
  7368. var directive = $injector.invoke(directiveFactory);
  7369. if (isFunction(directive)) {
  7370. directive = { compile: valueFn(directive) };
  7371. } else if (!directive.compile && directive.link) {
  7372. directive.compile = valueFn(directive.link);
  7373. }
  7374. directive.priority = directive.priority || 0;
  7375. directive.index = index;
  7376. directive.name = directive.name || name;
  7377. directive.require = getDirectiveRequire(directive);
  7378. directive.restrict = getDirectiveRestrict(directive.restrict, name);
  7379. directive.$$moduleName = directiveFactory.$$moduleName;
  7380. directives.push(directive);
  7381. } catch (e) {
  7382. $exceptionHandler(e);
  7383. }
  7384. });
  7385. return directives;
  7386. }]);
  7387. }
  7388. hasDirectives[name].push(directiveFactory);
  7389. } else {
  7390. forEach(name, reverseParams(registerDirective));
  7391. }
  7392. return this;
  7393. };
  7394. /**
  7395. * @ngdoc method
  7396. * @name $compileProvider#component
  7397. * @module ng
  7398. * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
  7399. * @param {Object} options Component definition object (a simplified
  7400. * {@link ng.$compile#directive-definition-object directive definition object}),
  7401. * with the following properties (all optional):
  7402. *
  7403. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  7404. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  7405. * registered controller} if passed as a string. An empty `noop` function by default.
  7406. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  7407. * If present, the controller will be published to scope under the `controllerAs` name.
  7408. * If not present, this will default to be `$ctrl`.
  7409. * - `template` – `{string=|function()=}` – html template as a string or a function that
  7410. * returns an html template as a string which should be used as the contents of this component.
  7411. * Empty string by default.
  7412. *
  7413. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  7414. * the following locals:
  7415. *
  7416. * - `$element` - Current element
  7417. * - `$attrs` - Current attributes object for the element
  7418. *
  7419. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  7420. * template that should be used as the contents of this component.
  7421. *
  7422. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  7423. * the following locals:
  7424. *
  7425. * - `$element` - Current element
  7426. * - `$attrs` - Current attributes object for the element
  7427. *
  7428. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  7429. * Component properties are always bound to the component controller and not to the scope.
  7430. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  7431. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  7432. * Disabled by default.
  7433. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  7434. * this component's controller. The object keys specify the property names under which the required
  7435. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  7436. * - `$...` – additional properties to attach to the directive factory function and the controller
  7437. * constructor function. (This is used by the component router to annotate)
  7438. *
  7439. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  7440. * @description
  7441. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  7442. * type of directive, which represents a self-contained UI component in your application. Such components
  7443. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  7444. *
  7445. * Component definitions are very simple and do not require as much configuration as defining general
  7446. * directives. Component definitions usually consist only of a template and a controller backing it.
  7447. *
  7448. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  7449. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  7450. *
  7451. * Here are a few examples of how you would usually define components:
  7452. *
  7453. * ```js
  7454. * var myMod = angular.module(...);
  7455. * myMod.component('myComp', {
  7456. * template: '<div>My name is {{$ctrl.name}}</div>',
  7457. * controller: function() {
  7458. * this.name = 'shahar';
  7459. * }
  7460. * });
  7461. *
  7462. * myMod.component('myComp', {
  7463. * template: '<div>My name is {{$ctrl.name}}</div>',
  7464. * bindings: {name: '@'}
  7465. * });
  7466. *
  7467. * myMod.component('myComp', {
  7468. * templateUrl: 'views/my-comp.html',
  7469. * controller: 'MyCtrl',
  7470. * controllerAs: 'ctrl',
  7471. * bindings: {name: '@'}
  7472. * });
  7473. *
  7474. * ```
  7475. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  7476. *
  7477. * <br />
  7478. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  7479. */
  7480. this.component = function registerComponent(name, options) {
  7481. var controller = options.controller || function() {};
  7482. function factory($injector) {
  7483. function makeInjectable(fn) {
  7484. if (isFunction(fn) || isArray(fn)) {
  7485. return /** @this */ function(tElement, tAttrs) {
  7486. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  7487. };
  7488. } else {
  7489. return fn;
  7490. }
  7491. }
  7492. var template = (!options.template && !options.templateUrl ? '' : options.template);
  7493. var ddo = {
  7494. controller: controller,
  7495. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  7496. template: makeInjectable(template),
  7497. templateUrl: makeInjectable(options.templateUrl),
  7498. transclude: options.transclude,
  7499. scope: {},
  7500. bindToController: options.bindings || {},
  7501. restrict: 'E',
  7502. require: options.require
  7503. };
  7504. // Copy annotations (starting with $) over to the DDO
  7505. forEach(options, function(val, key) {
  7506. if (key.charAt(0) === '$') ddo[key] = val;
  7507. });
  7508. return ddo;
  7509. }
  7510. // TODO(pete) remove the following `forEach` before we release 1.6.0
  7511. // The component-router@0.2.0 looks for the annotations on the controller constructor
  7512. // Nothing in Angular looks for annotations on the factory function but we can't remove
  7513. // it from 1.5.x yet.
  7514. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  7515. // These could be used by libraries such as the new component router
  7516. forEach(options, function(val, key) {
  7517. if (key.charAt(0) === '$') {
  7518. factory[key] = val;
  7519. // Don't try to copy over annotations to named controller
  7520. if (isFunction(controller)) controller[key] = val;
  7521. }
  7522. });
  7523. factory.$inject = ['$injector'];
  7524. return this.directive(name, factory);
  7525. };
  7526. /**
  7527. * @ngdoc method
  7528. * @name $compileProvider#aHrefSanitizationWhitelist
  7529. * @kind function
  7530. *
  7531. * @description
  7532. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7533. * urls during a[href] sanitization.
  7534. *
  7535. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  7536. *
  7537. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  7538. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  7539. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7540. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7541. *
  7542. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7543. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7544. * chaining otherwise.
  7545. */
  7546. this.aHrefSanitizationWhitelist = function(regexp) {
  7547. if (isDefined(regexp)) {
  7548. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  7549. return this;
  7550. } else {
  7551. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  7552. }
  7553. };
  7554. /**
  7555. * @ngdoc method
  7556. * @name $compileProvider#imgSrcSanitizationWhitelist
  7557. * @kind function
  7558. *
  7559. * @description
  7560. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7561. * urls during img[src] sanitization.
  7562. *
  7563. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  7564. *
  7565. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  7566. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  7567. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7568. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7569. *
  7570. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7571. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7572. * chaining otherwise.
  7573. */
  7574. this.imgSrcSanitizationWhitelist = function(regexp) {
  7575. if (isDefined(regexp)) {
  7576. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  7577. return this;
  7578. } else {
  7579. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  7580. }
  7581. };
  7582. /**
  7583. * @ngdoc method
  7584. * @name $compileProvider#debugInfoEnabled
  7585. *
  7586. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  7587. * current debugInfoEnabled state
  7588. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7589. *
  7590. * @kind function
  7591. *
  7592. * @description
  7593. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7594. * binding information and a reference to the current scope on to DOM elements.
  7595. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7596. * * `ng-binding` CSS class
  7597. * * `$binding` data property containing an array of the binding expressions
  7598. *
  7599. * You may want to disable this in production for a significant performance boost. See
  7600. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7601. *
  7602. * The default value is true.
  7603. */
  7604. var debugInfoEnabled = true;
  7605. this.debugInfoEnabled = function(enabled) {
  7606. if (isDefined(enabled)) {
  7607. debugInfoEnabled = enabled;
  7608. return this;
  7609. }
  7610. return debugInfoEnabled;
  7611. };
  7612. /**
  7613. * @ngdoc method
  7614. * @name $compileProvider#preAssignBindingsEnabled
  7615. *
  7616. * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the
  7617. * current preAssignBindingsEnabled state
  7618. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7619. *
  7620. * @kind function
  7621. *
  7622. * @description
  7623. * Call this method to enable/disable whether directive controllers are assigned bindings before
  7624. * calling the controller's constructor.
  7625. * If enabled (true), the compiler assigns the value of each of the bindings to the
  7626. * properties of the controller object before the constructor of this object is called.
  7627. *
  7628. * If disabled (false), the compiler calls the constructor first before assigning bindings.
  7629. *
  7630. * The default value is true in Angular 1.5.x but will switch to false in Angular 1.6.x.
  7631. */
  7632. var preAssignBindingsEnabled = false;
  7633. this.preAssignBindingsEnabled = function(enabled) {
  7634. if (isDefined(enabled)) {
  7635. preAssignBindingsEnabled = enabled;
  7636. return this;
  7637. }
  7638. return preAssignBindingsEnabled;
  7639. };
  7640. var TTL = 10;
  7641. /**
  7642. * @ngdoc method
  7643. * @name $compileProvider#onChangesTtl
  7644. * @description
  7645. *
  7646. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  7647. * assuming that the model is unstable.
  7648. *
  7649. * The current default is 10 iterations.
  7650. *
  7651. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  7652. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  7653. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  7654. * the `$onChanges` hook execution.
  7655. *
  7656. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  7657. *
  7658. * @param {number} limit The number of `$onChanges` hook iterations.
  7659. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  7660. */
  7661. this.onChangesTtl = function(value) {
  7662. if (arguments.length) {
  7663. TTL = value;
  7664. return this;
  7665. }
  7666. return TTL;
  7667. };
  7668. var commentDirectivesEnabledConfig = true;
  7669. /**
  7670. * @ngdoc method
  7671. * @name $compileProvider#commentDirectivesEnabled
  7672. * @description
  7673. *
  7674. * It indicates to the compiler
  7675. * whether or not directives on comments should be compiled.
  7676. * Defaults to `true`.
  7677. *
  7678. * Calling this function with false disables the compilation of directives
  7679. * on comments for the whole application.
  7680. * This results in a compilation performance gain,
  7681. * as the compiler doesn't have to check comments when looking for directives.
  7682. * This should however only be used if you are sure that no comment directives are used in
  7683. * the application (including any 3rd party directives).
  7684. *
  7685. * @param {boolean} enabled `false` if the compiler may ignore directives on comments
  7686. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7687. */
  7688. this.commentDirectivesEnabled = function(value) {
  7689. if (arguments.length) {
  7690. commentDirectivesEnabledConfig = value;
  7691. return this;
  7692. }
  7693. return commentDirectivesEnabledConfig;
  7694. };
  7695. var cssClassDirectivesEnabledConfig = true;
  7696. /**
  7697. * @ngdoc method
  7698. * @name $compileProvider#cssClassDirectivesEnabled
  7699. * @description
  7700. *
  7701. * It indicates to the compiler
  7702. * whether or not directives on element classes should be compiled.
  7703. * Defaults to `true`.
  7704. *
  7705. * Calling this function with false disables the compilation of directives
  7706. * on element classes for the whole application.
  7707. * This results in a compilation performance gain,
  7708. * as the compiler doesn't have to check element classes when looking for directives.
  7709. * This should however only be used if you are sure that no class directives are used in
  7710. * the application (including any 3rd party directives).
  7711. *
  7712. * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
  7713. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7714. */
  7715. this.cssClassDirectivesEnabled = function(value) {
  7716. if (arguments.length) {
  7717. cssClassDirectivesEnabledConfig = value;
  7718. return this;
  7719. }
  7720. return cssClassDirectivesEnabledConfig;
  7721. };
  7722. this.$get = [
  7723. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7724. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7725. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7726. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7727. var SIMPLE_ATTR_NAME = /^\w/;
  7728. var specialAttrHolder = window.document.createElement('div');
  7729. var commentDirectivesEnabled = commentDirectivesEnabledConfig;
  7730. var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
  7731. var onChangesTtl = TTL;
  7732. // The onChanges hooks should all be run together in a single digest
  7733. // When changes occur, the call to trigger their hooks will be added to this queue
  7734. var onChangesQueue;
  7735. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  7736. function flushOnChangesQueue() {
  7737. try {
  7738. if (!(--onChangesTtl)) {
  7739. // We have hit the TTL limit so reset everything
  7740. onChangesQueue = undefined;
  7741. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  7742. }
  7743. // We must run this hook in an apply since the $$postDigest runs outside apply
  7744. $rootScope.$apply(function() {
  7745. var errors = [];
  7746. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  7747. try {
  7748. onChangesQueue[i]();
  7749. } catch (e) {
  7750. errors.push(e);
  7751. }
  7752. }
  7753. // Reset the queue to trigger a new schedule next time there is a change
  7754. onChangesQueue = undefined;
  7755. if (errors.length) {
  7756. throw errors;
  7757. }
  7758. });
  7759. } finally {
  7760. onChangesTtl++;
  7761. }
  7762. }
  7763. function Attributes(element, attributesToCopy) {
  7764. if (attributesToCopy) {
  7765. var keys = Object.keys(attributesToCopy);
  7766. var i, l, key;
  7767. for (i = 0, l = keys.length; i < l; i++) {
  7768. key = keys[i];
  7769. this[key] = attributesToCopy[key];
  7770. }
  7771. } else {
  7772. this.$attr = {};
  7773. }
  7774. this.$$element = element;
  7775. }
  7776. Attributes.prototype = {
  7777. /**
  7778. * @ngdoc method
  7779. * @name $compile.directive.Attributes#$normalize
  7780. * @kind function
  7781. *
  7782. * @description
  7783. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7784. * `data-`) to its normalized, camelCase form.
  7785. *
  7786. * Also there is special case for Moz prefix starting with upper case letter.
  7787. *
  7788. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7789. *
  7790. * @param {string} name Name to normalize
  7791. */
  7792. $normalize: directiveNormalize,
  7793. /**
  7794. * @ngdoc method
  7795. * @name $compile.directive.Attributes#$addClass
  7796. * @kind function
  7797. *
  7798. * @description
  7799. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7800. * are enabled then an animation will be triggered for the class addition.
  7801. *
  7802. * @param {string} classVal The className value that will be added to the element
  7803. */
  7804. $addClass: function(classVal) {
  7805. if (classVal && classVal.length > 0) {
  7806. $animate.addClass(this.$$element, classVal);
  7807. }
  7808. },
  7809. /**
  7810. * @ngdoc method
  7811. * @name $compile.directive.Attributes#$removeClass
  7812. * @kind function
  7813. *
  7814. * @description
  7815. * Removes the CSS class value specified by the classVal parameter from the element. If
  7816. * animations are enabled then an animation will be triggered for the class removal.
  7817. *
  7818. * @param {string} classVal The className value that will be removed from the element
  7819. */
  7820. $removeClass: function(classVal) {
  7821. if (classVal && classVal.length > 0) {
  7822. $animate.removeClass(this.$$element, classVal);
  7823. }
  7824. },
  7825. /**
  7826. * @ngdoc method
  7827. * @name $compile.directive.Attributes#$updateClass
  7828. * @kind function
  7829. *
  7830. * @description
  7831. * Adds and removes the appropriate CSS class values to the element based on the difference
  7832. * between the new and old CSS class values (specified as newClasses and oldClasses).
  7833. *
  7834. * @param {string} newClasses The current CSS className value
  7835. * @param {string} oldClasses The former CSS className value
  7836. */
  7837. $updateClass: function(newClasses, oldClasses) {
  7838. var toAdd = tokenDifference(newClasses, oldClasses);
  7839. if (toAdd && toAdd.length) {
  7840. $animate.addClass(this.$$element, toAdd);
  7841. }
  7842. var toRemove = tokenDifference(oldClasses, newClasses);
  7843. if (toRemove && toRemove.length) {
  7844. $animate.removeClass(this.$$element, toRemove);
  7845. }
  7846. },
  7847. /**
  7848. * Set a normalized attribute on the element in a way such that all directives
  7849. * can share the attribute. This function properly handles boolean attributes.
  7850. * @param {string} key Normalized key. (ie ngAttribute)
  7851. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  7852. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  7853. * Defaults to true.
  7854. * @param {string=} attrName Optional none normalized name. Defaults to key.
  7855. */
  7856. $set: function(key, value, writeAttr, attrName) {
  7857. // TODO: decide whether or not to throw an error if "class"
  7858. //is set through this function since it may cause $updateClass to
  7859. //become unstable.
  7860. var node = this.$$element[0],
  7861. booleanKey = getBooleanAttrName(node, key),
  7862. aliasedKey = getAliasedAttrName(key),
  7863. observer = key,
  7864. nodeName;
  7865. if (booleanKey) {
  7866. this.$$element.prop(key, value);
  7867. attrName = booleanKey;
  7868. } else if (aliasedKey) {
  7869. this[aliasedKey] = value;
  7870. observer = aliasedKey;
  7871. }
  7872. this[key] = value;
  7873. // translate normalized key to actual key
  7874. if (attrName) {
  7875. this.$attr[key] = attrName;
  7876. } else {
  7877. attrName = this.$attr[key];
  7878. if (!attrName) {
  7879. this.$attr[key] = attrName = snake_case(key, '-');
  7880. }
  7881. }
  7882. nodeName = nodeName_(this.$$element);
  7883. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  7884. (nodeName === 'img' && key === 'src')) {
  7885. // sanitize a[href] and img[src] values
  7886. this[key] = value = $$sanitizeUri(value, key === 'src');
  7887. } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
  7888. // sanitize img[srcset] values
  7889. var result = '';
  7890. // first check if there are spaces because it's not the same pattern
  7891. var trimmedSrcset = trim(value);
  7892. // ( 999x ,| 999w ,| ,|, )
  7893. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  7894. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  7895. // split srcset into tuple of uri and descriptor except for the last item
  7896. var rawUris = trimmedSrcset.split(pattern);
  7897. // for each tuples
  7898. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  7899. for (var i = 0; i < nbrUrisWith2parts; i++) {
  7900. var innerIdx = i * 2;
  7901. // sanitize the uri
  7902. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  7903. // add the descriptor
  7904. result += (' ' + trim(rawUris[innerIdx + 1]));
  7905. }
  7906. // split the last item into uri and descriptor
  7907. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  7908. // sanitize the last uri
  7909. result += $$sanitizeUri(trim(lastTuple[0]), true);
  7910. // and add the last descriptor if any
  7911. if (lastTuple.length === 2) {
  7912. result += (' ' + trim(lastTuple[1]));
  7913. }
  7914. this[key] = value = result;
  7915. }
  7916. if (writeAttr !== false) {
  7917. if (value === null || isUndefined(value)) {
  7918. this.$$element.removeAttr(attrName);
  7919. } else {
  7920. if (SIMPLE_ATTR_NAME.test(attrName)) {
  7921. this.$$element.attr(attrName, value);
  7922. } else {
  7923. setSpecialAttr(this.$$element[0], attrName, value);
  7924. }
  7925. }
  7926. }
  7927. // fire observers
  7928. var $$observers = this.$$observers;
  7929. if ($$observers) {
  7930. forEach($$observers[observer], function(fn) {
  7931. try {
  7932. fn(value);
  7933. } catch (e) {
  7934. $exceptionHandler(e);
  7935. }
  7936. });
  7937. }
  7938. },
  7939. /**
  7940. * @ngdoc method
  7941. * @name $compile.directive.Attributes#$observe
  7942. * @kind function
  7943. *
  7944. * @description
  7945. * Observes an interpolated attribute.
  7946. *
  7947. * The observer function will be invoked once during the next `$digest` following
  7948. * compilation. The observer is then invoked whenever the interpolated value
  7949. * changes.
  7950. *
  7951. * @param {string} key Normalized key. (ie ngAttribute) .
  7952. * @param {function(interpolatedValue)} fn Function that will be called whenever
  7953. the interpolated value of the attribute changes.
  7954. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  7955. * guide} for more info.
  7956. * @returns {function()} Returns a deregistration function for this observer.
  7957. */
  7958. $observe: function(key, fn) {
  7959. var attrs = this,
  7960. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  7961. listeners = ($$observers[key] || ($$observers[key] = []));
  7962. listeners.push(fn);
  7963. $rootScope.$evalAsync(function() {
  7964. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  7965. // no one registered attribute interpolation function, so lets call it manually
  7966. fn(attrs[key]);
  7967. }
  7968. });
  7969. return function() {
  7970. arrayRemove(listeners, fn);
  7971. };
  7972. }
  7973. };
  7974. function setSpecialAttr(element, attrName, value) {
  7975. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  7976. // so we have to jump through some hoops to get such an attribute
  7977. // https://github.com/angular/angular.js/pull/13318
  7978. specialAttrHolder.innerHTML = '<span ' + attrName + '>';
  7979. var attributes = specialAttrHolder.firstChild.attributes;
  7980. var attribute = attributes[0];
  7981. // We have to remove the attribute from its container element before we can add it to the destination element
  7982. attributes.removeNamedItem(attribute.name);
  7983. attribute.value = value;
  7984. element.attributes.setNamedItem(attribute);
  7985. }
  7986. function safeAddClass($element, className) {
  7987. try {
  7988. $element.addClass(className);
  7989. } catch (e) {
  7990. // ignore, since it means that we are trying to set class on
  7991. // SVG element, where class name is read-only.
  7992. }
  7993. }
  7994. var startSymbol = $interpolate.startSymbol(),
  7995. endSymbol = $interpolate.endSymbol(),
  7996. denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
  7997. ? identity
  7998. : function denormalizeTemplate(template) {
  7999. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  8000. },
  8001. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  8002. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  8003. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  8004. var bindings = $element.data('$binding') || [];
  8005. if (isArray(binding)) {
  8006. bindings = bindings.concat(binding);
  8007. } else {
  8008. bindings.push(binding);
  8009. }
  8010. $element.data('$binding', bindings);
  8011. } : noop;
  8012. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  8013. safeAddClass($element, 'ng-binding');
  8014. } : noop;
  8015. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  8016. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  8017. $element.data(dataName, scope);
  8018. } : noop;
  8019. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  8020. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  8021. } : noop;
  8022. compile.$$createComment = function(directiveName, comment) {
  8023. var content = '';
  8024. if (debugInfoEnabled) {
  8025. content = ' ' + (directiveName || '') + ': ';
  8026. if (comment) content += comment + ' ';
  8027. }
  8028. return window.document.createComment(content);
  8029. };
  8030. return compile;
  8031. //================================
  8032. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  8033. previousCompileContext) {
  8034. if (!($compileNodes instanceof jqLite)) {
  8035. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  8036. // modify it.
  8037. $compileNodes = jqLite($compileNodes);
  8038. }
  8039. var compositeLinkFn =
  8040. compileNodes($compileNodes, transcludeFn, $compileNodes,
  8041. maxPriority, ignoreDirective, previousCompileContext);
  8042. compile.$$addScopeClass($compileNodes);
  8043. var namespace = null;
  8044. return function publicLinkFn(scope, cloneConnectFn, options) {
  8045. if (!$compileNodes) {
  8046. throw $compileMinErr('multilink', 'This element has already been linked.');
  8047. }
  8048. assertArg(scope, 'scope');
  8049. if (previousCompileContext && previousCompileContext.needsNewScope) {
  8050. // A parent directive did a replace and a directive on this element asked
  8051. // for transclusion, which caused us to lose a layer of element on which
  8052. // we could hold the new transclusion scope, so we will create it manually
  8053. // here.
  8054. scope = scope.$parent.$new();
  8055. }
  8056. options = options || {};
  8057. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  8058. transcludeControllers = options.transcludeControllers,
  8059. futureParentElement = options.futureParentElement;
  8060. // When `parentBoundTranscludeFn` is passed, it is a
  8061. // `controllersBoundTransclude` function (it was previously passed
  8062. // as `transclude` to directive.link) so we must unwrap it to get
  8063. // its `boundTranscludeFn`
  8064. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  8065. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  8066. }
  8067. if (!namespace) {
  8068. namespace = detectNamespaceForChildElements(futureParentElement);
  8069. }
  8070. var $linkNode;
  8071. if (namespace !== 'html') {
  8072. // When using a directive with replace:true and templateUrl the $compileNodes
  8073. // (or a child element inside of them)
  8074. // might change, so we need to recreate the namespace adapted compileNodes
  8075. // for call to the link function.
  8076. // Note: This will already clone the nodes...
  8077. $linkNode = jqLite(
  8078. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  8079. );
  8080. } else if (cloneConnectFn) {
  8081. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  8082. // and sometimes changes the structure of the DOM.
  8083. $linkNode = JQLitePrototype.clone.call($compileNodes);
  8084. } else {
  8085. $linkNode = $compileNodes;
  8086. }
  8087. if (transcludeControllers) {
  8088. for (var controllerName in transcludeControllers) {
  8089. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  8090. }
  8091. }
  8092. compile.$$addScopeInfo($linkNode, scope);
  8093. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  8094. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  8095. if (!cloneConnectFn) {
  8096. $compileNodes = compositeLinkFn = null;
  8097. }
  8098. return $linkNode;
  8099. };
  8100. }
  8101. function detectNamespaceForChildElements(parentElement) {
  8102. // TODO: Make this detect MathML as well...
  8103. var node = parentElement && parentElement[0];
  8104. if (!node) {
  8105. return 'html';
  8106. } else {
  8107. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  8108. }
  8109. }
  8110. /**
  8111. * Compile function matches each node in nodeList against the directives. Once all directives
  8112. * for a particular node are collected their compile functions are executed. The compile
  8113. * functions return values - the linking functions - are combined into a composite linking
  8114. * function, which is the a linking function for the node.
  8115. *
  8116. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  8117. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8118. * scope argument is auto-generated to the new child of the transcluded parent scope.
  8119. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  8120. * the rootElement must be set the jqLite collection of the compile root. This is
  8121. * needed so that the jqLite collection items can be replaced with widgets.
  8122. * @param {number=} maxPriority Max directive priority.
  8123. * @returns {Function} A composite linking function of all of the matched directives or null.
  8124. */
  8125. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  8126. previousCompileContext) {
  8127. var linkFns = [],
  8128. // `nodeList` can be either an element's `.childNodes` (live NodeList)
  8129. // or a jqLite/jQuery collection or an array
  8130. notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),
  8131. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  8132. for (var i = 0; i < nodeList.length; i++) {
  8133. attrs = new Attributes();
  8134. // Support: IE 11 only
  8135. // Workaround for #11781 and #14924
  8136. if (msie === 11) {
  8137. mergeConsecutiveTextNodes(nodeList, i, notLiveList);
  8138. }
  8139. // We must always refer to `nodeList[i]` hereafter,
  8140. // since the nodes can be replaced underneath us.
  8141. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  8142. ignoreDirective);
  8143. nodeLinkFn = (directives.length)
  8144. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  8145. null, [], [], previousCompileContext)
  8146. : null;
  8147. if (nodeLinkFn && nodeLinkFn.scope) {
  8148. compile.$$addScopeClass(attrs.$$element);
  8149. }
  8150. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  8151. !(childNodes = nodeList[i].childNodes) ||
  8152. !childNodes.length)
  8153. ? null
  8154. : compileNodes(childNodes,
  8155. nodeLinkFn ? (
  8156. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  8157. && nodeLinkFn.transclude) : transcludeFn);
  8158. if (nodeLinkFn || childLinkFn) {
  8159. linkFns.push(i, nodeLinkFn, childLinkFn);
  8160. linkFnFound = true;
  8161. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  8162. }
  8163. //use the previous context only for the first element in the virtual group
  8164. previousCompileContext = null;
  8165. }
  8166. // return a linking function if we have found anything, null otherwise
  8167. return linkFnFound ? compositeLinkFn : null;
  8168. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  8169. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  8170. var stableNodeList;
  8171. if (nodeLinkFnFound) {
  8172. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  8173. // offsets don't get screwed up
  8174. var nodeListLength = nodeList.length;
  8175. stableNodeList = new Array(nodeListLength);
  8176. // create a sparse array by only copying the elements which have a linkFn
  8177. for (i = 0; i < linkFns.length; i += 3) {
  8178. idx = linkFns[i];
  8179. stableNodeList[idx] = nodeList[idx];
  8180. }
  8181. } else {
  8182. stableNodeList = nodeList;
  8183. }
  8184. for (i = 0, ii = linkFns.length; i < ii;) {
  8185. node = stableNodeList[linkFns[i++]];
  8186. nodeLinkFn = linkFns[i++];
  8187. childLinkFn = linkFns[i++];
  8188. if (nodeLinkFn) {
  8189. if (nodeLinkFn.scope) {
  8190. childScope = scope.$new();
  8191. compile.$$addScopeInfo(jqLite(node), childScope);
  8192. } else {
  8193. childScope = scope;
  8194. }
  8195. if (nodeLinkFn.transcludeOnThisElement) {
  8196. childBoundTranscludeFn = createBoundTranscludeFn(
  8197. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  8198. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  8199. childBoundTranscludeFn = parentBoundTranscludeFn;
  8200. } else if (!parentBoundTranscludeFn && transcludeFn) {
  8201. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  8202. } else {
  8203. childBoundTranscludeFn = null;
  8204. }
  8205. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  8206. } else if (childLinkFn) {
  8207. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  8208. }
  8209. }
  8210. }
  8211. }
  8212. function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {
  8213. var node = nodeList[idx];
  8214. var parent = node.parentNode;
  8215. var sibling;
  8216. if (node.nodeType !== NODE_TYPE_TEXT) {
  8217. return;
  8218. }
  8219. while (true) {
  8220. sibling = parent ? node.nextSibling : nodeList[idx + 1];
  8221. if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {
  8222. break;
  8223. }
  8224. node.nodeValue = node.nodeValue + sibling.nodeValue;
  8225. if (sibling.parentNode) {
  8226. sibling.parentNode.removeChild(sibling);
  8227. }
  8228. if (notLiveList && sibling === nodeList[idx + 1]) {
  8229. nodeList.splice(idx + 1, 1);
  8230. }
  8231. }
  8232. }
  8233. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  8234. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  8235. if (!transcludedScope) {
  8236. transcludedScope = scope.$new(false, containingScope);
  8237. transcludedScope.$$transcluded = true;
  8238. }
  8239. return transcludeFn(transcludedScope, cloneFn, {
  8240. parentBoundTranscludeFn: previousBoundTranscludeFn,
  8241. transcludeControllers: controllers,
  8242. futureParentElement: futureParentElement
  8243. });
  8244. }
  8245. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  8246. // so that they are available inside the `controllersBoundTransclude` function
  8247. var boundSlots = boundTranscludeFn.$$slots = createMap();
  8248. for (var slotName in transcludeFn.$$slots) {
  8249. if (transcludeFn.$$slots[slotName]) {
  8250. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  8251. } else {
  8252. boundSlots[slotName] = null;
  8253. }
  8254. }
  8255. return boundTranscludeFn;
  8256. }
  8257. /**
  8258. * Looks for directives on the given node and adds them to the directive collection which is
  8259. * sorted.
  8260. *
  8261. * @param node Node to search.
  8262. * @param directives An array to which the directives are added to. This array is sorted before
  8263. * the function returns.
  8264. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  8265. * @param {number=} maxPriority Max directive priority.
  8266. */
  8267. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8268. var nodeType = node.nodeType,
  8269. attrsMap = attrs.$attr,
  8270. match,
  8271. nodeName,
  8272. className;
  8273. switch (nodeType) {
  8274. case NODE_TYPE_ELEMENT: /* Element */
  8275. nodeName = nodeName_(node);
  8276. // use the node name: <directive>
  8277. addDirective(directives,
  8278. directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
  8279. // iterate over the attributes
  8280. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  8281. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  8282. var attrStartName = false;
  8283. var attrEndName = false;
  8284. attr = nAttrs[j];
  8285. name = attr.name;
  8286. value = attr.value;
  8287. // support ngAttr attribute binding
  8288. ngAttrName = directiveNormalize(name);
  8289. isNgAttr = NG_ATTR_BINDING.test(ngAttrName);
  8290. if (isNgAttr) {
  8291. name = name.replace(PREFIX_REGEXP, '')
  8292. .substr(8).replace(/_(.)/g, function(match, letter) {
  8293. return letter.toUpperCase();
  8294. });
  8295. }
  8296. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  8297. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  8298. attrStartName = name;
  8299. attrEndName = name.substr(0, name.length - 5) + 'end';
  8300. name = name.substr(0, name.length - 6);
  8301. }
  8302. nName = directiveNormalize(name.toLowerCase());
  8303. attrsMap[nName] = name;
  8304. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  8305. attrs[nName] = value;
  8306. if (getBooleanAttrName(node, nName)) {
  8307. attrs[nName] = true; // presence means true
  8308. }
  8309. }
  8310. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  8311. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  8312. attrEndName);
  8313. }
  8314. if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {
  8315. // Hidden input elements can have strange behaviour when navigating back to the page
  8316. // This tells the browser not to try to cache and reinstate previous values
  8317. node.setAttribute('autocomplete', 'off');
  8318. }
  8319. // use class as directive
  8320. if (!cssClassDirectivesEnabled) break;
  8321. className = node.className;
  8322. if (isObject(className)) {
  8323. // Maybe SVGAnimatedString
  8324. className = className.animVal;
  8325. }
  8326. if (isString(className) && className !== '') {
  8327. while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
  8328. nName = directiveNormalize(match[2]);
  8329. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  8330. attrs[nName] = trim(match[3]);
  8331. }
  8332. className = className.substr(match.index + match[0].length);
  8333. }
  8334. }
  8335. break;
  8336. case NODE_TYPE_TEXT: /* Text Node */
  8337. addTextInterpolateDirective(directives, node.nodeValue);
  8338. break;
  8339. case NODE_TYPE_COMMENT: /* Comment */
  8340. if (!commentDirectivesEnabled) break;
  8341. collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
  8342. break;
  8343. }
  8344. directives.sort(byPriority);
  8345. return directives;
  8346. }
  8347. function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8348. // function created because of performance, try/catch disables
  8349. // the optimization of the whole function #14848
  8350. try {
  8351. var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  8352. if (match) {
  8353. var nName = directiveNormalize(match[1]);
  8354. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  8355. attrs[nName] = trim(match[2]);
  8356. }
  8357. }
  8358. } catch (e) {
  8359. // turns out that under some circumstances IE9 throws errors when one attempts to read
  8360. // comment's node value.
  8361. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  8362. }
  8363. }
  8364. /**
  8365. * Given a node with a directive-start it collects all of the siblings until it finds
  8366. * directive-end.
  8367. * @param node
  8368. * @param attrStart
  8369. * @param attrEnd
  8370. * @returns {*}
  8371. */
  8372. function groupScan(node, attrStart, attrEnd) {
  8373. var nodes = [];
  8374. var depth = 0;
  8375. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  8376. do {
  8377. if (!node) {
  8378. throw $compileMinErr('uterdir',
  8379. 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
  8380. attrStart, attrEnd);
  8381. }
  8382. if (node.nodeType === NODE_TYPE_ELEMENT) {
  8383. if (node.hasAttribute(attrStart)) depth++;
  8384. if (node.hasAttribute(attrEnd)) depth--;
  8385. }
  8386. nodes.push(node);
  8387. node = node.nextSibling;
  8388. } while (depth > 0);
  8389. } else {
  8390. nodes.push(node);
  8391. }
  8392. return jqLite(nodes);
  8393. }
  8394. /**
  8395. * Wrapper for linking function which converts normal linking function into a grouped
  8396. * linking function.
  8397. * @param linkFn
  8398. * @param attrStart
  8399. * @param attrEnd
  8400. * @returns {Function}
  8401. */
  8402. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  8403. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  8404. element = groupScan(element[0], attrStart, attrEnd);
  8405. return linkFn(scope, element, attrs, controllers, transcludeFn);
  8406. };
  8407. }
  8408. /**
  8409. * A function generator that is used to support both eager and lazy compilation
  8410. * linking function.
  8411. * @param eager
  8412. * @param $compileNodes
  8413. * @param transcludeFn
  8414. * @param maxPriority
  8415. * @param ignoreDirective
  8416. * @param previousCompileContext
  8417. * @returns {Function}
  8418. */
  8419. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  8420. var compiled;
  8421. if (eager) {
  8422. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8423. }
  8424. return /** @this */ function lazyCompilation() {
  8425. if (!compiled) {
  8426. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8427. // Null out all of these references in order to make them eligible for garbage collection
  8428. // since this is a potentially long lived closure
  8429. $compileNodes = transcludeFn = previousCompileContext = null;
  8430. }
  8431. return compiled.apply(this, arguments);
  8432. };
  8433. }
  8434. /**
  8435. * Once the directives have been collected, their compile functions are executed. This method
  8436. * is responsible for inlining directive templates as well as terminating the application
  8437. * of the directives if the terminal directive has been reached.
  8438. *
  8439. * @param {Array} directives Array of collected directives to execute their compile function.
  8440. * this needs to be pre-sorted by priority order.
  8441. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  8442. * @param {Object} templateAttrs The shared attribute function
  8443. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8444. * scope argument is auto-generated to the new
  8445. * child of the transcluded parent scope.
  8446. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  8447. * argument has the root jqLite array so that we can replace nodes
  8448. * on it.
  8449. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  8450. * compiling the transclusion.
  8451. * @param {Array.<Function>} preLinkFns
  8452. * @param {Array.<Function>} postLinkFns
  8453. * @param {Object} previousCompileContext Context used for previous compilation of the current
  8454. * node
  8455. * @returns {Function} linkFn
  8456. */
  8457. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  8458. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  8459. previousCompileContext) {
  8460. previousCompileContext = previousCompileContext || {};
  8461. var terminalPriority = -Number.MAX_VALUE,
  8462. newScopeDirective = previousCompileContext.newScopeDirective,
  8463. controllerDirectives = previousCompileContext.controllerDirectives,
  8464. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  8465. templateDirective = previousCompileContext.templateDirective,
  8466. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  8467. hasTranscludeDirective = false,
  8468. hasTemplate = false,
  8469. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  8470. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  8471. directive,
  8472. directiveName,
  8473. $template,
  8474. replaceDirective = originalReplaceDirective,
  8475. childTranscludeFn = transcludeFn,
  8476. linkFn,
  8477. didScanForMultipleTransclusion = false,
  8478. mightHaveMultipleTransclusionError = false,
  8479. directiveValue;
  8480. // executes all directives on the current element
  8481. for (var i = 0, ii = directives.length; i < ii; i++) {
  8482. directive = directives[i];
  8483. var attrStart = directive.$$start;
  8484. var attrEnd = directive.$$end;
  8485. // collect multiblock sections
  8486. if (attrStart) {
  8487. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  8488. }
  8489. $template = undefined;
  8490. if (terminalPriority > directive.priority) {
  8491. break; // prevent further processing of directives
  8492. }
  8493. directiveValue = directive.scope;
  8494. if (directiveValue) {
  8495. // skip the check for directives with async templates, we'll check the derived sync
  8496. // directive when the template arrives
  8497. if (!directive.templateUrl) {
  8498. if (isObject(directiveValue)) {
  8499. // This directive is trying to add an isolated scope.
  8500. // Check that there is no scope of any kind already
  8501. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  8502. directive, $compileNode);
  8503. newIsolateScopeDirective = directive;
  8504. } else {
  8505. // This directive is trying to add a child scope.
  8506. // Check that there is no isolated scope already
  8507. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  8508. $compileNode);
  8509. }
  8510. }
  8511. newScopeDirective = newScopeDirective || directive;
  8512. }
  8513. directiveName = directive.name;
  8514. // If we encounter a condition that can result in transclusion on the directive,
  8515. // then scan ahead in the remaining directives for others that may cause a multiple
  8516. // transclusion error to be thrown during the compilation process. If a matching directive
  8517. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  8518. // compile the `transclude` function rather than doing it lazily in order to throw
  8519. // exceptions at the correct time
  8520. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  8521. || (directive.transclude && !directive.$$tlb))) {
  8522. var candidateDirective;
  8523. for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
  8524. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  8525. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  8526. mightHaveMultipleTransclusionError = true;
  8527. break;
  8528. }
  8529. }
  8530. didScanForMultipleTransclusion = true;
  8531. }
  8532. if (!directive.templateUrl && directive.controller) {
  8533. controllerDirectives = controllerDirectives || createMap();
  8534. assertNoDuplicate('\'' + directiveName + '\' controller',
  8535. controllerDirectives[directiveName], directive, $compileNode);
  8536. controllerDirectives[directiveName] = directive;
  8537. }
  8538. directiveValue = directive.transclude;
  8539. if (directiveValue) {
  8540. hasTranscludeDirective = true;
  8541. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  8542. // This option should only be used by directives that know how to safely handle element transclusion,
  8543. // where the transcluded nodes are added or replaced after linking.
  8544. if (!directive.$$tlb) {
  8545. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  8546. nonTlbTranscludeDirective = directive;
  8547. }
  8548. if (directiveValue === 'element') {
  8549. hasElementTranscludeDirective = true;
  8550. terminalPriority = directive.priority;
  8551. $template = $compileNode;
  8552. $compileNode = templateAttrs.$$element =
  8553. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  8554. compileNode = $compileNode[0];
  8555. replaceWith(jqCollection, sliceArgs($template), compileNode);
  8556. // Support: Chrome < 50
  8557. // https://github.com/angular/angular.js/issues/14041
  8558. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  8559. // in the `replaceWith` function is improperly garbage collected despite still
  8560. // being referenced by the `parentNode` property of all of the child nodes. By adding
  8561. // a reference to the fragment via a different property, we can avoid that incorrect
  8562. // behavior.
  8563. // TODO: remove this line after Chrome 50 has been released
  8564. $template[0].$$parentNode = $template[0].parentNode;
  8565. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  8566. replaceDirective && replaceDirective.name, {
  8567. // Don't pass in:
  8568. // - controllerDirectives - otherwise we'll create duplicates controllers
  8569. // - newIsolateScopeDirective or templateDirective - combining templates with
  8570. // element transclusion doesn't make sense.
  8571. //
  8572. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  8573. // on the same element more than once.
  8574. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8575. });
  8576. } else {
  8577. var slots = createMap();
  8578. if (!isObject(directiveValue)) {
  8579. $template = jqLite(jqLiteClone(compileNode)).contents();
  8580. } else {
  8581. // We have transclusion slots,
  8582. // collect them up, compile them and store their transclusion functions
  8583. $template = [];
  8584. var slotMap = createMap();
  8585. var filledSlots = createMap();
  8586. // Parse the element selectors
  8587. forEach(directiveValue, function(elementSelector, slotName) {
  8588. // If an element selector starts with a ? then it is optional
  8589. var optional = (elementSelector.charAt(0) === '?');
  8590. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  8591. slotMap[elementSelector] = slotName;
  8592. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  8593. // Later when calling boundTransclusion functions with a slot name we only error if the
  8594. // slot is `undefined`
  8595. slots[slotName] = null;
  8596. // filledSlots contains `true` for all slots that are either optional or have been
  8597. // filled. This is used to check that we have not missed any required slots
  8598. filledSlots[slotName] = optional;
  8599. });
  8600. // Add the matching elements into their slot
  8601. forEach($compileNode.contents(), function(node) {
  8602. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  8603. if (slotName) {
  8604. filledSlots[slotName] = true;
  8605. slots[slotName] = slots[slotName] || [];
  8606. slots[slotName].push(node);
  8607. } else {
  8608. $template.push(node);
  8609. }
  8610. });
  8611. // Check for required slots that were not filled
  8612. forEach(filledSlots, function(filled, slotName) {
  8613. if (!filled) {
  8614. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  8615. }
  8616. });
  8617. for (var slotName in slots) {
  8618. if (slots[slotName]) {
  8619. // Only define a transclusion function if the slot was filled
  8620. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  8621. }
  8622. }
  8623. }
  8624. $compileNode.empty(); // clear contents
  8625. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  8626. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  8627. childTranscludeFn.$$slots = slots;
  8628. }
  8629. }
  8630. if (directive.template) {
  8631. hasTemplate = true;
  8632. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8633. templateDirective = directive;
  8634. directiveValue = (isFunction(directive.template))
  8635. ? directive.template($compileNode, templateAttrs)
  8636. : directive.template;
  8637. directiveValue = denormalizeTemplate(directiveValue);
  8638. if (directive.replace) {
  8639. replaceDirective = directive;
  8640. if (jqLiteIsTextNode(directiveValue)) {
  8641. $template = [];
  8642. } else {
  8643. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  8644. }
  8645. compileNode = $template[0];
  8646. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8647. throw $compileMinErr('tplrt',
  8648. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  8649. directiveName, '');
  8650. }
  8651. replaceWith(jqCollection, $compileNode, compileNode);
  8652. var newTemplateAttrs = {$attr: {}};
  8653. // combine directives from the original node and from the template:
  8654. // - take the array of directives for this element
  8655. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  8656. // - collect directives from the template and sort them by priority
  8657. // - combine directives as: processed + template + unprocessed
  8658. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  8659. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  8660. if (newIsolateScopeDirective || newScopeDirective) {
  8661. // The original directive caused the current element to be replaced but this element
  8662. // also needs to have a new scope, so we need to tell the template directives
  8663. // that they would need to get their scope from further up, if they require transclusion
  8664. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  8665. }
  8666. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  8667. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  8668. ii = directives.length;
  8669. } else {
  8670. $compileNode.html(directiveValue);
  8671. }
  8672. }
  8673. if (directive.templateUrl) {
  8674. hasTemplate = true;
  8675. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8676. templateDirective = directive;
  8677. if (directive.replace) {
  8678. replaceDirective = directive;
  8679. }
  8680. // eslint-disable-next-line no-func-assign
  8681. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  8682. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  8683. controllerDirectives: controllerDirectives,
  8684. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  8685. newIsolateScopeDirective: newIsolateScopeDirective,
  8686. templateDirective: templateDirective,
  8687. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8688. });
  8689. ii = directives.length;
  8690. } else if (directive.compile) {
  8691. try {
  8692. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  8693. var context = directive.$$originalDirective || directive;
  8694. if (isFunction(linkFn)) {
  8695. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  8696. } else if (linkFn) {
  8697. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  8698. }
  8699. } catch (e) {
  8700. $exceptionHandler(e, startingTag($compileNode));
  8701. }
  8702. }
  8703. if (directive.terminal) {
  8704. nodeLinkFn.terminal = true;
  8705. terminalPriority = Math.max(terminalPriority, directive.priority);
  8706. }
  8707. }
  8708. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  8709. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  8710. nodeLinkFn.templateOnThisElement = hasTemplate;
  8711. nodeLinkFn.transclude = childTranscludeFn;
  8712. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  8713. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  8714. return nodeLinkFn;
  8715. ////////////////////
  8716. function addLinkFns(pre, post, attrStart, attrEnd) {
  8717. if (pre) {
  8718. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  8719. pre.require = directive.require;
  8720. pre.directiveName = directiveName;
  8721. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8722. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  8723. }
  8724. preLinkFns.push(pre);
  8725. }
  8726. if (post) {
  8727. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  8728. post.require = directive.require;
  8729. post.directiveName = directiveName;
  8730. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8731. post = cloneAndAnnotateFn(post, {isolateScope: true});
  8732. }
  8733. postLinkFns.push(post);
  8734. }
  8735. }
  8736. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8737. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8738. attrs, scopeBindingInfo;
  8739. if (compileNode === linkNode) {
  8740. attrs = templateAttrs;
  8741. $element = templateAttrs.$$element;
  8742. } else {
  8743. $element = jqLite(linkNode);
  8744. attrs = new Attributes($element, templateAttrs);
  8745. }
  8746. controllerScope = scope;
  8747. if (newIsolateScopeDirective) {
  8748. isolateScope = scope.$new(true);
  8749. } else if (newScopeDirective) {
  8750. controllerScope = scope.$parent;
  8751. }
  8752. if (boundTranscludeFn) {
  8753. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8754. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8755. transcludeFn = controllersBoundTransclude;
  8756. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8757. // expose the slots on the `$transclude` function
  8758. transcludeFn.isSlotFilled = function(slotName) {
  8759. return !!boundTranscludeFn.$$slots[slotName];
  8760. };
  8761. }
  8762. if (controllerDirectives) {
  8763. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  8764. }
  8765. if (newIsolateScopeDirective) {
  8766. // Initialize isolate scope bindings for new isolate scope directive.
  8767. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8768. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8769. compile.$$addScopeClass($element, true);
  8770. isolateScope.$$isolateBindings =
  8771. newIsolateScopeDirective.$$isolateBindings;
  8772. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  8773. isolateScope.$$isolateBindings,
  8774. newIsolateScopeDirective);
  8775. if (scopeBindingInfo.removeWatches) {
  8776. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  8777. }
  8778. }
  8779. // Initialize bindToController bindings
  8780. for (var name in elementControllers) {
  8781. var controllerDirective = controllerDirectives[name];
  8782. var controller = elementControllers[name];
  8783. var bindings = controllerDirective.$$bindings.bindToController;
  8784. if (preAssignBindingsEnabled) {
  8785. if (bindings) {
  8786. controller.bindingInfo =
  8787. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8788. } else {
  8789. controller.bindingInfo = {};
  8790. }
  8791. var controllerResult = controller();
  8792. if (controllerResult !== controller.instance) {
  8793. // If the controller constructor has a return value, overwrite the instance
  8794. // from setupControllers
  8795. controller.instance = controllerResult;
  8796. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8797. if (controller.bindingInfo.removeWatches) {
  8798. controller.bindingInfo.removeWatches();
  8799. }
  8800. controller.bindingInfo =
  8801. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8802. }
  8803. } else {
  8804. controller.instance = controller();
  8805. $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
  8806. controller.bindingInfo =
  8807. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8808. }
  8809. }
  8810. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  8811. forEach(controllerDirectives, function(controllerDirective, name) {
  8812. var require = controllerDirective.require;
  8813. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  8814. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  8815. }
  8816. });
  8817. // Handle the init and destroy lifecycle hooks on all controllers that have them
  8818. forEach(elementControllers, function(controller) {
  8819. var controllerInstance = controller.instance;
  8820. if (isFunction(controllerInstance.$onChanges)) {
  8821. try {
  8822. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  8823. } catch (e) {
  8824. $exceptionHandler(e);
  8825. }
  8826. }
  8827. if (isFunction(controllerInstance.$onInit)) {
  8828. try {
  8829. controllerInstance.$onInit();
  8830. } catch (e) {
  8831. $exceptionHandler(e);
  8832. }
  8833. }
  8834. if (isFunction(controllerInstance.$doCheck)) {
  8835. controllerScope.$watch(function() { controllerInstance.$doCheck(); });
  8836. controllerInstance.$doCheck();
  8837. }
  8838. if (isFunction(controllerInstance.$onDestroy)) {
  8839. controllerScope.$on('$destroy', function callOnDestroyHook() {
  8840. controllerInstance.$onDestroy();
  8841. });
  8842. }
  8843. });
  8844. // PRELINKING
  8845. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  8846. linkFn = preLinkFns[i];
  8847. invokeLinkFn(linkFn,
  8848. linkFn.isolateScope ? isolateScope : scope,
  8849. $element,
  8850. attrs,
  8851. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8852. transcludeFn
  8853. );
  8854. }
  8855. // RECURSION
  8856. // We only pass the isolate scope, if the isolate directive has a template,
  8857. // otherwise the child elements do not belong to the isolate directive.
  8858. var scopeToChild = scope;
  8859. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  8860. scopeToChild = isolateScope;
  8861. }
  8862. if (childLinkFn) {
  8863. childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  8864. }
  8865. // POSTLINKING
  8866. for (i = postLinkFns.length - 1; i >= 0; i--) {
  8867. linkFn = postLinkFns[i];
  8868. invokeLinkFn(linkFn,
  8869. linkFn.isolateScope ? isolateScope : scope,
  8870. $element,
  8871. attrs,
  8872. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8873. transcludeFn
  8874. );
  8875. }
  8876. // Trigger $postLink lifecycle hooks
  8877. forEach(elementControllers, function(controller) {
  8878. var controllerInstance = controller.instance;
  8879. if (isFunction(controllerInstance.$postLink)) {
  8880. controllerInstance.$postLink();
  8881. }
  8882. });
  8883. // This is the function that is injected as `$transclude`.
  8884. // Note: all arguments are optional!
  8885. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  8886. var transcludeControllers;
  8887. // No scope passed in:
  8888. if (!isScope(scope)) {
  8889. slotName = futureParentElement;
  8890. futureParentElement = cloneAttachFn;
  8891. cloneAttachFn = scope;
  8892. scope = undefined;
  8893. }
  8894. if (hasElementTranscludeDirective) {
  8895. transcludeControllers = elementControllers;
  8896. }
  8897. if (!futureParentElement) {
  8898. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  8899. }
  8900. if (slotName) {
  8901. // slotTranscludeFn can be one of three things:
  8902. // * a transclude function - a filled slot
  8903. // * `null` - an optional slot that was not filled
  8904. // * `undefined` - a slot that was not declared (i.e. invalid)
  8905. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  8906. if (slotTranscludeFn) {
  8907. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8908. } else if (isUndefined(slotTranscludeFn)) {
  8909. throw $compileMinErr('noslot',
  8910. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  8911. 'Element: {1}',
  8912. slotName, startingTag($element));
  8913. }
  8914. } else {
  8915. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8916. }
  8917. }
  8918. }
  8919. }
  8920. function getControllers(directiveName, require, $element, elementControllers) {
  8921. var value;
  8922. if (isString(require)) {
  8923. var match = require.match(REQUIRE_PREFIX_REGEXP);
  8924. var name = require.substring(match[0].length);
  8925. var inheritType = match[1] || match[3];
  8926. var optional = match[2] === '?';
  8927. //If only parents then start at the parent element
  8928. if (inheritType === '^^') {
  8929. $element = $element.parent();
  8930. //Otherwise attempt getting the controller from elementControllers in case
  8931. //the element is transcluded (and has no data) and to avoid .data if possible
  8932. } else {
  8933. value = elementControllers && elementControllers[name];
  8934. value = value && value.instance;
  8935. }
  8936. if (!value) {
  8937. var dataName = '$' + name + 'Controller';
  8938. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  8939. }
  8940. if (!value && !optional) {
  8941. throw $compileMinErr('ctreq',
  8942. 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
  8943. name, directiveName);
  8944. }
  8945. } else if (isArray(require)) {
  8946. value = [];
  8947. for (var i = 0, ii = require.length; i < ii; i++) {
  8948. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  8949. }
  8950. } else if (isObject(require)) {
  8951. value = {};
  8952. forEach(require, function(controller, property) {
  8953. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  8954. });
  8955. }
  8956. return value || null;
  8957. }
  8958. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  8959. var elementControllers = createMap();
  8960. for (var controllerKey in controllerDirectives) {
  8961. var directive = controllerDirectives[controllerKey];
  8962. var locals = {
  8963. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  8964. $element: $element,
  8965. $attrs: attrs,
  8966. $transclude: transcludeFn
  8967. };
  8968. var controller = directive.controller;
  8969. if (controller === '@') {
  8970. controller = attrs[directive.name];
  8971. }
  8972. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  8973. // For directives with element transclusion the element is a comment.
  8974. // In this case .data will not attach any data.
  8975. // Instead, we save the controllers for the element in a local hash and attach to .data
  8976. // later, once we have the actual element.
  8977. elementControllers[directive.name] = controllerInstance;
  8978. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  8979. }
  8980. return elementControllers;
  8981. }
  8982. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  8983. // or child scope created. For instance:
  8984. // * if the directive has been pulled into a template because another directive with a higher priority
  8985. // asked for element transclusion
  8986. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  8987. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  8988. function markDirectiveScope(directives, isolateScope, newScope) {
  8989. for (var j = 0, jj = directives.length; j < jj; j++) {
  8990. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  8991. }
  8992. }
  8993. /**
  8994. * looks up the directive and decorates it with exception handling and proper parameters. We
  8995. * call this the boundDirective.
  8996. *
  8997. * @param {string} name name of the directive to look up.
  8998. * @param {string} location The directive must be found in specific format.
  8999. * String containing any of theses characters:
  9000. *
  9001. * * `E`: element name
  9002. * * `A': attribute
  9003. * * `C`: class
  9004. * * `M`: comment
  9005. * @returns {boolean} true if directive was added.
  9006. */
  9007. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  9008. endAttrName) {
  9009. if (name === ignoreDirective) return null;
  9010. var match = null;
  9011. if (hasDirectives.hasOwnProperty(name)) {
  9012. for (var directive, directives = $injector.get(name + Suffix),
  9013. i = 0, ii = directives.length; i < ii; i++) {
  9014. directive = directives[i];
  9015. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  9016. directive.restrict.indexOf(location) !== -1) {
  9017. if (startAttrName) {
  9018. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  9019. }
  9020. if (!directive.$$bindings) {
  9021. var bindings = directive.$$bindings =
  9022. parseDirectiveBindings(directive, directive.name);
  9023. if (isObject(bindings.isolateScope)) {
  9024. directive.$$isolateBindings = bindings.isolateScope;
  9025. }
  9026. }
  9027. tDirectives.push(directive);
  9028. match = directive;
  9029. }
  9030. }
  9031. }
  9032. return match;
  9033. }
  9034. /**
  9035. * looks up the directive and returns true if it is a multi-element directive,
  9036. * and therefore requires DOM nodes between -start and -end markers to be grouped
  9037. * together.
  9038. *
  9039. * @param {string} name name of the directive to look up.
  9040. * @returns true if directive was registered as multi-element.
  9041. */
  9042. function directiveIsMultiElement(name) {
  9043. if (hasDirectives.hasOwnProperty(name)) {
  9044. for (var directive, directives = $injector.get(name + Suffix),
  9045. i = 0, ii = directives.length; i < ii; i++) {
  9046. directive = directives[i];
  9047. if (directive.multiElement) {
  9048. return true;
  9049. }
  9050. }
  9051. }
  9052. return false;
  9053. }
  9054. /**
  9055. * When the element is replaced with HTML template then the new attributes
  9056. * on the template need to be merged with the existing attributes in the DOM.
  9057. * The desired effect is to have both of the attributes present.
  9058. *
  9059. * @param {object} dst destination attributes (original DOM)
  9060. * @param {object} src source attributes (from the directive template)
  9061. */
  9062. function mergeTemplateAttributes(dst, src) {
  9063. var srcAttr = src.$attr,
  9064. dstAttr = dst.$attr;
  9065. // reapply the old attributes to the new element
  9066. forEach(dst, function(value, key) {
  9067. if (key.charAt(0) !== '$') {
  9068. if (src[key] && src[key] !== value) {
  9069. if (value.length) {
  9070. value += (key === 'style' ? ';' : ' ') + src[key];
  9071. } else {
  9072. value = src[key];
  9073. }
  9074. }
  9075. dst.$set(key, value, true, srcAttr[key]);
  9076. }
  9077. });
  9078. // copy the new attributes on the old attrs object
  9079. forEach(src, function(value, key) {
  9080. // Check if we already set this attribute in the loop above.
  9081. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  9082. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  9083. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  9084. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  9085. dst[key] = value;
  9086. if (key !== 'class' && key !== 'style') {
  9087. dstAttr[key] = srcAttr[key];
  9088. }
  9089. }
  9090. });
  9091. }
  9092. function compileTemplateUrl(directives, $compileNode, tAttrs,
  9093. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  9094. var linkQueue = [],
  9095. afterTemplateNodeLinkFn,
  9096. afterTemplateChildLinkFn,
  9097. beforeTemplateCompileNode = $compileNode[0],
  9098. origAsyncDirective = directives.shift(),
  9099. derivedSyncDirective = inherit(origAsyncDirective, {
  9100. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  9101. }),
  9102. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  9103. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  9104. : origAsyncDirective.templateUrl,
  9105. templateNamespace = origAsyncDirective.templateNamespace;
  9106. $compileNode.empty();
  9107. $templateRequest(templateUrl)
  9108. .then(function(content) {
  9109. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  9110. content = denormalizeTemplate(content);
  9111. if (origAsyncDirective.replace) {
  9112. if (jqLiteIsTextNode(content)) {
  9113. $template = [];
  9114. } else {
  9115. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  9116. }
  9117. compileNode = $template[0];
  9118. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  9119. throw $compileMinErr('tplrt',
  9120. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  9121. origAsyncDirective.name, templateUrl);
  9122. }
  9123. tempTemplateAttrs = {$attr: {}};
  9124. replaceWith($rootElement, $compileNode, compileNode);
  9125. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  9126. if (isObject(origAsyncDirective.scope)) {
  9127. // the original directive that caused the template to be loaded async required
  9128. // an isolate scope
  9129. markDirectiveScope(templateDirectives, true);
  9130. }
  9131. directives = templateDirectives.concat(directives);
  9132. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  9133. } else {
  9134. compileNode = beforeTemplateCompileNode;
  9135. $compileNode.html(content);
  9136. }
  9137. directives.unshift(derivedSyncDirective);
  9138. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  9139. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  9140. previousCompileContext);
  9141. forEach($rootElement, function(node, i) {
  9142. if (node === compileNode) {
  9143. $rootElement[i] = $compileNode[0];
  9144. }
  9145. });
  9146. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  9147. while (linkQueue.length) {
  9148. var scope = linkQueue.shift(),
  9149. beforeTemplateLinkNode = linkQueue.shift(),
  9150. linkRootElement = linkQueue.shift(),
  9151. boundTranscludeFn = linkQueue.shift(),
  9152. linkNode = $compileNode[0];
  9153. if (scope.$$destroyed) continue;
  9154. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  9155. var oldClasses = beforeTemplateLinkNode.className;
  9156. if (!(previousCompileContext.hasElementTranscludeDirective &&
  9157. origAsyncDirective.replace)) {
  9158. // it was cloned therefore we have to clone as well.
  9159. linkNode = jqLiteClone(compileNode);
  9160. }
  9161. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  9162. // Copy in CSS classes from original node
  9163. safeAddClass(jqLite(linkNode), oldClasses);
  9164. }
  9165. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9166. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9167. } else {
  9168. childBoundTranscludeFn = boundTranscludeFn;
  9169. }
  9170. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  9171. childBoundTranscludeFn);
  9172. }
  9173. linkQueue = null;
  9174. }).catch(function(error) {
  9175. if (error instanceof Error) {
  9176. $exceptionHandler(error);
  9177. }
  9178. });
  9179. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  9180. var childBoundTranscludeFn = boundTranscludeFn;
  9181. if (scope.$$destroyed) return;
  9182. if (linkQueue) {
  9183. linkQueue.push(scope,
  9184. node,
  9185. rootElement,
  9186. childBoundTranscludeFn);
  9187. } else {
  9188. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9189. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9190. }
  9191. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  9192. }
  9193. };
  9194. }
  9195. /**
  9196. * Sorting function for bound directives.
  9197. */
  9198. function byPriority(a, b) {
  9199. var diff = b.priority - a.priority;
  9200. if (diff !== 0) return diff;
  9201. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  9202. return a.index - b.index;
  9203. }
  9204. function assertNoDuplicate(what, previousDirective, directive, element) {
  9205. function wrapModuleNameIfDefined(moduleName) {
  9206. return moduleName ?
  9207. (' (module: ' + moduleName + ')') :
  9208. '';
  9209. }
  9210. if (previousDirective) {
  9211. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  9212. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  9213. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  9214. }
  9215. }
  9216. function addTextInterpolateDirective(directives, text) {
  9217. var interpolateFn = $interpolate(text, true);
  9218. if (interpolateFn) {
  9219. directives.push({
  9220. priority: 0,
  9221. compile: function textInterpolateCompileFn(templateNode) {
  9222. var templateNodeParent = templateNode.parent(),
  9223. hasCompileParent = !!templateNodeParent.length;
  9224. // When transcluding a template that has bindings in the root
  9225. // we don't have a parent and thus need to add the class during linking fn.
  9226. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  9227. return function textInterpolateLinkFn(scope, node) {
  9228. var parent = node.parent();
  9229. if (!hasCompileParent) compile.$$addBindingClass(parent);
  9230. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  9231. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  9232. node[0].nodeValue = value;
  9233. });
  9234. };
  9235. }
  9236. });
  9237. }
  9238. }
  9239. function wrapTemplate(type, template) {
  9240. type = lowercase(type || 'html');
  9241. switch (type) {
  9242. case 'svg':
  9243. case 'math':
  9244. var wrapper = window.document.createElement('div');
  9245. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  9246. return wrapper.childNodes[0].childNodes;
  9247. default:
  9248. return template;
  9249. }
  9250. }
  9251. function getTrustedContext(node, attrNormalizedName) {
  9252. if (attrNormalizedName === 'srcdoc') {
  9253. return $sce.HTML;
  9254. }
  9255. var tag = nodeName_(node);
  9256. // All tags with src attributes require a RESOURCE_URL value, except for
  9257. // img and various html5 media tags.
  9258. if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
  9259. if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) {
  9260. return $sce.RESOURCE_URL;
  9261. }
  9262. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  9263. } else if (attrNormalizedName === 'xlinkHref' ||
  9264. (tag === 'form' && attrNormalizedName === 'action') ||
  9265. // links can be stylesheets or imports, which can run script in the current origin
  9266. (tag === 'link' && attrNormalizedName === 'href')
  9267. ) {
  9268. return $sce.RESOURCE_URL;
  9269. }
  9270. }
  9271. function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {
  9272. var trustedContext = getTrustedContext(node, name);
  9273. var mustHaveExpression = !isNgAttr;
  9274. var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;
  9275. var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
  9276. // no interpolation found -> ignore
  9277. if (!interpolateFn) return;
  9278. if (name === 'multiple' && nodeName_(node) === 'select') {
  9279. throw $compileMinErr('selmulti',
  9280. 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
  9281. startingTag(node));
  9282. }
  9283. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  9284. throw $compileMinErr('nodomevents',
  9285. 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' +
  9286. 'ng- versions (such as ng-click instead of onclick) instead.');
  9287. }
  9288. directives.push({
  9289. priority: 100,
  9290. compile: function() {
  9291. return {
  9292. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  9293. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  9294. // If the attribute has changed since last $interpolate()ed
  9295. var newValue = attr[name];
  9296. if (newValue !== value) {
  9297. // we need to interpolate again since the attribute value has been updated
  9298. // (e.g. by another directive's compile function)
  9299. // ensure unset/empty values make interpolateFn falsy
  9300. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  9301. value = newValue;
  9302. }
  9303. // if attribute was updated so that there is no interpolation going on we don't want to
  9304. // register any observers
  9305. if (!interpolateFn) return;
  9306. // initialize attr object so that it's ready in case we need the value for isolate
  9307. // scope initialization, otherwise the value would not be available from isolate
  9308. // directive's linking fn during linking phase
  9309. attr[name] = interpolateFn(scope);
  9310. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  9311. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  9312. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  9313. //special case for class attribute addition + removal
  9314. //so that class changes can tap into the animation
  9315. //hooks provided by the $animate service. Be sure to
  9316. //skip animations when the first digest occurs (when
  9317. //both the new and the old values are the same) since
  9318. //the CSS classes are the non-interpolated values
  9319. if (name === 'class' && newValue !== oldValue) {
  9320. attr.$updateClass(newValue, oldValue);
  9321. } else {
  9322. attr.$set(name, newValue);
  9323. }
  9324. });
  9325. }
  9326. };
  9327. }
  9328. });
  9329. }
  9330. /**
  9331. * This is a special jqLite.replaceWith, which can replace items which
  9332. * have no parents, provided that the containing jqLite collection is provided.
  9333. *
  9334. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  9335. * in the root of the tree.
  9336. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  9337. * the shell, but replace its DOM node reference.
  9338. * @param {Node} newNode The new DOM node.
  9339. */
  9340. function replaceWith($rootElement, elementsToRemove, newNode) {
  9341. var firstElementToRemove = elementsToRemove[0],
  9342. removeCount = elementsToRemove.length,
  9343. parent = firstElementToRemove.parentNode,
  9344. i, ii;
  9345. if ($rootElement) {
  9346. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  9347. if ($rootElement[i] === firstElementToRemove) {
  9348. $rootElement[i++] = newNode;
  9349. for (var j = i, j2 = j + removeCount - 1,
  9350. jj = $rootElement.length;
  9351. j < jj; j++, j2++) {
  9352. if (j2 < jj) {
  9353. $rootElement[j] = $rootElement[j2];
  9354. } else {
  9355. delete $rootElement[j];
  9356. }
  9357. }
  9358. $rootElement.length -= removeCount - 1;
  9359. // If the replaced element is also the jQuery .context then replace it
  9360. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  9361. // http://api.jquery.com/context/
  9362. if ($rootElement.context === firstElementToRemove) {
  9363. $rootElement.context = newNode;
  9364. }
  9365. break;
  9366. }
  9367. }
  9368. }
  9369. if (parent) {
  9370. parent.replaceChild(newNode, firstElementToRemove);
  9371. }
  9372. // Append all the `elementsToRemove` to a fragment. This will...
  9373. // - remove them from the DOM
  9374. // - allow them to still be traversed with .nextSibling
  9375. // - allow a single fragment.qSA to fetch all elements being removed
  9376. var fragment = window.document.createDocumentFragment();
  9377. for (i = 0; i < removeCount; i++) {
  9378. fragment.appendChild(elementsToRemove[i]);
  9379. }
  9380. if (jqLite.hasData(firstElementToRemove)) {
  9381. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  9382. // data here because there's no public interface in jQuery to do that and copying over
  9383. // event listeners (which is the main use of private data) wouldn't work anyway.
  9384. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  9385. // Remove $destroy event listeners from `firstElementToRemove`
  9386. jqLite(firstElementToRemove).off('$destroy');
  9387. }
  9388. // Cleanup any data/listeners on the elements and children.
  9389. // This includes invoking the $destroy event on any elements with listeners.
  9390. jqLite.cleanData(fragment.querySelectorAll('*'));
  9391. // Update the jqLite collection to only contain the `newNode`
  9392. for (i = 1; i < removeCount; i++) {
  9393. delete elementsToRemove[i];
  9394. }
  9395. elementsToRemove[0] = newNode;
  9396. elementsToRemove.length = 1;
  9397. }
  9398. function cloneAndAnnotateFn(fn, annotation) {
  9399. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  9400. }
  9401. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  9402. try {
  9403. linkFn(scope, $element, attrs, controllers, transcludeFn);
  9404. } catch (e) {
  9405. $exceptionHandler(e, startingTag($element));
  9406. }
  9407. }
  9408. // Set up $watches for isolate scope and controller bindings.
  9409. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  9410. var removeWatchCollection = [];
  9411. var initialChanges = {};
  9412. var changes;
  9413. forEach(bindings, function initializeBinding(definition, scopeName) {
  9414. var attrName = definition.attrName,
  9415. optional = definition.optional,
  9416. mode = definition.mode, // @, =, <, or &
  9417. lastValue,
  9418. parentGet, parentSet, compare, removeWatch;
  9419. switch (mode) {
  9420. case '@':
  9421. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  9422. destination[scopeName] = attrs[attrName] = undefined;
  9423. }
  9424. removeWatch = attrs.$observe(attrName, function(value) {
  9425. if (isString(value) || isBoolean(value)) {
  9426. var oldValue = destination[scopeName];
  9427. recordChanges(scopeName, value, oldValue);
  9428. destination[scopeName] = value;
  9429. }
  9430. });
  9431. attrs.$$observers[attrName].$$scope = scope;
  9432. lastValue = attrs[attrName];
  9433. if (isString(lastValue)) {
  9434. // If the attribute has been provided then we trigger an interpolation to ensure
  9435. // the value is there for use in the link fn
  9436. destination[scopeName] = $interpolate(lastValue)(scope);
  9437. } else if (isBoolean(lastValue)) {
  9438. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  9439. // the value to boolean rather than a string, so we special case this situation
  9440. destination[scopeName] = lastValue;
  9441. }
  9442. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9443. removeWatchCollection.push(removeWatch);
  9444. break;
  9445. case '=':
  9446. if (!hasOwnProperty.call(attrs, attrName)) {
  9447. if (optional) break;
  9448. attrs[attrName] = undefined;
  9449. }
  9450. if (optional && !attrs[attrName]) break;
  9451. parentGet = $parse(attrs[attrName]);
  9452. if (parentGet.literal) {
  9453. compare = equals;
  9454. } else {
  9455. // eslint-disable-next-line no-self-compare
  9456. compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
  9457. }
  9458. parentSet = parentGet.assign || function() {
  9459. // reset the change, or we will throw this exception on every $digest
  9460. lastValue = destination[scopeName] = parentGet(scope);
  9461. throw $compileMinErr('nonassign',
  9462. 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
  9463. attrs[attrName], attrName, directive.name);
  9464. };
  9465. lastValue = destination[scopeName] = parentGet(scope);
  9466. var parentValueWatch = function parentValueWatch(parentValue) {
  9467. if (!compare(parentValue, destination[scopeName])) {
  9468. // we are out of sync and need to copy
  9469. if (!compare(parentValue, lastValue)) {
  9470. // parent changed and it has precedence
  9471. destination[scopeName] = parentValue;
  9472. } else {
  9473. // if the parent can be assigned then do so
  9474. parentSet(scope, parentValue = destination[scopeName]);
  9475. }
  9476. }
  9477. lastValue = parentValue;
  9478. return lastValue;
  9479. };
  9480. parentValueWatch.$stateful = true;
  9481. if (definition.collection) {
  9482. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  9483. } else {
  9484. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  9485. }
  9486. removeWatchCollection.push(removeWatch);
  9487. break;
  9488. case '<':
  9489. if (!hasOwnProperty.call(attrs, attrName)) {
  9490. if (optional) break;
  9491. attrs[attrName] = undefined;
  9492. }
  9493. if (optional && !attrs[attrName]) break;
  9494. parentGet = $parse(attrs[attrName]);
  9495. var deepWatch = parentGet.literal;
  9496. var initialValue = destination[scopeName] = parentGet(scope);
  9497. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9498. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
  9499. if (oldValue === newValue) {
  9500. if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) {
  9501. return;
  9502. }
  9503. oldValue = initialValue;
  9504. }
  9505. recordChanges(scopeName, newValue, oldValue);
  9506. destination[scopeName] = newValue;
  9507. }, deepWatch);
  9508. removeWatchCollection.push(removeWatch);
  9509. break;
  9510. case '&':
  9511. // Don't assign Object.prototype method to scope
  9512. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  9513. // Don't assign noop to destination if expression is not valid
  9514. if (parentGet === noop && optional) break;
  9515. destination[scopeName] = function(locals) {
  9516. return parentGet(scope, locals);
  9517. };
  9518. break;
  9519. }
  9520. });
  9521. function recordChanges(key, currentValue, previousValue) {
  9522. if (isFunction(destination.$onChanges) && currentValue !== previousValue &&
  9523. // eslint-disable-next-line no-self-compare
  9524. (currentValue === currentValue || previousValue === previousValue)) {
  9525. // If we have not already scheduled the top level onChangesQueue handler then do so now
  9526. if (!onChangesQueue) {
  9527. scope.$$postDigest(flushOnChangesQueue);
  9528. onChangesQueue = [];
  9529. }
  9530. // If we have not already queued a trigger of onChanges for this controller then do so now
  9531. if (!changes) {
  9532. changes = {};
  9533. onChangesQueue.push(triggerOnChangesHook);
  9534. }
  9535. // If the has been a change on this property already then we need to reuse the previous value
  9536. if (changes[key]) {
  9537. previousValue = changes[key].previousValue;
  9538. }
  9539. // Store this change
  9540. changes[key] = new SimpleChange(previousValue, currentValue);
  9541. }
  9542. }
  9543. function triggerOnChangesHook() {
  9544. destination.$onChanges(changes);
  9545. // Now clear the changes so that we schedule onChanges when more changes arrive
  9546. changes = undefined;
  9547. }
  9548. return {
  9549. initialChanges: initialChanges,
  9550. removeWatches: removeWatchCollection.length && function removeWatches() {
  9551. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  9552. removeWatchCollection[i]();
  9553. }
  9554. }
  9555. };
  9556. }
  9557. }];
  9558. }
  9559. function SimpleChange(previous, current) {
  9560. this.previousValue = previous;
  9561. this.currentValue = current;
  9562. }
  9563. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  9564. var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
  9565. var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
  9566. /**
  9567. * Converts all accepted directives format into proper directive name.
  9568. * @param name Name to normalize
  9569. */
  9570. function directiveNormalize(name) {
  9571. return name
  9572. .replace(PREFIX_REGEXP, '')
  9573. .replace(SPECIAL_CHARS_REGEXP, fnCamelCaseReplace);
  9574. }
  9575. /**
  9576. * @ngdoc type
  9577. * @name $compile.directive.Attributes
  9578. *
  9579. * @description
  9580. * A shared object between directive compile / linking functions which contains normalized DOM
  9581. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  9582. * needed since all of these are treated as equivalent in Angular:
  9583. *
  9584. * ```
  9585. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  9586. * ```
  9587. */
  9588. /**
  9589. * @ngdoc property
  9590. * @name $compile.directive.Attributes#$attr
  9591. *
  9592. * @description
  9593. * A map of DOM element attribute names to the normalized name. This is
  9594. * needed to do reverse lookup from normalized name back to actual name.
  9595. */
  9596. /**
  9597. * @ngdoc method
  9598. * @name $compile.directive.Attributes#$set
  9599. * @kind function
  9600. *
  9601. * @description
  9602. * Set DOM element attribute value.
  9603. *
  9604. *
  9605. * @param {string} name Normalized element attribute name of the property to modify. The name is
  9606. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  9607. * property to the original name.
  9608. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  9609. */
  9610. /**
  9611. * Closure compiler type information
  9612. */
  9613. function nodesetLinkingFn(
  9614. /* angular.Scope */ scope,
  9615. /* NodeList */ nodeList,
  9616. /* Element */ rootElement,
  9617. /* function(Function) */ boundTranscludeFn
  9618. ) {}
  9619. function directiveLinkingFn(
  9620. /* nodesetLinkingFn */ nodesetLinkingFn,
  9621. /* angular.Scope */ scope,
  9622. /* Node */ node,
  9623. /* Element */ rootElement,
  9624. /* function(Function) */ boundTranscludeFn
  9625. ) {}
  9626. function tokenDifference(str1, str2) {
  9627. var values = '',
  9628. tokens1 = str1.split(/\s+/),
  9629. tokens2 = str2.split(/\s+/);
  9630. outer:
  9631. for (var i = 0; i < tokens1.length; i++) {
  9632. var token = tokens1[i];
  9633. for (var j = 0; j < tokens2.length; j++) {
  9634. if (token === tokens2[j]) continue outer;
  9635. }
  9636. values += (values.length > 0 ? ' ' : '') + token;
  9637. }
  9638. return values;
  9639. }
  9640. function removeComments(jqNodes) {
  9641. jqNodes = jqLite(jqNodes);
  9642. var i = jqNodes.length;
  9643. if (i <= 1) {
  9644. return jqNodes;
  9645. }
  9646. while (i--) {
  9647. var node = jqNodes[i];
  9648. if (node.nodeType === NODE_TYPE_COMMENT ||
  9649. (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {
  9650. splice.call(jqNodes, i, 1);
  9651. }
  9652. }
  9653. return jqNodes;
  9654. }
  9655. var $controllerMinErr = minErr('$controller');
  9656. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  9657. function identifierForController(controller, ident) {
  9658. if (ident && isString(ident)) return ident;
  9659. if (isString(controller)) {
  9660. var match = CNTRL_REG.exec(controller);
  9661. if (match) return match[3];
  9662. }
  9663. }
  9664. /**
  9665. * @ngdoc provider
  9666. * @name $controllerProvider
  9667. * @this
  9668. *
  9669. * @description
  9670. * The {@link ng.$controller $controller service} is used by Angular to create new
  9671. * controllers.
  9672. *
  9673. * This provider allows controller registration via the
  9674. * {@link ng.$controllerProvider#register register} method.
  9675. */
  9676. function $ControllerProvider() {
  9677. var controllers = {},
  9678. globals = false;
  9679. /**
  9680. * @ngdoc method
  9681. * @name $controllerProvider#has
  9682. * @param {string} name Controller name to check.
  9683. */
  9684. this.has = function(name) {
  9685. return controllers.hasOwnProperty(name);
  9686. };
  9687. /**
  9688. * @ngdoc method
  9689. * @name $controllerProvider#register
  9690. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  9691. * the names and the values are the constructors.
  9692. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  9693. * annotations in the array notation).
  9694. */
  9695. this.register = function(name, constructor) {
  9696. assertNotHasOwnProperty(name, 'controller');
  9697. if (isObject(name)) {
  9698. extend(controllers, name);
  9699. } else {
  9700. controllers[name] = constructor;
  9701. }
  9702. };
  9703. /**
  9704. * @ngdoc method
  9705. * @name $controllerProvider#allowGlobals
  9706. * @description If called, allows `$controller` to find controller constructors on `window`
  9707. *
  9708. * @deprecated
  9709. * sinceVersion="v1.3.0"
  9710. * removeVersion="v1.7.0"
  9711. * This method of finding controllers has been deprecated.
  9712. */
  9713. this.allowGlobals = function() {
  9714. globals = true;
  9715. };
  9716. this.$get = ['$injector', '$window', function($injector, $window) {
  9717. /**
  9718. * @ngdoc service
  9719. * @name $controller
  9720. * @requires $injector
  9721. *
  9722. * @param {Function|string} constructor If called with a function then it's considered to be the
  9723. * controller constructor function. Otherwise it's considered to be a string which is used
  9724. * to retrieve the controller constructor using the following steps:
  9725. *
  9726. * * check if a controller with given name is registered via `$controllerProvider`
  9727. * * check if evaluating the string on the current scope returns a constructor
  9728. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  9729. * `window` object (deprecated, not recommended)
  9730. *
  9731. * The string can use the `controller as property` syntax, where the controller instance is published
  9732. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  9733. * to work correctly.
  9734. *
  9735. * @param {Object} locals Injection locals for Controller.
  9736. * @return {Object} Instance of given controller.
  9737. *
  9738. * @description
  9739. * `$controller` service is responsible for instantiating controllers.
  9740. *
  9741. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  9742. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  9743. */
  9744. return function $controller(expression, locals, later, ident) {
  9745. // PRIVATE API:
  9746. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  9747. // If true, $controller will allocate the object with the correct
  9748. // prototype chain, but will not invoke the controller until a returned
  9749. // callback is invoked.
  9750. // param `ident` --- An optional label which overrides the label parsed from the controller
  9751. // expression, if any.
  9752. var instance, match, constructor, identifier;
  9753. later = later === true;
  9754. if (ident && isString(ident)) {
  9755. identifier = ident;
  9756. }
  9757. if (isString(expression)) {
  9758. match = expression.match(CNTRL_REG);
  9759. if (!match) {
  9760. throw $controllerMinErr('ctrlfmt',
  9761. 'Badly formed controller string \'{0}\'. ' +
  9762. 'Must match `__name__ as __id__` or `__name__`.', expression);
  9763. }
  9764. constructor = match[1];
  9765. identifier = identifier || match[3];
  9766. expression = controllers.hasOwnProperty(constructor)
  9767. ? controllers[constructor]
  9768. : getter(locals.$scope, constructor, true) ||
  9769. (globals ? getter($window, constructor, true) : undefined);
  9770. if (!expression) {
  9771. throw $controllerMinErr('ctrlreg',
  9772. 'The controller with the name \'{0}\' is not registered.', constructor);
  9773. }
  9774. assertArgFn(expression, constructor, true);
  9775. }
  9776. if (later) {
  9777. // Instantiate controller later:
  9778. // This machinery is used to create an instance of the object before calling the
  9779. // controller's constructor itself.
  9780. //
  9781. // This allows properties to be added to the controller before the constructor is
  9782. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  9783. //
  9784. // This feature is not intended for use by applications, and is thus not documented
  9785. // publicly.
  9786. // Object creation: http://jsperf.com/create-constructor/2
  9787. var controllerPrototype = (isArray(expression) ?
  9788. expression[expression.length - 1] : expression).prototype;
  9789. instance = Object.create(controllerPrototype || null);
  9790. if (identifier) {
  9791. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9792. }
  9793. return extend(function $controllerInit() {
  9794. var result = $injector.invoke(expression, instance, locals, constructor);
  9795. if (result !== instance && (isObject(result) || isFunction(result))) {
  9796. instance = result;
  9797. if (identifier) {
  9798. // If result changed, re-assign controllerAs value to scope.
  9799. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9800. }
  9801. }
  9802. return instance;
  9803. }, {
  9804. instance: instance,
  9805. identifier: identifier
  9806. });
  9807. }
  9808. instance = $injector.instantiate(expression, locals, constructor);
  9809. if (identifier) {
  9810. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9811. }
  9812. return instance;
  9813. };
  9814. function addIdentifier(locals, identifier, instance, name) {
  9815. if (!(locals && isObject(locals.$scope))) {
  9816. throw minErr('$controller')('noscp',
  9817. 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
  9818. name, identifier);
  9819. }
  9820. locals.$scope[identifier] = instance;
  9821. }
  9822. }];
  9823. }
  9824. /**
  9825. * @ngdoc service
  9826. * @name $document
  9827. * @requires $window
  9828. * @this
  9829. *
  9830. * @description
  9831. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  9832. *
  9833. * @example
  9834. <example module="documentExample" name="document">
  9835. <file name="index.html">
  9836. <div ng-controller="ExampleController">
  9837. <p>$document title: <b ng-bind="title"></b></p>
  9838. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  9839. </div>
  9840. </file>
  9841. <file name="script.js">
  9842. angular.module('documentExample', [])
  9843. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  9844. $scope.title = $document[0].title;
  9845. $scope.windowTitle = angular.element(window.document)[0].title;
  9846. }]);
  9847. </file>
  9848. </example>
  9849. */
  9850. function $DocumentProvider() {
  9851. this.$get = ['$window', function(window) {
  9852. return jqLite(window.document);
  9853. }];
  9854. }
  9855. /**
  9856. * @private
  9857. * @this
  9858. * Listens for document visibility change and makes the current status accessible.
  9859. */
  9860. function $$IsDocumentHiddenProvider() {
  9861. this.$get = ['$document', '$rootScope', function($document, $rootScope) {
  9862. var doc = $document[0];
  9863. var hidden = doc && doc.hidden;
  9864. $document.on('visibilitychange', changeListener);
  9865. $rootScope.$on('$destroy', function() {
  9866. $document.off('visibilitychange', changeListener);
  9867. });
  9868. function changeListener() {
  9869. hidden = doc.hidden;
  9870. }
  9871. return function() {
  9872. return hidden;
  9873. };
  9874. }];
  9875. }
  9876. /**
  9877. * @ngdoc service
  9878. * @name $exceptionHandler
  9879. * @requires ng.$log
  9880. * @this
  9881. *
  9882. * @description
  9883. * Any uncaught exception in angular expressions is delegated to this service.
  9884. * The default implementation simply delegates to `$log.error` which logs it into
  9885. * the browser console.
  9886. *
  9887. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  9888. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  9889. *
  9890. * ## Example:
  9891. *
  9892. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  9893. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  9894. * of `$log.error()`.
  9895. *
  9896. * ```js
  9897. * angular.
  9898. * module('exceptionOverwrite', []).
  9899. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  9900. * return function myExceptionHandler(exception, cause) {
  9901. * logErrorsToBackend(exception, cause);
  9902. * $log.warn(exception, cause);
  9903. * };
  9904. * }]);
  9905. * ```
  9906. *
  9907. * <hr />
  9908. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  9909. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  9910. * (unless executed during a digest).
  9911. *
  9912. * If you wish, you can manually delegate exceptions, e.g.
  9913. * `try { ... } catch(e) { $exceptionHandler(e); }`
  9914. *
  9915. * @param {Error} exception Exception associated with the error.
  9916. * @param {string=} cause Optional information about the context in which
  9917. * the error was thrown.
  9918. *
  9919. */
  9920. function $ExceptionHandlerProvider() {
  9921. this.$get = ['$log', function($log) {
  9922. return function(exception, cause) {
  9923. $log.error.apply($log, arguments);
  9924. };
  9925. }];
  9926. }
  9927. var $$ForceReflowProvider = /** @this */ function() {
  9928. this.$get = ['$document', function($document) {
  9929. return function(domNode) {
  9930. //the line below will force the browser to perform a repaint so
  9931. //that all the animated elements within the animation frame will
  9932. //be properly updated and drawn on screen. This is required to
  9933. //ensure that the preparation animation is properly flushed so that
  9934. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  9935. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  9936. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  9937. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  9938. if (domNode) {
  9939. if (!domNode.nodeType && domNode instanceof jqLite) {
  9940. domNode = domNode[0];
  9941. }
  9942. } else {
  9943. domNode = $document[0].body;
  9944. }
  9945. return domNode.offsetWidth + 1;
  9946. };
  9947. }];
  9948. };
  9949. var APPLICATION_JSON = 'application/json';
  9950. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  9951. var JSON_START = /^\[|^\{(?!\{)/;
  9952. var JSON_ENDS = {
  9953. '[': /]$/,
  9954. '{': /}$/
  9955. };
  9956. var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/;
  9957. var $httpMinErr = minErr('$http');
  9958. function serializeValue(v) {
  9959. if (isObject(v)) {
  9960. return isDate(v) ? v.toISOString() : toJson(v);
  9961. }
  9962. return v;
  9963. }
  9964. /** @this */
  9965. function $HttpParamSerializerProvider() {
  9966. /**
  9967. * @ngdoc service
  9968. * @name $httpParamSerializer
  9969. * @description
  9970. *
  9971. * Default {@link $http `$http`} params serializer that converts objects to strings
  9972. * according to the following rules:
  9973. *
  9974. * * `{'foo': 'bar'}` results in `foo=bar`
  9975. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  9976. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  9977. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
  9978. *
  9979. * Note that serializer will sort the request parameters alphabetically.
  9980. * */
  9981. this.$get = function() {
  9982. return function ngParamSerializer(params) {
  9983. if (!params) return '';
  9984. var parts = [];
  9985. forEachSorted(params, function(value, key) {
  9986. if (value === null || isUndefined(value)) return;
  9987. if (isArray(value)) {
  9988. forEach(value, function(v) {
  9989. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  9990. });
  9991. } else {
  9992. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  9993. }
  9994. });
  9995. return parts.join('&');
  9996. };
  9997. };
  9998. }
  9999. /** @this */
  10000. function $HttpParamSerializerJQLikeProvider() {
  10001. /**
  10002. * @ngdoc service
  10003. * @name $httpParamSerializerJQLike
  10004. *
  10005. * @description
  10006. *
  10007. * Alternative {@link $http `$http`} params serializer that follows
  10008. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  10009. * The serializer will also sort the params alphabetically.
  10010. *
  10011. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  10012. *
  10013. * ```js
  10014. * $http({
  10015. * url: myUrl,
  10016. * method: 'GET',
  10017. * params: myParams,
  10018. * paramSerializer: '$httpParamSerializerJQLike'
  10019. * });
  10020. * ```
  10021. *
  10022. * It is also possible to set it as the default `paramSerializer` in the
  10023. * {@link $httpProvider#defaults `$httpProvider`}.
  10024. *
  10025. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  10026. * form data for submission:
  10027. *
  10028. * ```js
  10029. * .controller(function($http, $httpParamSerializerJQLike) {
  10030. * //...
  10031. *
  10032. * $http({
  10033. * url: myUrl,
  10034. * method: 'POST',
  10035. * data: $httpParamSerializerJQLike(myData),
  10036. * headers: {
  10037. * 'Content-Type': 'application/x-www-form-urlencoded'
  10038. * }
  10039. * });
  10040. *
  10041. * });
  10042. * ```
  10043. *
  10044. * */
  10045. this.$get = function() {
  10046. return function jQueryLikeParamSerializer(params) {
  10047. if (!params) return '';
  10048. var parts = [];
  10049. serialize(params, '', true);
  10050. return parts.join('&');
  10051. function serialize(toSerialize, prefix, topLevel) {
  10052. if (toSerialize === null || isUndefined(toSerialize)) return;
  10053. if (isArray(toSerialize)) {
  10054. forEach(toSerialize, function(value, index) {
  10055. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  10056. });
  10057. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  10058. forEachSorted(toSerialize, function(value, key) {
  10059. serialize(value, prefix +
  10060. (topLevel ? '' : '[') +
  10061. key +
  10062. (topLevel ? '' : ']'));
  10063. });
  10064. } else {
  10065. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  10066. }
  10067. }
  10068. };
  10069. };
  10070. }
  10071. function defaultHttpResponseTransform(data, headers) {
  10072. if (isString(data)) {
  10073. // Strip json vulnerability protection prefix and trim whitespace
  10074. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  10075. if (tempData) {
  10076. var contentType = headers('Content-Type');
  10077. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  10078. data = fromJson(tempData);
  10079. }
  10080. }
  10081. }
  10082. return data;
  10083. }
  10084. function isJsonLike(str) {
  10085. var jsonStart = str.match(JSON_START);
  10086. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  10087. }
  10088. /**
  10089. * Parse headers into key value object
  10090. *
  10091. * @param {string} headers Raw headers as a string
  10092. * @returns {Object} Parsed headers as key value object
  10093. */
  10094. function parseHeaders(headers) {
  10095. var parsed = createMap(), i;
  10096. function fillInParsed(key, val) {
  10097. if (key) {
  10098. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  10099. }
  10100. }
  10101. if (isString(headers)) {
  10102. forEach(headers.split('\n'), function(line) {
  10103. i = line.indexOf(':');
  10104. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  10105. });
  10106. } else if (isObject(headers)) {
  10107. forEach(headers, function(headerVal, headerKey) {
  10108. fillInParsed(lowercase(headerKey), trim(headerVal));
  10109. });
  10110. }
  10111. return parsed;
  10112. }
  10113. /**
  10114. * Returns a function that provides access to parsed headers.
  10115. *
  10116. * Headers are lazy parsed when first requested.
  10117. * @see parseHeaders
  10118. *
  10119. * @param {(string|Object)} headers Headers to provide access to.
  10120. * @returns {function(string=)} Returns a getter function which if called with:
  10121. *
  10122. * - if called with an argument returns a single header value or null
  10123. * - if called with no arguments returns an object containing all headers.
  10124. */
  10125. function headersGetter(headers) {
  10126. var headersObj;
  10127. return function(name) {
  10128. if (!headersObj) headersObj = parseHeaders(headers);
  10129. if (name) {
  10130. var value = headersObj[lowercase(name)];
  10131. if (value === undefined) {
  10132. value = null;
  10133. }
  10134. return value;
  10135. }
  10136. return headersObj;
  10137. };
  10138. }
  10139. /**
  10140. * Chain all given functions
  10141. *
  10142. * This function is used for both request and response transforming
  10143. *
  10144. * @param {*} data Data to transform.
  10145. * @param {function(string=)} headers HTTP headers getter fn.
  10146. * @param {number} status HTTP status code of the response.
  10147. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  10148. * @returns {*} Transformed data.
  10149. */
  10150. function transformData(data, headers, status, fns) {
  10151. if (isFunction(fns)) {
  10152. return fns(data, headers, status);
  10153. }
  10154. forEach(fns, function(fn) {
  10155. data = fn(data, headers, status);
  10156. });
  10157. return data;
  10158. }
  10159. function isSuccess(status) {
  10160. return 200 <= status && status < 300;
  10161. }
  10162. /**
  10163. * @ngdoc provider
  10164. * @name $httpProvider
  10165. * @this
  10166. *
  10167. * @description
  10168. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  10169. * */
  10170. function $HttpProvider() {
  10171. /**
  10172. * @ngdoc property
  10173. * @name $httpProvider#defaults
  10174. * @description
  10175. *
  10176. * Object containing default values for all {@link ng.$http $http} requests.
  10177. *
  10178. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  10179. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  10180. * by default. See {@link $http#caching $http Caching} for more information.
  10181. *
  10182. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  10183. * Defaults value is `'XSRF-TOKEN'`.
  10184. *
  10185. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  10186. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  10187. *
  10188. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  10189. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  10190. * setting default headers.
  10191. * - **`defaults.headers.common`**
  10192. * - **`defaults.headers.post`**
  10193. * - **`defaults.headers.put`**
  10194. * - **`defaults.headers.patch`**
  10195. *
  10196. *
  10197. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  10198. * used to the prepare string representation of request parameters (specified as an object).
  10199. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  10200. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  10201. *
  10202. * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the
  10203. * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the
  10204. * {@link $jsonpCallbacks} service. Defaults to `'callback'`.
  10205. *
  10206. **/
  10207. var defaults = this.defaults = {
  10208. // transform incoming response data
  10209. transformResponse: [defaultHttpResponseTransform],
  10210. // transform outgoing request data
  10211. transformRequest: [function(d) {
  10212. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  10213. }],
  10214. // default headers
  10215. headers: {
  10216. common: {
  10217. 'Accept': 'application/json, text/plain, */*'
  10218. },
  10219. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10220. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10221. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  10222. },
  10223. xsrfCookieName: 'XSRF-TOKEN',
  10224. xsrfHeaderName: 'X-XSRF-TOKEN',
  10225. paramSerializer: '$httpParamSerializer',
  10226. jsonpCallbackParam: 'callback'
  10227. };
  10228. var useApplyAsync = false;
  10229. /**
  10230. * @ngdoc method
  10231. * @name $httpProvider#useApplyAsync
  10232. * @description
  10233. *
  10234. * Configure $http service to combine processing of multiple http responses received at around
  10235. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  10236. * significant performance improvement for bigger applications that make many HTTP requests
  10237. * concurrently (common during application bootstrap).
  10238. *
  10239. * Defaults to false. If no value is specified, returns the current configured value.
  10240. *
  10241. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  10242. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  10243. * to load and share the same digest cycle.
  10244. *
  10245. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  10246. * otherwise, returns the current configured value.
  10247. **/
  10248. this.useApplyAsync = function(value) {
  10249. if (isDefined(value)) {
  10250. useApplyAsync = !!value;
  10251. return this;
  10252. }
  10253. return useApplyAsync;
  10254. };
  10255. /**
  10256. * @ngdoc property
  10257. * @name $httpProvider#interceptors
  10258. * @description
  10259. *
  10260. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  10261. * pre-processing of request or postprocessing of responses.
  10262. *
  10263. * These service factories are ordered by request, i.e. they are applied in the same order as the
  10264. * array, on request, but reverse order, on response.
  10265. *
  10266. * {@link ng.$http#interceptors Interceptors detailed info}
  10267. **/
  10268. var interceptorFactories = this.interceptors = [];
  10269. this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
  10270. function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {
  10271. var defaultCache = $cacheFactory('$http');
  10272. /**
  10273. * Make sure that default param serializer is exposed as a function
  10274. */
  10275. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  10276. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  10277. /**
  10278. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  10279. * The reversal is needed so that we can build up the interception chain around the
  10280. * server request.
  10281. */
  10282. var reversedInterceptors = [];
  10283. forEach(interceptorFactories, function(interceptorFactory) {
  10284. reversedInterceptors.unshift(isString(interceptorFactory)
  10285. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  10286. });
  10287. /**
  10288. * @ngdoc service
  10289. * @kind function
  10290. * @name $http
  10291. * @requires ng.$httpBackend
  10292. * @requires $cacheFactory
  10293. * @requires $rootScope
  10294. * @requires $q
  10295. * @requires $injector
  10296. *
  10297. * @description
  10298. * The `$http` service is a core Angular service that facilitates communication with the remote
  10299. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  10300. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  10301. *
  10302. * For unit testing applications that use `$http` service, see
  10303. * {@link ngMock.$httpBackend $httpBackend mock}.
  10304. *
  10305. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  10306. * $resource} service.
  10307. *
  10308. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  10309. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  10310. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  10311. *
  10312. *
  10313. * ## General usage
  10314. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  10315. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  10316. *
  10317. * ```js
  10318. * // Simple GET request example:
  10319. * $http({
  10320. * method: 'GET',
  10321. * url: '/someUrl'
  10322. * }).then(function successCallback(response) {
  10323. * // this callback will be called asynchronously
  10324. * // when the response is available
  10325. * }, function errorCallback(response) {
  10326. * // called asynchronously if an error occurs
  10327. * // or server returns response with an error status.
  10328. * });
  10329. * ```
  10330. *
  10331. * The response object has these properties:
  10332. *
  10333. * - **data** – `{string|Object}` – The response body transformed with the transform
  10334. * functions.
  10335. * - **status** – `{number}` – HTTP status code of the response.
  10336. * - **headers** – `{function([headerName])}` – Header getter function.
  10337. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  10338. * - **statusText** – `{string}` – HTTP status text of the response.
  10339. *
  10340. * A response status code between 200 and 299 is considered a success status and will result in
  10341. * the success callback being called. Any response status code outside of that range is
  10342. * considered an error status and will result in the error callback being called.
  10343. * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
  10344. * aborted, e.g. using a `config.timeout`.
  10345. * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
  10346. * that the outcome (success or error) will be determined by the final response status code.
  10347. *
  10348. *
  10349. * ## Shortcut methods
  10350. *
  10351. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  10352. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  10353. * last argument.
  10354. *
  10355. * ```js
  10356. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  10357. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  10358. * ```
  10359. *
  10360. * Complete list of shortcut methods:
  10361. *
  10362. * - {@link ng.$http#get $http.get}
  10363. * - {@link ng.$http#head $http.head}
  10364. * - {@link ng.$http#post $http.post}
  10365. * - {@link ng.$http#put $http.put}
  10366. * - {@link ng.$http#delete $http.delete}
  10367. * - {@link ng.$http#jsonp $http.jsonp}
  10368. * - {@link ng.$http#patch $http.patch}
  10369. *
  10370. *
  10371. * ## Writing Unit Tests that use $http
  10372. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  10373. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  10374. * request using trained responses.
  10375. *
  10376. * ```
  10377. * $httpBackend.expectGET(...);
  10378. * $http.get(...);
  10379. * $httpBackend.flush();
  10380. * ```
  10381. *
  10382. * ## Setting HTTP Headers
  10383. *
  10384. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  10385. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  10386. * object, which currently contains this default configuration:
  10387. *
  10388. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  10389. * - <code>Accept: application/json, text/plain, \*&#65279;/&#65279;\*</code>
  10390. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  10391. * - `Content-Type: application/json`
  10392. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  10393. * - `Content-Type: application/json`
  10394. *
  10395. * To add or overwrite these defaults, simply add or remove a property from these configuration
  10396. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  10397. * with the lowercased HTTP method name as the key, e.g.
  10398. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  10399. *
  10400. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  10401. * fashion. For example:
  10402. *
  10403. * ```
  10404. * module.run(function($http) {
  10405. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  10406. * });
  10407. * ```
  10408. *
  10409. * In addition, you can supply a `headers` property in the config object passed when
  10410. * calling `$http(config)`, which overrides the defaults without changing them globally.
  10411. *
  10412. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  10413. * Use the `headers` property, setting the desired header to `undefined`. For example:
  10414. *
  10415. * ```js
  10416. * var req = {
  10417. * method: 'POST',
  10418. * url: 'http://example.com',
  10419. * headers: {
  10420. * 'Content-Type': undefined
  10421. * },
  10422. * data: { test: 'test' }
  10423. * }
  10424. *
  10425. * $http(req).then(function(){...}, function(){...});
  10426. * ```
  10427. *
  10428. * ## Transforming Requests and Responses
  10429. *
  10430. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  10431. * and `transformResponse`. These properties can be a single function that returns
  10432. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  10433. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  10434. *
  10435. * <div class="alert alert-warning">
  10436. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  10437. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  10438. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  10439. * function will be reflected on the scope and in any templates where the object is data-bound.
  10440. * To prevent this, transform functions should have no side-effects.
  10441. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  10442. * </div>
  10443. *
  10444. * ### Default Transformations
  10445. *
  10446. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  10447. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  10448. * then these will be applied.
  10449. *
  10450. * You can augment or replace the default transformations by modifying these properties by adding to or
  10451. * replacing the array.
  10452. *
  10453. * Angular provides the following default transformations:
  10454. *
  10455. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  10456. *
  10457. * - If the `data` property of the request configuration object contains an object, serialize it
  10458. * into JSON format.
  10459. *
  10460. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  10461. *
  10462. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  10463. * - If JSON response is detected, deserialize it using a JSON parser.
  10464. *
  10465. *
  10466. * ### Overriding the Default Transformations Per Request
  10467. *
  10468. * If you wish to override the request/response transformations only for a single request then provide
  10469. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  10470. * into `$http`.
  10471. *
  10472. * Note that if you provide these properties on the config object the default transformations will be
  10473. * overwritten. If you wish to augment the default transformations then you must include them in your
  10474. * local transformation array.
  10475. *
  10476. * The following code demonstrates adding a new response transformation to be run after the default response
  10477. * transformations have been run.
  10478. *
  10479. * ```js
  10480. * function appendTransform(defaults, transform) {
  10481. *
  10482. * // We can't guarantee that the default transformation is an array
  10483. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  10484. *
  10485. * // Append the new transformation to the defaults
  10486. * return defaults.concat(transform);
  10487. * }
  10488. *
  10489. * $http({
  10490. * url: '...',
  10491. * method: 'GET',
  10492. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  10493. * return doTransform(value);
  10494. * })
  10495. * });
  10496. * ```
  10497. *
  10498. *
  10499. * ## Caching
  10500. *
  10501. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  10502. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  10503. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  10504. * precedence over the default cache value.
  10505. *
  10506. * In order to:
  10507. * * cache all responses - set the default cache value to TRUE or to a cache object
  10508. * * cache a specific response - set config.cache value to TRUE or to a cache object
  10509. *
  10510. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  10511. * then the default `$cacheFactory("$http")` object is used.
  10512. *
  10513. * The default cache value can be set by updating the
  10514. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  10515. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  10516. *
  10517. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  10518. * the relevant cache object. The next time the same request is made, the response is returned
  10519. * from the cache without sending a request to the server.
  10520. *
  10521. * Take note that:
  10522. *
  10523. * * Only GET and JSONP requests are cached.
  10524. * * The cache key is the request URL including search parameters; headers are not considered.
  10525. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  10526. * * If multiple identical requests are made using the same cache, which is not yet populated,
  10527. * one request will be made to the server and remaining requests will return the same response.
  10528. * * A cache-control header on the response does not affect if or how responses are cached.
  10529. *
  10530. *
  10531. * ## Interceptors
  10532. *
  10533. * Before you start creating interceptors, be sure to understand the
  10534. * {@link ng.$q $q and deferred/promise APIs}.
  10535. *
  10536. * For purposes of global error handling, authentication, or any kind of synchronous or
  10537. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  10538. * able to intercept requests before they are handed to the server and
  10539. * responses before they are handed over to the application code that
  10540. * initiated these requests. The interceptors leverage the {@link ng.$q
  10541. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  10542. *
  10543. * The interceptors are service factories that are registered with the `$httpProvider` by
  10544. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  10545. * injected with dependencies (if specified) and returns the interceptor.
  10546. *
  10547. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  10548. *
  10549. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  10550. * modify the `config` object or create a new one. The function needs to return the `config`
  10551. * object directly, or a promise containing the `config` or a new `config` object.
  10552. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  10553. * resolved with a rejection.
  10554. * * `response`: interceptors get called with http `response` object. The function is free to
  10555. * modify the `response` object or create a new one. The function needs to return the `response`
  10556. * object directly, or as a promise containing the `response` or a new `response` object.
  10557. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  10558. * resolved with a rejection.
  10559. *
  10560. *
  10561. * ```js
  10562. * // register the interceptor as a service
  10563. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  10564. * return {
  10565. * // optional method
  10566. * 'request': function(config) {
  10567. * // do something on success
  10568. * return config;
  10569. * },
  10570. *
  10571. * // optional method
  10572. * 'requestError': function(rejection) {
  10573. * // do something on error
  10574. * if (canRecover(rejection)) {
  10575. * return responseOrNewPromise
  10576. * }
  10577. * return $q.reject(rejection);
  10578. * },
  10579. *
  10580. *
  10581. *
  10582. * // optional method
  10583. * 'response': function(response) {
  10584. * // do something on success
  10585. * return response;
  10586. * },
  10587. *
  10588. * // optional method
  10589. * 'responseError': function(rejection) {
  10590. * // do something on error
  10591. * if (canRecover(rejection)) {
  10592. * return responseOrNewPromise
  10593. * }
  10594. * return $q.reject(rejection);
  10595. * }
  10596. * };
  10597. * });
  10598. *
  10599. * $httpProvider.interceptors.push('myHttpInterceptor');
  10600. *
  10601. *
  10602. * // alternatively, register the interceptor via an anonymous factory
  10603. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  10604. * return {
  10605. * 'request': function(config) {
  10606. * // same as above
  10607. * },
  10608. *
  10609. * 'response': function(response) {
  10610. * // same as above
  10611. * }
  10612. * };
  10613. * });
  10614. * ```
  10615. *
  10616. * ## Security Considerations
  10617. *
  10618. * When designing web applications, consider security threats from:
  10619. *
  10620. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10621. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  10622. *
  10623. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  10624. * pre-configured with strategies that address these issues, but for this to work backend server
  10625. * cooperation is required.
  10626. *
  10627. * ### JSON Vulnerability Protection
  10628. *
  10629. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10630. * allows third party website to turn your JSON resource URL into
  10631. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  10632. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  10633. * Angular will automatically strip the prefix before processing it as JSON.
  10634. *
  10635. * For example if your server needs to return:
  10636. * ```js
  10637. * ['one','two']
  10638. * ```
  10639. *
  10640. * which is vulnerable to attack, your server can return:
  10641. * ```js
  10642. * )]}',
  10643. * ['one','two']
  10644. * ```
  10645. *
  10646. * Angular will strip the prefix, before processing the JSON.
  10647. *
  10648. *
  10649. * ### Cross Site Request Forgery (XSRF) Protection
  10650. *
  10651. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  10652. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  10653. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  10654. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  10655. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  10656. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  10657. * The header will not be set for cross-domain requests.
  10658. *
  10659. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  10660. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  10661. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  10662. * that only JavaScript running on your domain could have sent the request. The token must be
  10663. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  10664. * making up its own tokens). We recommend that the token is a digest of your site's
  10665. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  10666. * for added security.
  10667. *
  10668. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  10669. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  10670. * or the per-request config object.
  10671. *
  10672. * In order to prevent collisions in environments where multiple Angular apps share the
  10673. * same domain or subdomain, we recommend that each application uses unique cookie name.
  10674. *
  10675. * @param {object} config Object describing the request to be made and how it should be
  10676. * processed. The object has following properties:
  10677. *
  10678. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  10679. * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;
  10680. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10681. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  10682. * with the `paramSerializer` and appended as GET parameters.
  10683. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  10684. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  10685. * HTTP headers to send to the server. If the return value of a function is null, the
  10686. * header will not be sent. Functions accept a config object as an argument.
  10687. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  10688. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  10689. * The handler will be called in the context of a `$apply` block.
  10690. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  10691. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  10692. * The handler will be called in the context of a `$apply` block.
  10693. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  10694. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  10695. * - **transformRequest** –
  10696. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  10697. * transform function or an array of such functions. The transform function takes the http
  10698. * request body and headers and returns its transformed (typically serialized) version.
  10699. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10700. * Overriding the Default Transformations}
  10701. * - **transformResponse** –
  10702. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  10703. * transform function or an array of such functions. The transform function takes the http
  10704. * response body, headers and status and returns its transformed (typically deserialized) version.
  10705. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10706. * Overriding the Default Transformations}
  10707. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  10708. * prepare the string representation of request parameters (specified as an object).
  10709. * If specified as string, it is interpreted as function registered with the
  10710. * {@link $injector $injector}, which means you can create your own serializer
  10711. * by registering it as a {@link auto.$provide#service service}.
  10712. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  10713. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  10714. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  10715. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  10716. * See {@link $http#caching $http Caching} for more information.
  10717. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  10718. * that should abort the request when resolved.
  10719. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  10720. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  10721. * for more information.
  10722. * - **responseType** - `{string}` - see
  10723. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  10724. *
  10725. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  10726. * when the request succeeds or fails.
  10727. *
  10728. *
  10729. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  10730. * requests. This is primarily meant to be used for debugging purposes.
  10731. *
  10732. *
  10733. * @example
  10734. <example module="httpExample" name="http-service">
  10735. <file name="index.html">
  10736. <div ng-controller="FetchController">
  10737. <select ng-model="method" aria-label="Request method">
  10738. <option>GET</option>
  10739. <option>JSONP</option>
  10740. </select>
  10741. <input type="text" ng-model="url" size="80" aria-label="URL" />
  10742. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  10743. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  10744. <button id="samplejsonpbtn"
  10745. ng-click="updateModel('JSONP',
  10746. 'https://angularjs.org/greet.php?name=Super%20Hero')">
  10747. Sample JSONP
  10748. </button>
  10749. <button id="invalidjsonpbtn"
  10750. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')">
  10751. Invalid JSONP
  10752. </button>
  10753. <pre>http status code: {{status}}</pre>
  10754. <pre>http response data: {{data}}</pre>
  10755. </div>
  10756. </file>
  10757. <file name="script.js">
  10758. angular.module('httpExample', [])
  10759. .config(['$sceDelegateProvider', function($sceDelegateProvider) {
  10760. // We must whitelist the JSONP endpoint that we are using to show that we trust it
  10761. $sceDelegateProvider.resourceUrlWhitelist([
  10762. 'self',
  10763. 'https://angularjs.org/**'
  10764. ]);
  10765. }])
  10766. .controller('FetchController', ['$scope', '$http', '$templateCache',
  10767. function($scope, $http, $templateCache) {
  10768. $scope.method = 'GET';
  10769. $scope.url = 'http-hello.html';
  10770. $scope.fetch = function() {
  10771. $scope.code = null;
  10772. $scope.response = null;
  10773. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  10774. then(function(response) {
  10775. $scope.status = response.status;
  10776. $scope.data = response.data;
  10777. }, function(response) {
  10778. $scope.data = response.data || 'Request failed';
  10779. $scope.status = response.status;
  10780. });
  10781. };
  10782. $scope.updateModel = function(method, url) {
  10783. $scope.method = method;
  10784. $scope.url = url;
  10785. };
  10786. }]);
  10787. </file>
  10788. <file name="http-hello.html">
  10789. Hello, $http!
  10790. </file>
  10791. <file name="protractor.js" type="protractor">
  10792. var status = element(by.binding('status'));
  10793. var data = element(by.binding('data'));
  10794. var fetchBtn = element(by.id('fetchbtn'));
  10795. var sampleGetBtn = element(by.id('samplegetbtn'));
  10796. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  10797. it('should make an xhr GET request', function() {
  10798. sampleGetBtn.click();
  10799. fetchBtn.click();
  10800. expect(status.getText()).toMatch('200');
  10801. expect(data.getText()).toMatch(/Hello, \$http!/);
  10802. });
  10803. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  10804. // it('should make a JSONP request to angularjs.org', function() {
  10805. // var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  10806. // sampleJsonpBtn.click();
  10807. // fetchBtn.click();
  10808. // expect(status.getText()).toMatch('200');
  10809. // expect(data.getText()).toMatch(/Super Hero!/);
  10810. // });
  10811. it('should make JSONP request to invalid URL and invoke the error handler',
  10812. function() {
  10813. invalidJsonpBtn.click();
  10814. fetchBtn.click();
  10815. expect(status.getText()).toMatch('0');
  10816. expect(data.getText()).toMatch('Request failed');
  10817. });
  10818. </file>
  10819. </example>
  10820. */
  10821. function $http(requestConfig) {
  10822. if (!isObject(requestConfig)) {
  10823. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  10824. }
  10825. if (!isString($sce.valueOf(requestConfig.url))) {
  10826. throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);
  10827. }
  10828. var config = extend({
  10829. method: 'get',
  10830. transformRequest: defaults.transformRequest,
  10831. transformResponse: defaults.transformResponse,
  10832. paramSerializer: defaults.paramSerializer,
  10833. jsonpCallbackParam: defaults.jsonpCallbackParam
  10834. }, requestConfig);
  10835. config.headers = mergeHeaders(requestConfig);
  10836. config.method = uppercase(config.method);
  10837. config.paramSerializer = isString(config.paramSerializer) ?
  10838. $injector.get(config.paramSerializer) : config.paramSerializer;
  10839. $browser.$$incOutstandingRequestCount();
  10840. var requestInterceptors = [];
  10841. var responseInterceptors = [];
  10842. var promise = $q.resolve(config);
  10843. // apply interceptors
  10844. forEach(reversedInterceptors, function(interceptor) {
  10845. if (interceptor.request || interceptor.requestError) {
  10846. requestInterceptors.unshift(interceptor.request, interceptor.requestError);
  10847. }
  10848. if (interceptor.response || interceptor.responseError) {
  10849. responseInterceptors.push(interceptor.response, interceptor.responseError);
  10850. }
  10851. });
  10852. promise = chainInterceptors(promise, requestInterceptors);
  10853. promise = promise.then(serverRequest);
  10854. promise = chainInterceptors(promise, responseInterceptors);
  10855. promise = promise.finally(completeOutstandingRequest);
  10856. return promise;
  10857. function chainInterceptors(promise, interceptors) {
  10858. for (var i = 0, ii = interceptors.length; i < ii;) {
  10859. var thenFn = interceptors[i++];
  10860. var rejectFn = interceptors[i++];
  10861. promise = promise.then(thenFn, rejectFn);
  10862. }
  10863. interceptors.length = 0;
  10864. return promise;
  10865. }
  10866. function completeOutstandingRequest() {
  10867. $browser.$$completeOutstandingRequest(noop);
  10868. }
  10869. function executeHeaderFns(headers, config) {
  10870. var headerContent, processedHeaders = {};
  10871. forEach(headers, function(headerFn, header) {
  10872. if (isFunction(headerFn)) {
  10873. headerContent = headerFn(config);
  10874. if (headerContent != null) {
  10875. processedHeaders[header] = headerContent;
  10876. }
  10877. } else {
  10878. processedHeaders[header] = headerFn;
  10879. }
  10880. });
  10881. return processedHeaders;
  10882. }
  10883. function mergeHeaders(config) {
  10884. var defHeaders = defaults.headers,
  10885. reqHeaders = extend({}, config.headers),
  10886. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  10887. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  10888. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  10889. defaultHeadersIteration:
  10890. for (defHeaderName in defHeaders) {
  10891. lowercaseDefHeaderName = lowercase(defHeaderName);
  10892. for (reqHeaderName in reqHeaders) {
  10893. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  10894. continue defaultHeadersIteration;
  10895. }
  10896. }
  10897. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  10898. }
  10899. // execute if header value is a function for merged headers
  10900. return executeHeaderFns(reqHeaders, shallowCopy(config));
  10901. }
  10902. function serverRequest(config) {
  10903. var headers = config.headers;
  10904. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  10905. // strip content-type if data is undefined
  10906. if (isUndefined(reqData)) {
  10907. forEach(headers, function(value, header) {
  10908. if (lowercase(header) === 'content-type') {
  10909. delete headers[header];
  10910. }
  10911. });
  10912. }
  10913. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  10914. config.withCredentials = defaults.withCredentials;
  10915. }
  10916. // send request
  10917. return sendReq(config, reqData).then(transformResponse, transformResponse);
  10918. }
  10919. function transformResponse(response) {
  10920. // make a copy since the response must be cacheable
  10921. var resp = extend({}, response);
  10922. resp.data = transformData(response.data, response.headers, response.status,
  10923. config.transformResponse);
  10924. return (isSuccess(response.status))
  10925. ? resp
  10926. : $q.reject(resp);
  10927. }
  10928. }
  10929. $http.pendingRequests = [];
  10930. /**
  10931. * @ngdoc method
  10932. * @name $http#get
  10933. *
  10934. * @description
  10935. * Shortcut method to perform `GET` request.
  10936. *
  10937. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10938. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10939. * @param {Object=} config Optional configuration object
  10940. * @returns {HttpPromise} Future object
  10941. */
  10942. /**
  10943. * @ngdoc method
  10944. * @name $http#delete
  10945. *
  10946. * @description
  10947. * Shortcut method to perform `DELETE` request.
  10948. *
  10949. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10950. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10951. * @param {Object=} config Optional configuration object
  10952. * @returns {HttpPromise} Future object
  10953. */
  10954. /**
  10955. * @ngdoc method
  10956. * @name $http#head
  10957. *
  10958. * @description
  10959. * Shortcut method to perform `HEAD` request.
  10960. *
  10961. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10962. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10963. * @param {Object=} config Optional configuration object
  10964. * @returns {HttpPromise} Future object
  10965. */
  10966. /**
  10967. * @ngdoc method
  10968. * @name $http#jsonp
  10969. *
  10970. * @description
  10971. * Shortcut method to perform `JSONP` request.
  10972. *
  10973. * Note that, since JSONP requests are sensitive because the response is given full access to the browser,
  10974. * the url must be declared, via {@link $sce} as a trusted resource URL.
  10975. * You can trust a URL by adding it to the whitelist via
  10976. * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or
  10977. * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.
  10978. *
  10979. * JSONP requests must specify a callback to be used in the response from the server. This callback
  10980. * is passed as a query parameter in the request. You must specify the name of this parameter by
  10981. * setting the `jsonpCallbackParam` property on the request config object.
  10982. *
  10983. * ```
  10984. * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
  10985. * ```
  10986. *
  10987. * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.
  10988. * Initially this is set to `'callback'`.
  10989. *
  10990. * <div class="alert alert-danger">
  10991. * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback
  10992. * parameter value should go.
  10993. * </div>
  10994. *
  10995. * If you would like to customise where and how the callbacks are stored then try overriding
  10996. * or decorating the {@link $jsonpCallbacks} service.
  10997. *
  10998. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  10999. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11000. * @param {Object=} config Optional configuration object
  11001. * @returns {HttpPromise} Future object
  11002. */
  11003. createShortMethods('get', 'delete', 'head', 'jsonp');
  11004. /**
  11005. * @ngdoc method
  11006. * @name $http#post
  11007. *
  11008. * @description
  11009. * Shortcut method to perform `POST` request.
  11010. *
  11011. * @param {string} url Relative or absolute URL specifying the destination of the request
  11012. * @param {*} data Request content
  11013. * @param {Object=} config Optional configuration object
  11014. * @returns {HttpPromise} Future object
  11015. */
  11016. /**
  11017. * @ngdoc method
  11018. * @name $http#put
  11019. *
  11020. * @description
  11021. * Shortcut method to perform `PUT` request.
  11022. *
  11023. * @param {string} url Relative or absolute URL specifying the destination of the request
  11024. * @param {*} data Request content
  11025. * @param {Object=} config Optional configuration object
  11026. * @returns {HttpPromise} Future object
  11027. */
  11028. /**
  11029. * @ngdoc method
  11030. * @name $http#patch
  11031. *
  11032. * @description
  11033. * Shortcut method to perform `PATCH` request.
  11034. *
  11035. * @param {string} url Relative or absolute URL specifying the destination of the request
  11036. * @param {*} data Request content
  11037. * @param {Object=} config Optional configuration object
  11038. * @returns {HttpPromise} Future object
  11039. */
  11040. createShortMethodsWithData('post', 'put', 'patch');
  11041. /**
  11042. * @ngdoc property
  11043. * @name $http#defaults
  11044. *
  11045. * @description
  11046. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  11047. * default headers, withCredentials as well as request and response transformations.
  11048. *
  11049. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  11050. */
  11051. $http.defaults = defaults;
  11052. return $http;
  11053. function createShortMethods(names) {
  11054. forEach(arguments, function(name) {
  11055. $http[name] = function(url, config) {
  11056. return $http(extend({}, config || {}, {
  11057. method: name,
  11058. url: url
  11059. }));
  11060. };
  11061. });
  11062. }
  11063. function createShortMethodsWithData(name) {
  11064. forEach(arguments, function(name) {
  11065. $http[name] = function(url, data, config) {
  11066. return $http(extend({}, config || {}, {
  11067. method: name,
  11068. url: url,
  11069. data: data
  11070. }));
  11071. };
  11072. });
  11073. }
  11074. /**
  11075. * Makes the request.
  11076. *
  11077. * !!! ACCESSES CLOSURE VARS:
  11078. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  11079. */
  11080. function sendReq(config, reqData) {
  11081. var deferred = $q.defer(),
  11082. promise = deferred.promise,
  11083. cache,
  11084. cachedResp,
  11085. reqHeaders = config.headers,
  11086. isJsonp = lowercase(config.method) === 'jsonp',
  11087. url = config.url;
  11088. if (isJsonp) {
  11089. // JSONP is a pretty sensitive operation where we're allowing a script to have full access to
  11090. // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.
  11091. url = $sce.getTrustedResourceUrl(url);
  11092. } else if (!isString(url)) {
  11093. // If it is not a string then the URL must be a $sce trusted object
  11094. url = $sce.valueOf(url);
  11095. }
  11096. url = buildUrl(url, config.paramSerializer(config.params));
  11097. if (isJsonp) {
  11098. // Check the url and add the JSONP callback placeholder
  11099. url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);
  11100. }
  11101. $http.pendingRequests.push(config);
  11102. promise.then(removePendingReq, removePendingReq);
  11103. if ((config.cache || defaults.cache) && config.cache !== false &&
  11104. (config.method === 'GET' || config.method === 'JSONP')) {
  11105. cache = isObject(config.cache) ? config.cache
  11106. : isObject(/** @type {?} */ (defaults).cache)
  11107. ? /** @type {?} */ (defaults).cache
  11108. : defaultCache;
  11109. }
  11110. if (cache) {
  11111. cachedResp = cache.get(url);
  11112. if (isDefined(cachedResp)) {
  11113. if (isPromiseLike(cachedResp)) {
  11114. // cached request has already been sent, but there is no response yet
  11115. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  11116. } else {
  11117. // serving from cache
  11118. if (isArray(cachedResp)) {
  11119. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  11120. } else {
  11121. resolvePromise(cachedResp, 200, {}, 'OK');
  11122. }
  11123. }
  11124. } else {
  11125. // put the promise for the non-transformed response into cache as a placeholder
  11126. cache.put(url, promise);
  11127. }
  11128. }
  11129. // if we won't have the response in cache, set the xsrf headers and
  11130. // send the request to the backend
  11131. if (isUndefined(cachedResp)) {
  11132. var xsrfValue = urlIsSameOrigin(config.url)
  11133. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  11134. : undefined;
  11135. if (xsrfValue) {
  11136. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  11137. }
  11138. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  11139. config.withCredentials, config.responseType,
  11140. createApplyHandlers(config.eventHandlers),
  11141. createApplyHandlers(config.uploadEventHandlers));
  11142. }
  11143. return promise;
  11144. function createApplyHandlers(eventHandlers) {
  11145. if (eventHandlers) {
  11146. var applyHandlers = {};
  11147. forEach(eventHandlers, function(eventHandler, key) {
  11148. applyHandlers[key] = function(event) {
  11149. if (useApplyAsync) {
  11150. $rootScope.$applyAsync(callEventHandler);
  11151. } else if ($rootScope.$$phase) {
  11152. callEventHandler();
  11153. } else {
  11154. $rootScope.$apply(callEventHandler);
  11155. }
  11156. function callEventHandler() {
  11157. eventHandler(event);
  11158. }
  11159. };
  11160. });
  11161. return applyHandlers;
  11162. }
  11163. }
  11164. /**
  11165. * Callback registered to $httpBackend():
  11166. * - caches the response if desired
  11167. * - resolves the raw $http promise
  11168. * - calls $apply
  11169. */
  11170. function done(status, response, headersString, statusText) {
  11171. if (cache) {
  11172. if (isSuccess(status)) {
  11173. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  11174. } else {
  11175. // remove promise from the cache
  11176. cache.remove(url);
  11177. }
  11178. }
  11179. function resolveHttpPromise() {
  11180. resolvePromise(response, status, headersString, statusText);
  11181. }
  11182. if (useApplyAsync) {
  11183. $rootScope.$applyAsync(resolveHttpPromise);
  11184. } else {
  11185. resolveHttpPromise();
  11186. if (!$rootScope.$$phase) $rootScope.$apply();
  11187. }
  11188. }
  11189. /**
  11190. * Resolves the raw $http promise.
  11191. */
  11192. function resolvePromise(response, status, headers, statusText) {
  11193. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  11194. status = status >= -1 ? status : 0;
  11195. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  11196. data: response,
  11197. status: status,
  11198. headers: headersGetter(headers),
  11199. config: config,
  11200. statusText: statusText
  11201. });
  11202. }
  11203. function resolvePromiseWithResult(result) {
  11204. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  11205. }
  11206. function removePendingReq() {
  11207. var idx = $http.pendingRequests.indexOf(config);
  11208. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  11209. }
  11210. }
  11211. function buildUrl(url, serializedParams) {
  11212. if (serializedParams.length > 0) {
  11213. url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
  11214. }
  11215. return url;
  11216. }
  11217. function sanitizeJsonpCallbackParam(url, key) {
  11218. if (/[&?][^=]+=JSON_CALLBACK/.test(url)) {
  11219. // Throw if the url already contains a reference to JSON_CALLBACK
  11220. throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url);
  11221. }
  11222. var callbackParamRegex = new RegExp('[&?]' + key + '=');
  11223. if (callbackParamRegex.test(url)) {
  11224. // Throw if the callback param was already provided
  11225. throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', key, url);
  11226. }
  11227. // Add in the JSON_CALLBACK callback param value
  11228. url += ((url.indexOf('?') === -1) ? '?' : '&') + key + '=JSON_CALLBACK';
  11229. return url;
  11230. }
  11231. }];
  11232. }
  11233. /**
  11234. * @ngdoc service
  11235. * @name $xhrFactory
  11236. * @this
  11237. *
  11238. * @description
  11239. * Factory function used to create XMLHttpRequest objects.
  11240. *
  11241. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  11242. *
  11243. * ```
  11244. * angular.module('myApp', [])
  11245. * .factory('$xhrFactory', function() {
  11246. * return function createXhr(method, url) {
  11247. * return new window.XMLHttpRequest({mozSystem: true});
  11248. * };
  11249. * });
  11250. * ```
  11251. *
  11252. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  11253. * @param {string} url URL of the request.
  11254. */
  11255. function $xhrFactoryProvider() {
  11256. this.$get = function() {
  11257. return function createXhr() {
  11258. return new window.XMLHttpRequest();
  11259. };
  11260. };
  11261. }
  11262. /**
  11263. * @ngdoc service
  11264. * @name $httpBackend
  11265. * @requires $jsonpCallbacks
  11266. * @requires $document
  11267. * @requires $xhrFactory
  11268. * @this
  11269. *
  11270. * @description
  11271. * HTTP backend used by the {@link ng.$http service} that delegates to
  11272. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  11273. *
  11274. * You should never need to use this service directly, instead use the higher-level abstractions:
  11275. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  11276. *
  11277. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  11278. * $httpBackend} which can be trained with responses.
  11279. */
  11280. function $HttpBackendProvider() {
  11281. this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
  11282. return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
  11283. }];
  11284. }
  11285. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  11286. // TODO(vojta): fix the signature
  11287. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  11288. url = url || $browser.url();
  11289. if (lowercase(method) === 'jsonp') {
  11290. var callbackPath = callbacks.createCallback(url);
  11291. var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
  11292. // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
  11293. var response = (status === 200) && callbacks.getResponse(callbackPath);
  11294. completeRequest(callback, status, response, '', text);
  11295. callbacks.removeCallback(callbackPath);
  11296. });
  11297. } else {
  11298. var xhr = createXhr(method, url);
  11299. xhr.open(method, url, true);
  11300. forEach(headers, function(value, key) {
  11301. if (isDefined(value)) {
  11302. xhr.setRequestHeader(key, value);
  11303. }
  11304. });
  11305. xhr.onload = function requestLoaded() {
  11306. var statusText = xhr.statusText || '';
  11307. // responseText is the old-school way of retrieving response (supported by IE9)
  11308. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  11309. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  11310. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  11311. var status = xhr.status === 1223 ? 204 : xhr.status;
  11312. // fix status code when it is 0 (0 status is undocumented).
  11313. // Occurs when accessing file resources or on Android 4.1 stock browser
  11314. // while retrieving files from application cache.
  11315. if (status === 0) {
  11316. status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
  11317. }
  11318. completeRequest(callback,
  11319. status,
  11320. response,
  11321. xhr.getAllResponseHeaders(),
  11322. statusText);
  11323. };
  11324. var requestError = function() {
  11325. // The response is always empty
  11326. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  11327. completeRequest(callback, -1, null, null, '');
  11328. };
  11329. xhr.onerror = requestError;
  11330. xhr.onabort = requestError;
  11331. xhr.ontimeout = requestError;
  11332. forEach(eventHandlers, function(value, key) {
  11333. xhr.addEventListener(key, value);
  11334. });
  11335. forEach(uploadEventHandlers, function(value, key) {
  11336. xhr.upload.addEventListener(key, value);
  11337. });
  11338. if (withCredentials) {
  11339. xhr.withCredentials = true;
  11340. }
  11341. if (responseType) {
  11342. try {
  11343. xhr.responseType = responseType;
  11344. } catch (e) {
  11345. // WebKit added support for the json responseType value on 09/03/2013
  11346. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  11347. // known to throw when setting the value "json" as the response type. Other older
  11348. // browsers implementing the responseType
  11349. //
  11350. // The json response type can be ignored if not supported, because JSON payloads are
  11351. // parsed on the client-side regardless.
  11352. if (responseType !== 'json') {
  11353. throw e;
  11354. }
  11355. }
  11356. }
  11357. xhr.send(isUndefined(post) ? null : post);
  11358. }
  11359. if (timeout > 0) {
  11360. var timeoutId = $browserDefer(timeoutRequest, timeout);
  11361. } else if (isPromiseLike(timeout)) {
  11362. timeout.then(timeoutRequest);
  11363. }
  11364. function timeoutRequest() {
  11365. if (jsonpDone) {
  11366. jsonpDone();
  11367. }
  11368. if (xhr) {
  11369. xhr.abort();
  11370. }
  11371. }
  11372. function completeRequest(callback, status, response, headersString, statusText) {
  11373. // cancel timeout and subsequent timeout promise resolution
  11374. if (isDefined(timeoutId)) {
  11375. $browserDefer.cancel(timeoutId);
  11376. }
  11377. jsonpDone = xhr = null;
  11378. callback(status, response, headersString, statusText);
  11379. }
  11380. };
  11381. function jsonpReq(url, callbackPath, done) {
  11382. url = url.replace('JSON_CALLBACK', callbackPath);
  11383. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  11384. // - fetches local scripts via XHR and evals them
  11385. // - adds and immediately removes script elements from the document
  11386. var script = rawDocument.createElement('script'), callback = null;
  11387. script.type = 'text/javascript';
  11388. script.src = url;
  11389. script.async = true;
  11390. callback = function(event) {
  11391. script.removeEventListener('load', callback);
  11392. script.removeEventListener('error', callback);
  11393. rawDocument.body.removeChild(script);
  11394. script = null;
  11395. var status = -1;
  11396. var text = 'unknown';
  11397. if (event) {
  11398. if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
  11399. event = { type: 'error' };
  11400. }
  11401. text = event.type;
  11402. status = event.type === 'error' ? 404 : 200;
  11403. }
  11404. if (done) {
  11405. done(status, text);
  11406. }
  11407. };
  11408. script.addEventListener('load', callback);
  11409. script.addEventListener('error', callback);
  11410. rawDocument.body.appendChild(script);
  11411. return callback;
  11412. }
  11413. }
  11414. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  11415. $interpolateMinErr.throwNoconcat = function(text) {
  11416. throw $interpolateMinErr('noconcat',
  11417. 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
  11418. 'interpolations that concatenate multiple expressions when a trusted value is ' +
  11419. 'required. See http://docs.angularjs.org/api/ng.$sce', text);
  11420. };
  11421. $interpolateMinErr.interr = function(text, err) {
  11422. return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
  11423. };
  11424. /**
  11425. * @ngdoc provider
  11426. * @name $interpolateProvider
  11427. * @this
  11428. *
  11429. * @description
  11430. *
  11431. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  11432. *
  11433. * <div class="alert alert-danger">
  11434. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  11435. * template within a Python Jinja template (or any other template language). Mixing templating
  11436. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  11437. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  11438. * security bugs!
  11439. * </div>
  11440. *
  11441. * @example
  11442. <example name="custom-interpolation-markup" module="customInterpolationApp">
  11443. <file name="index.html">
  11444. <script>
  11445. var customInterpolationApp = angular.module('customInterpolationApp', []);
  11446. customInterpolationApp.config(function($interpolateProvider) {
  11447. $interpolateProvider.startSymbol('//');
  11448. $interpolateProvider.endSymbol('//');
  11449. });
  11450. customInterpolationApp.controller('DemoController', function() {
  11451. this.label = "This binding is brought you by // interpolation symbols.";
  11452. });
  11453. </script>
  11454. <div ng-controller="DemoController as demo">
  11455. //demo.label//
  11456. </div>
  11457. </file>
  11458. <file name="protractor.js" type="protractor">
  11459. it('should interpolate binding with custom symbols', function() {
  11460. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  11461. });
  11462. </file>
  11463. </example>
  11464. */
  11465. function $InterpolateProvider() {
  11466. var startSymbol = '{{';
  11467. var endSymbol = '}}';
  11468. /**
  11469. * @ngdoc method
  11470. * @name $interpolateProvider#startSymbol
  11471. * @description
  11472. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  11473. *
  11474. * @param {string=} value new value to set the starting symbol to.
  11475. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11476. */
  11477. this.startSymbol = function(value) {
  11478. if (value) {
  11479. startSymbol = value;
  11480. return this;
  11481. } else {
  11482. return startSymbol;
  11483. }
  11484. };
  11485. /**
  11486. * @ngdoc method
  11487. * @name $interpolateProvider#endSymbol
  11488. * @description
  11489. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11490. *
  11491. * @param {string=} value new value to set the ending symbol to.
  11492. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11493. */
  11494. this.endSymbol = function(value) {
  11495. if (value) {
  11496. endSymbol = value;
  11497. return this;
  11498. } else {
  11499. return endSymbol;
  11500. }
  11501. };
  11502. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  11503. var startSymbolLength = startSymbol.length,
  11504. endSymbolLength = endSymbol.length,
  11505. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  11506. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  11507. function escape(ch) {
  11508. return '\\\\\\' + ch;
  11509. }
  11510. function unescapeText(text) {
  11511. return text.replace(escapedStartRegexp, startSymbol).
  11512. replace(escapedEndRegexp, endSymbol);
  11513. }
  11514. // TODO: this is the same as the constantWatchDelegate in parse.js
  11515. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  11516. var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  11517. unwatch();
  11518. return constantInterp(scope);
  11519. }, listener, objectEquality);
  11520. return unwatch;
  11521. }
  11522. /**
  11523. * @ngdoc service
  11524. * @name $interpolate
  11525. * @kind function
  11526. *
  11527. * @requires $parse
  11528. * @requires $sce
  11529. *
  11530. * @description
  11531. *
  11532. * Compiles a string with markup into an interpolation function. This service is used by the
  11533. * HTML {@link ng.$compile $compile} service for data binding. See
  11534. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  11535. * interpolation markup.
  11536. *
  11537. *
  11538. * ```js
  11539. * var $interpolate = ...; // injected
  11540. * var exp = $interpolate('Hello {{name | uppercase}}!');
  11541. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  11542. * ```
  11543. *
  11544. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  11545. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  11546. * evaluate to a value other than `undefined`.
  11547. *
  11548. * ```js
  11549. * var $interpolate = ...; // injected
  11550. * var context = {greeting: 'Hello', name: undefined };
  11551. *
  11552. * // default "forgiving" mode
  11553. * var exp = $interpolate('{{greeting}} {{name}}!');
  11554. * expect(exp(context)).toEqual('Hello !');
  11555. *
  11556. * // "allOrNothing" mode
  11557. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  11558. * expect(exp(context)).toBeUndefined();
  11559. * context.name = 'Angular';
  11560. * expect(exp(context)).toEqual('Hello Angular!');
  11561. * ```
  11562. *
  11563. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  11564. *
  11565. * #### Escaped Interpolation
  11566. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  11567. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  11568. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  11569. * or binding.
  11570. *
  11571. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  11572. * degree, while also enabling code examples to work without relying on the
  11573. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  11574. *
  11575. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  11576. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  11577. * interpolation start/end markers with their escaped counterparts.**
  11578. *
  11579. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  11580. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  11581. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  11582. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  11583. * this is typically useful only when user-data is used in rendering a template from the server, or
  11584. * when otherwise untrusted data is used by a directive.
  11585. *
  11586. * <example name="interpolation">
  11587. * <file name="index.html">
  11588. * <div ng-init="username='A user'">
  11589. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  11590. * </p>
  11591. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  11592. * application, but fails to accomplish their task, because the server has correctly
  11593. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  11594. * characters.</p>
  11595. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  11596. * from the database by an administrator.</p>
  11597. * </div>
  11598. * </file>
  11599. * </example>
  11600. *
  11601. * @knownIssue
  11602. * It is currently not possible for an interpolated expression to contain the interpolation end
  11603. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  11604. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  11605. *
  11606. * @knownIssue
  11607. * All directives and components must use the standard `{{` `}}` interpolation symbols
  11608. * in their templates. If you change the application interpolation symbols the {@link $compile}
  11609. * service will attempt to denormalize the standard symbols to the custom symbols.
  11610. * The denormalization process is not clever enough to know not to replace instances of the standard
  11611. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  11612. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  11613. *
  11614. * ```
  11615. * <div data-context='{"context":{"id":3,"type":"page"}}">
  11616. * ```
  11617. *
  11618. * The workaround is to ensure that such instances are separated by whitespace:
  11619. * ```
  11620. * <div data-context='{"context":{"id":3,"type":"page"} }">
  11621. * ```
  11622. *
  11623. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  11624. *
  11625. * @param {string} text The text with markup to interpolate.
  11626. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  11627. * embedded expression in order to return an interpolation function. Strings with no
  11628. * embedded expression will return null for the interpolation function.
  11629. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  11630. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  11631. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  11632. * provides Strict Contextual Escaping for details.
  11633. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  11634. * unless all embedded expressions evaluate to a value other than `undefined`.
  11635. * @returns {function(context)} an interpolation function which is used to compute the
  11636. * interpolated string. The function has these parameters:
  11637. *
  11638. * - `context`: evaluation context for all expressions embedded in the interpolated text
  11639. */
  11640. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  11641. // Provide a quick exit and simplified result function for text with no interpolation
  11642. if (!text.length || text.indexOf(startSymbol) === -1) {
  11643. var constantInterp;
  11644. if (!mustHaveExpression) {
  11645. var unescapedText = unescapeText(text);
  11646. constantInterp = valueFn(unescapedText);
  11647. constantInterp.exp = text;
  11648. constantInterp.expressions = [];
  11649. constantInterp.$$watchDelegate = constantWatchDelegate;
  11650. }
  11651. return constantInterp;
  11652. }
  11653. allOrNothing = !!allOrNothing;
  11654. var startIndex,
  11655. endIndex,
  11656. index = 0,
  11657. expressions = [],
  11658. parseFns = [],
  11659. textLength = text.length,
  11660. exp,
  11661. concat = [],
  11662. expressionPositions = [];
  11663. while (index < textLength) {
  11664. if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
  11665. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
  11666. if (index !== startIndex) {
  11667. concat.push(unescapeText(text.substring(index, startIndex)));
  11668. }
  11669. exp = text.substring(startIndex + startSymbolLength, endIndex);
  11670. expressions.push(exp);
  11671. parseFns.push($parse(exp, parseStringifyInterceptor));
  11672. index = endIndex + endSymbolLength;
  11673. expressionPositions.push(concat.length);
  11674. concat.push('');
  11675. } else {
  11676. // we did not find an interpolation, so we have to add the remainder to the separators array
  11677. if (index !== textLength) {
  11678. concat.push(unescapeText(text.substring(index)));
  11679. }
  11680. break;
  11681. }
  11682. }
  11683. // Concatenating expressions makes it hard to reason about whether some combination of
  11684. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  11685. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  11686. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  11687. // make it obvious that you bound the value to some user controlled value. This helps reduce
  11688. // the load when auditing for XSS issues.
  11689. if (trustedContext && concat.length > 1) {
  11690. $interpolateMinErr.throwNoconcat(text);
  11691. }
  11692. if (!mustHaveExpression || expressions.length) {
  11693. var compute = function(values) {
  11694. for (var i = 0, ii = expressions.length; i < ii; i++) {
  11695. if (allOrNothing && isUndefined(values[i])) return;
  11696. concat[expressionPositions[i]] = values[i];
  11697. }
  11698. return concat.join('');
  11699. };
  11700. var getValue = function(value) {
  11701. return trustedContext ?
  11702. $sce.getTrusted(trustedContext, value) :
  11703. $sce.valueOf(value);
  11704. };
  11705. return extend(function interpolationFn(context) {
  11706. var i = 0;
  11707. var ii = expressions.length;
  11708. var values = new Array(ii);
  11709. try {
  11710. for (; i < ii; i++) {
  11711. values[i] = parseFns[i](context);
  11712. }
  11713. return compute(values);
  11714. } catch (err) {
  11715. $exceptionHandler($interpolateMinErr.interr(text, err));
  11716. }
  11717. }, {
  11718. // all of these properties are undocumented for now
  11719. exp: text, //just for compatibility with regular watchers created via $watch
  11720. expressions: expressions,
  11721. $$watchDelegate: function(scope, listener) {
  11722. var lastValue;
  11723. return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
  11724. var currValue = compute(values);
  11725. if (isFunction(listener)) {
  11726. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  11727. }
  11728. lastValue = currValue;
  11729. });
  11730. }
  11731. });
  11732. }
  11733. function parseStringifyInterceptor(value) {
  11734. try {
  11735. value = getValue(value);
  11736. return allOrNothing && !isDefined(value) ? value : stringify(value);
  11737. } catch (err) {
  11738. $exceptionHandler($interpolateMinErr.interr(text, err));
  11739. }
  11740. }
  11741. }
  11742. /**
  11743. * @ngdoc method
  11744. * @name $interpolate#startSymbol
  11745. * @description
  11746. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  11747. *
  11748. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  11749. * the symbol.
  11750. *
  11751. * @returns {string} start symbol.
  11752. */
  11753. $interpolate.startSymbol = function() {
  11754. return startSymbol;
  11755. };
  11756. /**
  11757. * @ngdoc method
  11758. * @name $interpolate#endSymbol
  11759. * @description
  11760. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11761. *
  11762. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  11763. * the symbol.
  11764. *
  11765. * @returns {string} end symbol.
  11766. */
  11767. $interpolate.endSymbol = function() {
  11768. return endSymbol;
  11769. };
  11770. return $interpolate;
  11771. }];
  11772. }
  11773. /** @this */
  11774. function $IntervalProvider() {
  11775. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  11776. function($rootScope, $window, $q, $$q, $browser) {
  11777. var intervals = {};
  11778. /**
  11779. * @ngdoc service
  11780. * @name $interval
  11781. *
  11782. * @description
  11783. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  11784. * milliseconds.
  11785. *
  11786. * The return value of registering an interval function is a promise. This promise will be
  11787. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  11788. * run indefinitely if `count` is not defined. The value of the notification will be the
  11789. * number of iterations that have run.
  11790. * To cancel an interval, call `$interval.cancel(promise)`.
  11791. *
  11792. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  11793. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  11794. * time.
  11795. *
  11796. * <div class="alert alert-warning">
  11797. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  11798. * with them. In particular they are not automatically destroyed when a controller's scope or a
  11799. * directive's element are destroyed.
  11800. * You should take this into consideration and make sure to always cancel the interval at the
  11801. * appropriate moment. See the example below for more details on how and when to do this.
  11802. * </div>
  11803. *
  11804. * @param {function()} fn A function that should be called repeatedly. If no additional arguments
  11805. * are passed (see below), the function is called with the current iteration count.
  11806. * @param {number} delay Number of milliseconds between each function call.
  11807. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  11808. * indefinitely.
  11809. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  11810. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  11811. * @param {...*=} Pass additional parameters to the executed function.
  11812. * @returns {promise} A promise which will be notified on each iteration.
  11813. *
  11814. * @example
  11815. * <example module="intervalExample" name="interval-service">
  11816. * <file name="index.html">
  11817. * <script>
  11818. * angular.module('intervalExample', [])
  11819. * .controller('ExampleController', ['$scope', '$interval',
  11820. * function($scope, $interval) {
  11821. * $scope.format = 'M/d/yy h:mm:ss a';
  11822. * $scope.blood_1 = 100;
  11823. * $scope.blood_2 = 120;
  11824. *
  11825. * var stop;
  11826. * $scope.fight = function() {
  11827. * // Don't start a new fight if we are already fighting
  11828. * if ( angular.isDefined(stop) ) return;
  11829. *
  11830. * stop = $interval(function() {
  11831. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  11832. * $scope.blood_1 = $scope.blood_1 - 3;
  11833. * $scope.blood_2 = $scope.blood_2 - 4;
  11834. * } else {
  11835. * $scope.stopFight();
  11836. * }
  11837. * }, 100);
  11838. * };
  11839. *
  11840. * $scope.stopFight = function() {
  11841. * if (angular.isDefined(stop)) {
  11842. * $interval.cancel(stop);
  11843. * stop = undefined;
  11844. * }
  11845. * };
  11846. *
  11847. * $scope.resetFight = function() {
  11848. * $scope.blood_1 = 100;
  11849. * $scope.blood_2 = 120;
  11850. * };
  11851. *
  11852. * $scope.$on('$destroy', function() {
  11853. * // Make sure that the interval is destroyed too
  11854. * $scope.stopFight();
  11855. * });
  11856. * }])
  11857. * // Register the 'myCurrentTime' directive factory method.
  11858. * // We inject $interval and dateFilter service since the factory method is DI.
  11859. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  11860. * function($interval, dateFilter) {
  11861. * // return the directive link function. (compile function not needed)
  11862. * return function(scope, element, attrs) {
  11863. * var format, // date format
  11864. * stopTime; // so that we can cancel the time updates
  11865. *
  11866. * // used to update the UI
  11867. * function updateTime() {
  11868. * element.text(dateFilter(new Date(), format));
  11869. * }
  11870. *
  11871. * // watch the expression, and update the UI on change.
  11872. * scope.$watch(attrs.myCurrentTime, function(value) {
  11873. * format = value;
  11874. * updateTime();
  11875. * });
  11876. *
  11877. * stopTime = $interval(updateTime, 1000);
  11878. *
  11879. * // listen on DOM destroy (removal) event, and cancel the next UI update
  11880. * // to prevent updating time after the DOM element was removed.
  11881. * element.on('$destroy', function() {
  11882. * $interval.cancel(stopTime);
  11883. * });
  11884. * }
  11885. * }]);
  11886. * </script>
  11887. *
  11888. * <div>
  11889. * <div ng-controller="ExampleController">
  11890. * <label>Date format: <input ng-model="format"></label> <hr/>
  11891. * Current time is: <span my-current-time="format"></span>
  11892. * <hr/>
  11893. * Blood 1 : <font color='red'>{{blood_1}}</font>
  11894. * Blood 2 : <font color='red'>{{blood_2}}</font>
  11895. * <button type="button" data-ng-click="fight()">Fight</button>
  11896. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  11897. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  11898. * </div>
  11899. * </div>
  11900. *
  11901. * </file>
  11902. * </example>
  11903. */
  11904. function interval(fn, delay, count, invokeApply) {
  11905. var hasParams = arguments.length > 4,
  11906. args = hasParams ? sliceArgs(arguments, 4) : [],
  11907. setInterval = $window.setInterval,
  11908. clearInterval = $window.clearInterval,
  11909. iteration = 0,
  11910. skipApply = (isDefined(invokeApply) && !invokeApply),
  11911. deferred = (skipApply ? $$q : $q).defer(),
  11912. promise = deferred.promise;
  11913. count = isDefined(count) ? count : 0;
  11914. promise.$$intervalId = setInterval(function tick() {
  11915. if (skipApply) {
  11916. $browser.defer(callback);
  11917. } else {
  11918. $rootScope.$evalAsync(callback);
  11919. }
  11920. deferred.notify(iteration++);
  11921. if (count > 0 && iteration >= count) {
  11922. deferred.resolve(iteration);
  11923. clearInterval(promise.$$intervalId);
  11924. delete intervals[promise.$$intervalId];
  11925. }
  11926. if (!skipApply) $rootScope.$apply();
  11927. }, delay);
  11928. intervals[promise.$$intervalId] = deferred;
  11929. return promise;
  11930. function callback() {
  11931. if (!hasParams) {
  11932. fn(iteration);
  11933. } else {
  11934. fn.apply(null, args);
  11935. }
  11936. }
  11937. }
  11938. /**
  11939. * @ngdoc method
  11940. * @name $interval#cancel
  11941. *
  11942. * @description
  11943. * Cancels a task associated with the `promise`.
  11944. *
  11945. * @param {Promise=} promise returned by the `$interval` function.
  11946. * @returns {boolean} Returns `true` if the task was successfully canceled.
  11947. */
  11948. interval.cancel = function(promise) {
  11949. if (promise && promise.$$intervalId in intervals) {
  11950. // Interval cancels should not report as unhandled promise.
  11951. intervals[promise.$$intervalId].promise.catch(noop);
  11952. intervals[promise.$$intervalId].reject('canceled');
  11953. $window.clearInterval(promise.$$intervalId);
  11954. delete intervals[promise.$$intervalId];
  11955. return true;
  11956. }
  11957. return false;
  11958. };
  11959. return interval;
  11960. }];
  11961. }
  11962. /**
  11963. * @ngdoc service
  11964. * @name $jsonpCallbacks
  11965. * @requires $window
  11966. * @description
  11967. * This service handles the lifecycle of callbacks to handle JSONP requests.
  11968. * Override this service if you wish to customise where the callbacks are stored and
  11969. * how they vary compared to the requested url.
  11970. */
  11971. var $jsonpCallbacksProvider = /** @this */ function() {
  11972. this.$get = function() {
  11973. var callbacks = angular.callbacks;
  11974. var callbackMap = {};
  11975. function createCallback(callbackId) {
  11976. var callback = function(data) {
  11977. callback.data = data;
  11978. callback.called = true;
  11979. };
  11980. callback.id = callbackId;
  11981. return callback;
  11982. }
  11983. return {
  11984. /**
  11985. * @ngdoc method
  11986. * @name $jsonpCallbacks#createCallback
  11987. * @param {string} url the url of the JSONP request
  11988. * @returns {string} the callback path to send to the server as part of the JSONP request
  11989. * @description
  11990. * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
  11991. * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
  11992. */
  11993. createCallback: function(url) {
  11994. var callbackId = '_' + (callbacks.$$counter++).toString(36);
  11995. var callbackPath = 'angular.callbacks.' + callbackId;
  11996. var callback = createCallback(callbackId);
  11997. callbackMap[callbackPath] = callbacks[callbackId] = callback;
  11998. return callbackPath;
  11999. },
  12000. /**
  12001. * @ngdoc method
  12002. * @name $jsonpCallbacks#wasCalled
  12003. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12004. * @returns {boolean} whether the callback has been called, as a result of the JSONP response
  12005. * @description
  12006. * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
  12007. * callback that was passed in the request.
  12008. */
  12009. wasCalled: function(callbackPath) {
  12010. return callbackMap[callbackPath].called;
  12011. },
  12012. /**
  12013. * @ngdoc method
  12014. * @name $jsonpCallbacks#getResponse
  12015. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12016. * @returns {*} the data received from the response via the registered callback
  12017. * @description
  12018. * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
  12019. * in the JSONP response.
  12020. */
  12021. getResponse: function(callbackPath) {
  12022. return callbackMap[callbackPath].data;
  12023. },
  12024. /**
  12025. * @ngdoc method
  12026. * @name $jsonpCallbacks#removeCallback
  12027. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12028. * @description
  12029. * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
  12030. * completed or timed-out.
  12031. */
  12032. removeCallback: function(callbackPath) {
  12033. var callback = callbackMap[callbackPath];
  12034. delete callbacks[callback.id];
  12035. delete callbackMap[callbackPath];
  12036. }
  12037. };
  12038. };
  12039. };
  12040. /**
  12041. * @ngdoc service
  12042. * @name $locale
  12043. *
  12044. * @description
  12045. * $locale service provides localization rules for various Angular components. As of right now the
  12046. * only public api is:
  12047. *
  12048. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  12049. */
  12050. var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
  12051. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  12052. var $locationMinErr = minErr('$location');
  12053. /**
  12054. * Encode path using encodeUriSegment, ignoring forward slashes
  12055. *
  12056. * @param {string} path Path to encode
  12057. * @returns {string}
  12058. */
  12059. function encodePath(path) {
  12060. var segments = path.split('/'),
  12061. i = segments.length;
  12062. while (i--) {
  12063. segments[i] = encodeUriSegment(segments[i]);
  12064. }
  12065. return segments.join('/');
  12066. }
  12067. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  12068. var parsedUrl = urlResolve(absoluteUrl);
  12069. locationObj.$$protocol = parsedUrl.protocol;
  12070. locationObj.$$host = parsedUrl.hostname;
  12071. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  12072. }
  12073. var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
  12074. function parseAppUrl(url, locationObj) {
  12075. if (DOUBLE_SLASH_REGEX.test(url)) {
  12076. throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
  12077. }
  12078. var prefixed = (url.charAt(0) !== '/');
  12079. if (prefixed) {
  12080. url = '/' + url;
  12081. }
  12082. var match = urlResolve(url);
  12083. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  12084. match.pathname.substring(1) : match.pathname);
  12085. locationObj.$$search = parseKeyValue(match.search);
  12086. locationObj.$$hash = decodeURIComponent(match.hash);
  12087. // make sure path starts with '/';
  12088. if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
  12089. locationObj.$$path = '/' + locationObj.$$path;
  12090. }
  12091. }
  12092. function startsWith(str, search) {
  12093. return str.slice(0, search.length) === search;
  12094. }
  12095. /**
  12096. *
  12097. * @param {string} base
  12098. * @param {string} url
  12099. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  12100. * the expected string.
  12101. */
  12102. function stripBaseUrl(base, url) {
  12103. if (startsWith(url, base)) {
  12104. return url.substr(base.length);
  12105. }
  12106. }
  12107. function stripHash(url) {
  12108. var index = url.indexOf('#');
  12109. return index === -1 ? url : url.substr(0, index);
  12110. }
  12111. function trimEmptyHash(url) {
  12112. return url.replace(/(#.+)|#$/, '$1');
  12113. }
  12114. function stripFile(url) {
  12115. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  12116. }
  12117. /* return the server only (scheme://host:port) */
  12118. function serverBase(url) {
  12119. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  12120. }
  12121. /**
  12122. * LocationHtml5Url represents a URL
  12123. * This object is exposed as $location service when HTML5 mode is enabled and supported
  12124. *
  12125. * @constructor
  12126. * @param {string} appBase application base URL
  12127. * @param {string} appBaseNoFile application base URL stripped of any filename
  12128. * @param {string} basePrefix URL path prefix
  12129. */
  12130. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  12131. this.$$html5 = true;
  12132. basePrefix = basePrefix || '';
  12133. parseAbsoluteUrl(appBase, this);
  12134. /**
  12135. * Parse given HTML5 (regular) URL string into properties
  12136. * @param {string} url HTML5 URL
  12137. * @private
  12138. */
  12139. this.$$parse = function(url) {
  12140. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  12141. if (!isString(pathUrl)) {
  12142. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  12143. appBaseNoFile);
  12144. }
  12145. parseAppUrl(pathUrl, this);
  12146. if (!this.$$path) {
  12147. this.$$path = '/';
  12148. }
  12149. this.$$compose();
  12150. };
  12151. /**
  12152. * Compose url and update `absUrl` property
  12153. * @private
  12154. */
  12155. this.$$compose = function() {
  12156. var search = toKeyValue(this.$$search),
  12157. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12158. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12159. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  12160. this.$$urlUpdatedByLocation = true;
  12161. };
  12162. this.$$parseLinkUrl = function(url, relHref) {
  12163. if (relHref && relHref[0] === '#') {
  12164. // special case for links to hash fragments:
  12165. // keep the old url and only replace the hash fragment
  12166. this.hash(relHref.slice(1));
  12167. return true;
  12168. }
  12169. var appUrl, prevAppUrl;
  12170. var rewrittenUrl;
  12171. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  12172. prevAppUrl = appUrl;
  12173. if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  12174. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  12175. } else {
  12176. rewrittenUrl = appBase + prevAppUrl;
  12177. }
  12178. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12179. rewrittenUrl = appBaseNoFile + appUrl;
  12180. } else if (appBaseNoFile === url + '/') {
  12181. rewrittenUrl = appBaseNoFile;
  12182. }
  12183. if (rewrittenUrl) {
  12184. this.$$parse(rewrittenUrl);
  12185. }
  12186. return !!rewrittenUrl;
  12187. };
  12188. }
  12189. /**
  12190. * LocationHashbangUrl represents URL
  12191. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  12192. * It also serves as the base class for html5 mode fallback on legacy browsers.
  12193. *
  12194. * @constructor
  12195. * @param {string} appBase application base URL
  12196. * @param {string} appBaseNoFile application base URL stripped of any filename
  12197. * @param {string} hashPrefix hashbang prefix
  12198. */
  12199. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  12200. parseAbsoluteUrl(appBase, this);
  12201. /**
  12202. * Parse given hashbang URL into properties
  12203. * @param {string} url Hashbang URL
  12204. * @private
  12205. */
  12206. this.$$parse = function(url) {
  12207. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  12208. var withoutHashUrl;
  12209. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  12210. // The rest of the URL starts with a hash so we have
  12211. // got either a hashbang path or a plain hash fragment
  12212. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  12213. if (isUndefined(withoutHashUrl)) {
  12214. // There was no hashbang prefix so we just have a hash fragment
  12215. withoutHashUrl = withoutBaseUrl;
  12216. }
  12217. } else {
  12218. // There was no hashbang path nor hash fragment:
  12219. // If we are in HTML5 mode we use what is left as the path;
  12220. // Otherwise we ignore what is left
  12221. if (this.$$html5) {
  12222. withoutHashUrl = withoutBaseUrl;
  12223. } else {
  12224. withoutHashUrl = '';
  12225. if (isUndefined(withoutBaseUrl)) {
  12226. appBase = url;
  12227. /** @type {?} */ (this).replace();
  12228. }
  12229. }
  12230. }
  12231. parseAppUrl(withoutHashUrl, this);
  12232. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  12233. this.$$compose();
  12234. /*
  12235. * In Windows, on an anchor node on documents loaded from
  12236. * the filesystem, the browser will return a pathname
  12237. * prefixed with the drive name ('/C:/path') when a
  12238. * pathname without a drive is set:
  12239. * * a.setAttribute('href', '/foo')
  12240. * * a.pathname === '/C:/foo' //true
  12241. *
  12242. * Inside of Angular, we're always using pathnames that
  12243. * do not include drive names for routing.
  12244. */
  12245. function removeWindowsDriveName(path, url, base) {
  12246. /*
  12247. Matches paths for file protocol on windows,
  12248. such as /C:/foo/bar, and captures only /foo/bar.
  12249. */
  12250. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  12251. var firstPathSegmentMatch;
  12252. //Get the relative path from the input URL.
  12253. if (startsWith(url, base)) {
  12254. url = url.replace(base, '');
  12255. }
  12256. // The input URL intentionally contains a first path segment that ends with a colon.
  12257. if (windowsFilePathExp.exec(url)) {
  12258. return path;
  12259. }
  12260. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  12261. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  12262. }
  12263. };
  12264. /**
  12265. * Compose hashbang URL and update `absUrl` property
  12266. * @private
  12267. */
  12268. this.$$compose = function() {
  12269. var search = toKeyValue(this.$$search),
  12270. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12271. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12272. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  12273. this.$$urlUpdatedByLocation = true;
  12274. };
  12275. this.$$parseLinkUrl = function(url, relHref) {
  12276. if (stripHash(appBase) === stripHash(url)) {
  12277. this.$$parse(url);
  12278. return true;
  12279. }
  12280. return false;
  12281. };
  12282. }
  12283. /**
  12284. * LocationHashbangUrl represents URL
  12285. * This object is exposed as $location service when html5 history api is enabled but the browser
  12286. * does not support it.
  12287. *
  12288. * @constructor
  12289. * @param {string} appBase application base URL
  12290. * @param {string} appBaseNoFile application base URL stripped of any filename
  12291. * @param {string} hashPrefix hashbang prefix
  12292. */
  12293. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  12294. this.$$html5 = true;
  12295. LocationHashbangUrl.apply(this, arguments);
  12296. this.$$parseLinkUrl = function(url, relHref) {
  12297. if (relHref && relHref[0] === '#') {
  12298. // special case for links to hash fragments:
  12299. // keep the old url and only replace the hash fragment
  12300. this.hash(relHref.slice(1));
  12301. return true;
  12302. }
  12303. var rewrittenUrl;
  12304. var appUrl;
  12305. if (appBase === stripHash(url)) {
  12306. rewrittenUrl = url;
  12307. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12308. rewrittenUrl = appBase + hashPrefix + appUrl;
  12309. } else if (appBaseNoFile === url + '/') {
  12310. rewrittenUrl = appBaseNoFile;
  12311. }
  12312. if (rewrittenUrl) {
  12313. this.$$parse(rewrittenUrl);
  12314. }
  12315. return !!rewrittenUrl;
  12316. };
  12317. this.$$compose = function() {
  12318. var search = toKeyValue(this.$$search),
  12319. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12320. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12321. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  12322. this.$$absUrl = appBase + hashPrefix + this.$$url;
  12323. this.$$urlUpdatedByLocation = true;
  12324. };
  12325. }
  12326. var locationPrototype = {
  12327. /**
  12328. * Ensure absolute URL is initialized.
  12329. * @private
  12330. */
  12331. $$absUrl:'',
  12332. /**
  12333. * Are we in html5 mode?
  12334. * @private
  12335. */
  12336. $$html5: false,
  12337. /**
  12338. * Has any change been replacing?
  12339. * @private
  12340. */
  12341. $$replace: false,
  12342. /**
  12343. * @ngdoc method
  12344. * @name $location#absUrl
  12345. *
  12346. * @description
  12347. * This method is getter only.
  12348. *
  12349. * Return full URL representation with all segments encoded according to rules specified in
  12350. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  12351. *
  12352. *
  12353. * ```js
  12354. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12355. * var absUrl = $location.absUrl();
  12356. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  12357. * ```
  12358. *
  12359. * @return {string} full URL
  12360. */
  12361. absUrl: locationGetter('$$absUrl'),
  12362. /**
  12363. * @ngdoc method
  12364. * @name $location#url
  12365. *
  12366. * @description
  12367. * This method is getter / setter.
  12368. *
  12369. * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
  12370. *
  12371. * Change path, search and hash, when called with parameter and return `$location`.
  12372. *
  12373. *
  12374. * ```js
  12375. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12376. * var url = $location.url();
  12377. * // => "/some/path?foo=bar&baz=xoxo"
  12378. * ```
  12379. *
  12380. * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
  12381. * @return {string} url
  12382. */
  12383. url: function(url) {
  12384. if (isUndefined(url)) {
  12385. return this.$$url;
  12386. }
  12387. var match = PATH_MATCH.exec(url);
  12388. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  12389. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  12390. this.hash(match[5] || '');
  12391. return this;
  12392. },
  12393. /**
  12394. * @ngdoc method
  12395. * @name $location#protocol
  12396. *
  12397. * @description
  12398. * This method is getter only.
  12399. *
  12400. * Return protocol of current URL.
  12401. *
  12402. *
  12403. * ```js
  12404. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12405. * var protocol = $location.protocol();
  12406. * // => "http"
  12407. * ```
  12408. *
  12409. * @return {string} protocol of current URL
  12410. */
  12411. protocol: locationGetter('$$protocol'),
  12412. /**
  12413. * @ngdoc method
  12414. * @name $location#host
  12415. *
  12416. * @description
  12417. * This method is getter only.
  12418. *
  12419. * Return host of current URL.
  12420. *
  12421. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  12422. *
  12423. *
  12424. * ```js
  12425. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12426. * var host = $location.host();
  12427. * // => "example.com"
  12428. *
  12429. * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  12430. * host = $location.host();
  12431. * // => "example.com"
  12432. * host = location.host;
  12433. * // => "example.com:8080"
  12434. * ```
  12435. *
  12436. * @return {string} host of current URL.
  12437. */
  12438. host: locationGetter('$$host'),
  12439. /**
  12440. * @ngdoc method
  12441. * @name $location#port
  12442. *
  12443. * @description
  12444. * This method is getter only.
  12445. *
  12446. * Return port of current URL.
  12447. *
  12448. *
  12449. * ```js
  12450. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12451. * var port = $location.port();
  12452. * // => 80
  12453. * ```
  12454. *
  12455. * @return {Number} port
  12456. */
  12457. port: locationGetter('$$port'),
  12458. /**
  12459. * @ngdoc method
  12460. * @name $location#path
  12461. *
  12462. * @description
  12463. * This method is getter / setter.
  12464. *
  12465. * Return path of current URL when called without any parameter.
  12466. *
  12467. * Change path when called with parameter and return `$location`.
  12468. *
  12469. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  12470. * if it is missing.
  12471. *
  12472. *
  12473. * ```js
  12474. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12475. * var path = $location.path();
  12476. * // => "/some/path"
  12477. * ```
  12478. *
  12479. * @param {(string|number)=} path New path
  12480. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  12481. */
  12482. path: locationGetterSetter('$$path', function(path) {
  12483. path = path !== null ? path.toString() : '';
  12484. return path.charAt(0) === '/' ? path : '/' + path;
  12485. }),
  12486. /**
  12487. * @ngdoc method
  12488. * @name $location#search
  12489. *
  12490. * @description
  12491. * This method is getter / setter.
  12492. *
  12493. * Return search part (as object) of current URL when called without any parameter.
  12494. *
  12495. * Change search part when called with parameter and return `$location`.
  12496. *
  12497. *
  12498. * ```js
  12499. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12500. * var searchObject = $location.search();
  12501. * // => {foo: 'bar', baz: 'xoxo'}
  12502. *
  12503. * // set foo to 'yipee'
  12504. * $location.search('foo', 'yipee');
  12505. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  12506. * ```
  12507. *
  12508. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  12509. * hash object.
  12510. *
  12511. * When called with a single argument the method acts as a setter, setting the `search` component
  12512. * of `$location` to the specified value.
  12513. *
  12514. * If the argument is a hash object containing an array of values, these values will be encoded
  12515. * as duplicate search parameters in the URL.
  12516. *
  12517. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  12518. * will override only a single search property.
  12519. *
  12520. * If `paramValue` is an array, it will override the property of the `search` component of
  12521. * `$location` specified via the first argument.
  12522. *
  12523. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  12524. *
  12525. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  12526. * value nor trailing equal sign.
  12527. *
  12528. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  12529. * one or more arguments returns `$location` object itself.
  12530. */
  12531. search: function(search, paramValue) {
  12532. switch (arguments.length) {
  12533. case 0:
  12534. return this.$$search;
  12535. case 1:
  12536. if (isString(search) || isNumber(search)) {
  12537. search = search.toString();
  12538. this.$$search = parseKeyValue(search);
  12539. } else if (isObject(search)) {
  12540. search = copy(search, {});
  12541. // remove object undefined or null properties
  12542. forEach(search, function(value, key) {
  12543. if (value == null) delete search[key];
  12544. });
  12545. this.$$search = search;
  12546. } else {
  12547. throw $locationMinErr('isrcharg',
  12548. 'The first argument of the `$location#search()` call must be a string or an object.');
  12549. }
  12550. break;
  12551. default:
  12552. if (isUndefined(paramValue) || paramValue === null) {
  12553. delete this.$$search[search];
  12554. } else {
  12555. this.$$search[search] = paramValue;
  12556. }
  12557. }
  12558. this.$$compose();
  12559. return this;
  12560. },
  12561. /**
  12562. * @ngdoc method
  12563. * @name $location#hash
  12564. *
  12565. * @description
  12566. * This method is getter / setter.
  12567. *
  12568. * Returns the hash fragment when called without any parameters.
  12569. *
  12570. * Changes the hash fragment when called with a parameter and returns `$location`.
  12571. *
  12572. *
  12573. * ```js
  12574. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  12575. * var hash = $location.hash();
  12576. * // => "hashValue"
  12577. * ```
  12578. *
  12579. * @param {(string|number)=} hash New hash fragment
  12580. * @return {string} hash
  12581. */
  12582. hash: locationGetterSetter('$$hash', function(hash) {
  12583. return hash !== null ? hash.toString() : '';
  12584. }),
  12585. /**
  12586. * @ngdoc method
  12587. * @name $location#replace
  12588. *
  12589. * @description
  12590. * If called, all changes to $location during the current `$digest` will replace the current history
  12591. * record, instead of adding a new one.
  12592. */
  12593. replace: function() {
  12594. this.$$replace = true;
  12595. return this;
  12596. }
  12597. };
  12598. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  12599. Location.prototype = Object.create(locationPrototype);
  12600. /**
  12601. * @ngdoc method
  12602. * @name $location#state
  12603. *
  12604. * @description
  12605. * This method is getter / setter.
  12606. *
  12607. * Return the history state object when called without any parameter.
  12608. *
  12609. * Change the history state object when called with one parameter and return `$location`.
  12610. * The state object is later passed to `pushState` or `replaceState`.
  12611. *
  12612. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  12613. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  12614. * older browsers (like IE9 or Android < 4.0), don't use this method.
  12615. *
  12616. * @param {object=} state State object for pushState or replaceState
  12617. * @return {object} state
  12618. */
  12619. Location.prototype.state = function(state) {
  12620. if (!arguments.length) {
  12621. return this.$$state;
  12622. }
  12623. if (Location !== LocationHtml5Url || !this.$$html5) {
  12624. throw $locationMinErr('nostate', 'History API state support is available only ' +
  12625. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  12626. }
  12627. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  12628. // but we're changing the $$state reference to $browser.state() during the $digest
  12629. // so the modification window is narrow.
  12630. this.$$state = isUndefined(state) ? null : state;
  12631. this.$$urlUpdatedByLocation = true;
  12632. return this;
  12633. };
  12634. });
  12635. function locationGetter(property) {
  12636. return /** @this */ function() {
  12637. return this[property];
  12638. };
  12639. }
  12640. function locationGetterSetter(property, preprocess) {
  12641. return /** @this */ function(value) {
  12642. if (isUndefined(value)) {
  12643. return this[property];
  12644. }
  12645. this[property] = preprocess(value);
  12646. this.$$compose();
  12647. return this;
  12648. };
  12649. }
  12650. /**
  12651. * @ngdoc service
  12652. * @name $location
  12653. *
  12654. * @requires $rootElement
  12655. *
  12656. * @description
  12657. * The $location service parses the URL in the browser address bar (based on the
  12658. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  12659. * available to your application. Changes to the URL in the address bar are reflected into
  12660. * $location service and changes to $location are reflected into the browser address bar.
  12661. *
  12662. * **The $location service:**
  12663. *
  12664. * - Exposes the current URL in the browser address bar, so you can
  12665. * - Watch and observe the URL.
  12666. * - Change the URL.
  12667. * - Synchronizes the URL with the browser when the user
  12668. * - Changes the address bar.
  12669. * - Clicks the back or forward button (or clicks a History link).
  12670. * - Clicks on a link.
  12671. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  12672. *
  12673. * For more information see {@link guide/$location Developer Guide: Using $location}
  12674. */
  12675. /**
  12676. * @ngdoc provider
  12677. * @name $locationProvider
  12678. * @this
  12679. *
  12680. * @description
  12681. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  12682. */
  12683. function $LocationProvider() {
  12684. var hashPrefix = '!',
  12685. html5Mode = {
  12686. enabled: false,
  12687. requireBase: true,
  12688. rewriteLinks: true
  12689. };
  12690. /**
  12691. * @ngdoc method
  12692. * @name $locationProvider#hashPrefix
  12693. * @description
  12694. * The default value for the prefix is `'!'`.
  12695. * @param {string=} prefix Prefix for hash part (containing path and search)
  12696. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12697. */
  12698. this.hashPrefix = function(prefix) {
  12699. if (isDefined(prefix)) {
  12700. hashPrefix = prefix;
  12701. return this;
  12702. } else {
  12703. return hashPrefix;
  12704. }
  12705. };
  12706. /**
  12707. * @ngdoc method
  12708. * @name $locationProvider#html5Mode
  12709. * @description
  12710. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  12711. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  12712. * properties:
  12713. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  12714. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  12715. * support `pushState`.
  12716. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  12717. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  12718. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  12719. * See the {@link guide/$location $location guide for more information}
  12720. * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
  12721. * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
  12722. * only happen on links with an attribute that matches the given string. For example, if set
  12723. * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
  12724. * Note that [attribute name normalization](guide/directive#normalization) does not apply
  12725. * here, so `'internalLink'` will **not** match `'internal-link'`.
  12726. *
  12727. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  12728. */
  12729. this.html5Mode = function(mode) {
  12730. if (isBoolean(mode)) {
  12731. html5Mode.enabled = mode;
  12732. return this;
  12733. } else if (isObject(mode)) {
  12734. if (isBoolean(mode.enabled)) {
  12735. html5Mode.enabled = mode.enabled;
  12736. }
  12737. if (isBoolean(mode.requireBase)) {
  12738. html5Mode.requireBase = mode.requireBase;
  12739. }
  12740. if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
  12741. html5Mode.rewriteLinks = mode.rewriteLinks;
  12742. }
  12743. return this;
  12744. } else {
  12745. return html5Mode;
  12746. }
  12747. };
  12748. /**
  12749. * @ngdoc event
  12750. * @name $location#$locationChangeStart
  12751. * @eventType broadcast on root scope
  12752. * @description
  12753. * Broadcasted before a URL will change.
  12754. *
  12755. * This change can be prevented by calling
  12756. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  12757. * details about event object. Upon successful change
  12758. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  12759. *
  12760. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12761. * the browser supports the HTML5 History API.
  12762. *
  12763. * @param {Object} angularEvent Synthetic event object.
  12764. * @param {string} newUrl New URL
  12765. * @param {string=} oldUrl URL that was before it was changed.
  12766. * @param {string=} newState New history state object
  12767. * @param {string=} oldState History state object that was before it was changed.
  12768. */
  12769. /**
  12770. * @ngdoc event
  12771. * @name $location#$locationChangeSuccess
  12772. * @eventType broadcast on root scope
  12773. * @description
  12774. * Broadcasted after a URL was changed.
  12775. *
  12776. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12777. * the browser supports the HTML5 History API.
  12778. *
  12779. * @param {Object} angularEvent Synthetic event object.
  12780. * @param {string} newUrl New URL
  12781. * @param {string=} oldUrl URL that was before it was changed.
  12782. * @param {string=} newState New history state object
  12783. * @param {string=} oldState History state object that was before it was changed.
  12784. */
  12785. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  12786. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  12787. var $location,
  12788. LocationMode,
  12789. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  12790. initialUrl = $browser.url(),
  12791. appBase;
  12792. if (html5Mode.enabled) {
  12793. if (!baseHref && html5Mode.requireBase) {
  12794. throw $locationMinErr('nobase',
  12795. '$location in HTML5 mode requires a <base> tag to be present!');
  12796. }
  12797. appBase = serverBase(initialUrl) + (baseHref || '/');
  12798. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  12799. } else {
  12800. appBase = stripHash(initialUrl);
  12801. LocationMode = LocationHashbangUrl;
  12802. }
  12803. var appBaseNoFile = stripFile(appBase);
  12804. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  12805. $location.$$parseLinkUrl(initialUrl, initialUrl);
  12806. $location.$$state = $browser.state();
  12807. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  12808. function setBrowserUrlWithFallback(url, replace, state) {
  12809. var oldUrl = $location.url();
  12810. var oldState = $location.$$state;
  12811. try {
  12812. $browser.url(url, replace, state);
  12813. // Make sure $location.state() returns referentially identical (not just deeply equal)
  12814. // state object; this makes possible quick checking if the state changed in the digest
  12815. // loop. Checking deep equality would be too expensive.
  12816. $location.$$state = $browser.state();
  12817. } catch (e) {
  12818. // Restore old values if pushState fails
  12819. $location.url(oldUrl);
  12820. $location.$$state = oldState;
  12821. throw e;
  12822. }
  12823. }
  12824. $rootElement.on('click', function(event) {
  12825. var rewriteLinks = html5Mode.rewriteLinks;
  12826. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  12827. // currently we open nice url link and redirect then
  12828. if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
  12829. var elm = jqLite(event.target);
  12830. // traverse the DOM up to find first A tag
  12831. while (nodeName_(elm[0]) !== 'a') {
  12832. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  12833. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  12834. }
  12835. if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
  12836. var absHref = elm.prop('href');
  12837. // get the actual href attribute - see
  12838. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  12839. var relHref = elm.attr('href') || elm.attr('xlink:href');
  12840. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  12841. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  12842. // an animation.
  12843. absHref = urlResolve(absHref.animVal).href;
  12844. }
  12845. // Ignore when url is started with javascript: or mailto:
  12846. if (IGNORE_URI_REGEXP.test(absHref)) return;
  12847. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  12848. if ($location.$$parseLinkUrl(absHref, relHref)) {
  12849. // We do a preventDefault for all urls that are part of the angular application,
  12850. // in html5mode and also without, so that we are able to abort navigation without
  12851. // getting double entries in the location history.
  12852. event.preventDefault();
  12853. // update location manually
  12854. if ($location.absUrl() !== $browser.url()) {
  12855. $rootScope.$apply();
  12856. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  12857. $window.angular['ff-684208-preventDefault'] = true;
  12858. }
  12859. }
  12860. }
  12861. });
  12862. // rewrite hashbang url <> html5 url
  12863. if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {
  12864. $browser.url($location.absUrl(), true);
  12865. }
  12866. var initializing = true;
  12867. // update $location when $browser url changes
  12868. $browser.onUrlChange(function(newUrl, newState) {
  12869. if (!startsWith(newUrl, appBaseNoFile)) {
  12870. // If we are navigating outside of the app then force a reload
  12871. $window.location.href = newUrl;
  12872. return;
  12873. }
  12874. $rootScope.$evalAsync(function() {
  12875. var oldUrl = $location.absUrl();
  12876. var oldState = $location.$$state;
  12877. var defaultPrevented;
  12878. newUrl = trimEmptyHash(newUrl);
  12879. $location.$$parse(newUrl);
  12880. $location.$$state = newState;
  12881. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12882. newState, oldState).defaultPrevented;
  12883. // if the location was changed by a `$locationChangeStart` handler then stop
  12884. // processing this location change
  12885. if ($location.absUrl() !== newUrl) return;
  12886. if (defaultPrevented) {
  12887. $location.$$parse(oldUrl);
  12888. $location.$$state = oldState;
  12889. setBrowserUrlWithFallback(oldUrl, false, oldState);
  12890. } else {
  12891. initializing = false;
  12892. afterLocationChange(oldUrl, oldState);
  12893. }
  12894. });
  12895. if (!$rootScope.$$phase) $rootScope.$digest();
  12896. });
  12897. // update browser
  12898. $rootScope.$watch(function $locationWatch() {
  12899. if (initializing || $location.$$urlUpdatedByLocation) {
  12900. $location.$$urlUpdatedByLocation = false;
  12901. var oldUrl = trimEmptyHash($browser.url());
  12902. var newUrl = trimEmptyHash($location.absUrl());
  12903. var oldState = $browser.state();
  12904. var currentReplace = $location.$$replace;
  12905. var urlOrStateChanged = oldUrl !== newUrl ||
  12906. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  12907. if (initializing || urlOrStateChanged) {
  12908. initializing = false;
  12909. $rootScope.$evalAsync(function() {
  12910. var newUrl = $location.absUrl();
  12911. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12912. $location.$$state, oldState).defaultPrevented;
  12913. // if the location was changed by a `$locationChangeStart` handler then stop
  12914. // processing this location change
  12915. if ($location.absUrl() !== newUrl) return;
  12916. if (defaultPrevented) {
  12917. $location.$$parse(oldUrl);
  12918. $location.$$state = oldState;
  12919. } else {
  12920. if (urlOrStateChanged) {
  12921. setBrowserUrlWithFallback(newUrl, currentReplace,
  12922. oldState === $location.$$state ? null : $location.$$state);
  12923. }
  12924. afterLocationChange(oldUrl, oldState);
  12925. }
  12926. });
  12927. }
  12928. }
  12929. $location.$$replace = false;
  12930. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  12931. // there is a change
  12932. });
  12933. return $location;
  12934. function afterLocationChange(oldUrl, oldState) {
  12935. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  12936. $location.$$state, oldState);
  12937. }
  12938. }];
  12939. }
  12940. /**
  12941. * @ngdoc service
  12942. * @name $log
  12943. * @requires $window
  12944. *
  12945. * @description
  12946. * Simple service for logging. Default implementation safely writes the message
  12947. * into the browser's console (if present).
  12948. *
  12949. * The main purpose of this service is to simplify debugging and troubleshooting.
  12950. *
  12951. * The default is to log `debug` messages. You can use
  12952. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  12953. *
  12954. * @example
  12955. <example module="logExample" name="log-service">
  12956. <file name="script.js">
  12957. angular.module('logExample', [])
  12958. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  12959. $scope.$log = $log;
  12960. $scope.message = 'Hello World!';
  12961. }]);
  12962. </file>
  12963. <file name="index.html">
  12964. <div ng-controller="LogController">
  12965. <p>Reload this page with open console, enter text and hit the log button...</p>
  12966. <label>Message:
  12967. <input type="text" ng-model="message" /></label>
  12968. <button ng-click="$log.log(message)">log</button>
  12969. <button ng-click="$log.warn(message)">warn</button>
  12970. <button ng-click="$log.info(message)">info</button>
  12971. <button ng-click="$log.error(message)">error</button>
  12972. <button ng-click="$log.debug(message)">debug</button>
  12973. </div>
  12974. </file>
  12975. </example>
  12976. */
  12977. /**
  12978. * @ngdoc provider
  12979. * @name $logProvider
  12980. * @this
  12981. *
  12982. * @description
  12983. * Use the `$logProvider` to configure how the application logs messages
  12984. */
  12985. function $LogProvider() {
  12986. var debug = true,
  12987. self = this;
  12988. /**
  12989. * @ngdoc method
  12990. * @name $logProvider#debugEnabled
  12991. * @description
  12992. * @param {boolean=} flag enable or disable debug level messages
  12993. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12994. */
  12995. this.debugEnabled = function(flag) {
  12996. if (isDefined(flag)) {
  12997. debug = flag;
  12998. return this;
  12999. } else {
  13000. return debug;
  13001. }
  13002. };
  13003. this.$get = ['$window', function($window) {
  13004. // Support: IE 9-11, Edge 12-14+
  13005. // IE/Edge display errors in such a way that it requires the user to click in 4 places
  13006. // to see the stack trace. There is no way to feature-detect it so there's a chance
  13007. // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't
  13008. // break apps. Other browsers display errors in a sensible way and some of them map stack
  13009. // traces along source maps if available so it makes sense to let browsers display it
  13010. // as they want.
  13011. var formatStackTrace = msie || /\bEdge\//.test($window.navigator && $window.navigator.userAgent);
  13012. return {
  13013. /**
  13014. * @ngdoc method
  13015. * @name $log#log
  13016. *
  13017. * @description
  13018. * Write a log message
  13019. */
  13020. log: consoleLog('log'),
  13021. /**
  13022. * @ngdoc method
  13023. * @name $log#info
  13024. *
  13025. * @description
  13026. * Write an information message
  13027. */
  13028. info: consoleLog('info'),
  13029. /**
  13030. * @ngdoc method
  13031. * @name $log#warn
  13032. *
  13033. * @description
  13034. * Write a warning message
  13035. */
  13036. warn: consoleLog('warn'),
  13037. /**
  13038. * @ngdoc method
  13039. * @name $log#error
  13040. *
  13041. * @description
  13042. * Write an error message
  13043. */
  13044. error: consoleLog('error'),
  13045. /**
  13046. * @ngdoc method
  13047. * @name $log#debug
  13048. *
  13049. * @description
  13050. * Write a debug message
  13051. */
  13052. debug: (function() {
  13053. var fn = consoleLog('debug');
  13054. return function() {
  13055. if (debug) {
  13056. fn.apply(self, arguments);
  13057. }
  13058. };
  13059. })()
  13060. };
  13061. function formatError(arg) {
  13062. if (arg instanceof Error) {
  13063. if (arg.stack && formatStackTrace) {
  13064. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  13065. ? 'Error: ' + arg.message + '\n' + arg.stack
  13066. : arg.stack;
  13067. } else if (arg.sourceURL) {
  13068. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  13069. }
  13070. }
  13071. return arg;
  13072. }
  13073. function consoleLog(type) {
  13074. var console = $window.console || {},
  13075. logFn = console[type] || console.log || noop,
  13076. hasApply = false;
  13077. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  13078. // The reason behind this is that console.log has type "object" in IE8...
  13079. try {
  13080. hasApply = !!logFn.apply;
  13081. } catch (e) { /* empty */ }
  13082. if (hasApply) {
  13083. return function() {
  13084. var args = [];
  13085. forEach(arguments, function(arg) {
  13086. args.push(formatError(arg));
  13087. });
  13088. return logFn.apply(console, args);
  13089. };
  13090. }
  13091. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  13092. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  13093. return function(arg1, arg2) {
  13094. logFn(arg1, arg2 == null ? '' : arg2);
  13095. };
  13096. }
  13097. }];
  13098. }
  13099. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  13100. * Any commits to this file should be reviewed with security in mind. *
  13101. * Changes to this file can potentially create security vulnerabilities. *
  13102. * An approval from 2 Core members with history of modifying *
  13103. * this file is required. *
  13104. * *
  13105. * Does the change somehow allow for arbitrary javascript to be executed? *
  13106. * Or allows for someone to change the prototype of built-in objects? *
  13107. * Or gives undesired access to variables likes document or window? *
  13108. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  13109. var $parseMinErr = minErr('$parse');
  13110. var objectValueOf = {}.constructor.prototype.valueOf;
  13111. // Sandboxing Angular Expressions
  13112. // ------------------------------
  13113. // Angular expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by
  13114. // various means such as obtaining a reference to native JS functions like the Function constructor.
  13115. //
  13116. // As an example, consider the following Angular expression:
  13117. //
  13118. // {}.toString.constructor('alert("evil JS code")')
  13119. //
  13120. // It is important to realize that if you create an expression from a string that contains user provided
  13121. // content then it is possible that your application contains a security vulnerability to an XSS style attack.
  13122. //
  13123. // See https://docs.angularjs.org/guide/security
  13124. function getStringValue(name) {
  13125. // Property names must be strings. This means that non-string objects cannot be used
  13126. // as keys in an object. Any non-string object, including a number, is typecasted
  13127. // into a string via the toString method.
  13128. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  13129. //
  13130. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  13131. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  13132. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  13133. //
  13134. // TypeError: Cannot convert object to primitive value
  13135. //
  13136. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  13137. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  13138. // such a 'broken' object as a key.
  13139. return name + '';
  13140. }
  13141. var OPERATORS = createMap();
  13142. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  13143. var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
  13144. /////////////////////////////////////////
  13145. /**
  13146. * @constructor
  13147. */
  13148. var Lexer = function Lexer(options) {
  13149. this.options = options;
  13150. };
  13151. Lexer.prototype = {
  13152. constructor: Lexer,
  13153. lex: function(text) {
  13154. this.text = text;
  13155. this.index = 0;
  13156. this.tokens = [];
  13157. while (this.index < this.text.length) {
  13158. var ch = this.text.charAt(this.index);
  13159. if (ch === '"' || ch === '\'') {
  13160. this.readString(ch);
  13161. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  13162. this.readNumber();
  13163. } else if (this.isIdentifierStart(this.peekMultichar())) {
  13164. this.readIdent();
  13165. } else if (this.is(ch, '(){}[].,;:?')) {
  13166. this.tokens.push({index: this.index, text: ch});
  13167. this.index++;
  13168. } else if (this.isWhitespace(ch)) {
  13169. this.index++;
  13170. } else {
  13171. var ch2 = ch + this.peek();
  13172. var ch3 = ch2 + this.peek(2);
  13173. var op1 = OPERATORS[ch];
  13174. var op2 = OPERATORS[ch2];
  13175. var op3 = OPERATORS[ch3];
  13176. if (op1 || op2 || op3) {
  13177. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  13178. this.tokens.push({index: this.index, text: token, operator: true});
  13179. this.index += token.length;
  13180. } else {
  13181. this.throwError('Unexpected next character ', this.index, this.index + 1);
  13182. }
  13183. }
  13184. }
  13185. return this.tokens;
  13186. },
  13187. is: function(ch, chars) {
  13188. return chars.indexOf(ch) !== -1;
  13189. },
  13190. peek: function(i) {
  13191. var num = i || 1;
  13192. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  13193. },
  13194. isNumber: function(ch) {
  13195. return ('0' <= ch && ch <= '9') && typeof ch === 'string';
  13196. },
  13197. isWhitespace: function(ch) {
  13198. // IE treats non-breaking space as \u00A0
  13199. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  13200. ch === '\n' || ch === '\v' || ch === '\u00A0');
  13201. },
  13202. isIdentifierStart: function(ch) {
  13203. return this.options.isIdentifierStart ?
  13204. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  13205. this.isValidIdentifierStart(ch);
  13206. },
  13207. isValidIdentifierStart: function(ch) {
  13208. return ('a' <= ch && ch <= 'z' ||
  13209. 'A' <= ch && ch <= 'Z' ||
  13210. '_' === ch || ch === '$');
  13211. },
  13212. isIdentifierContinue: function(ch) {
  13213. return this.options.isIdentifierContinue ?
  13214. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  13215. this.isValidIdentifierContinue(ch);
  13216. },
  13217. isValidIdentifierContinue: function(ch, cp) {
  13218. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  13219. },
  13220. codePointAt: function(ch) {
  13221. if (ch.length === 1) return ch.charCodeAt(0);
  13222. // eslint-disable-next-line no-bitwise
  13223. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  13224. },
  13225. peekMultichar: function() {
  13226. var ch = this.text.charAt(this.index);
  13227. var peek = this.peek();
  13228. if (!peek) {
  13229. return ch;
  13230. }
  13231. var cp1 = ch.charCodeAt(0);
  13232. var cp2 = peek.charCodeAt(0);
  13233. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  13234. return ch + peek;
  13235. }
  13236. return ch;
  13237. },
  13238. isExpOperator: function(ch) {
  13239. return (ch === '-' || ch === '+' || this.isNumber(ch));
  13240. },
  13241. throwError: function(error, start, end) {
  13242. end = end || this.index;
  13243. var colStr = (isDefined(start)
  13244. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  13245. : ' ' + end);
  13246. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  13247. error, colStr, this.text);
  13248. },
  13249. readNumber: function() {
  13250. var number = '';
  13251. var start = this.index;
  13252. while (this.index < this.text.length) {
  13253. var ch = lowercase(this.text.charAt(this.index));
  13254. if (ch === '.' || this.isNumber(ch)) {
  13255. number += ch;
  13256. } else {
  13257. var peekCh = this.peek();
  13258. if (ch === 'e' && this.isExpOperator(peekCh)) {
  13259. number += ch;
  13260. } else if (this.isExpOperator(ch) &&
  13261. peekCh && this.isNumber(peekCh) &&
  13262. number.charAt(number.length - 1) === 'e') {
  13263. number += ch;
  13264. } else if (this.isExpOperator(ch) &&
  13265. (!peekCh || !this.isNumber(peekCh)) &&
  13266. number.charAt(number.length - 1) === 'e') {
  13267. this.throwError('Invalid exponent');
  13268. } else {
  13269. break;
  13270. }
  13271. }
  13272. this.index++;
  13273. }
  13274. this.tokens.push({
  13275. index: start,
  13276. text: number,
  13277. constant: true,
  13278. value: Number(number)
  13279. });
  13280. },
  13281. readIdent: function() {
  13282. var start = this.index;
  13283. this.index += this.peekMultichar().length;
  13284. while (this.index < this.text.length) {
  13285. var ch = this.peekMultichar();
  13286. if (!this.isIdentifierContinue(ch)) {
  13287. break;
  13288. }
  13289. this.index += ch.length;
  13290. }
  13291. this.tokens.push({
  13292. index: start,
  13293. text: this.text.slice(start, this.index),
  13294. identifier: true
  13295. });
  13296. },
  13297. readString: function(quote) {
  13298. var start = this.index;
  13299. this.index++;
  13300. var string = '';
  13301. var rawString = quote;
  13302. var escape = false;
  13303. while (this.index < this.text.length) {
  13304. var ch = this.text.charAt(this.index);
  13305. rawString += ch;
  13306. if (escape) {
  13307. if (ch === 'u') {
  13308. var hex = this.text.substring(this.index + 1, this.index + 5);
  13309. if (!hex.match(/[\da-f]{4}/i)) {
  13310. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  13311. }
  13312. this.index += 4;
  13313. string += String.fromCharCode(parseInt(hex, 16));
  13314. } else {
  13315. var rep = ESCAPE[ch];
  13316. string = string + (rep || ch);
  13317. }
  13318. escape = false;
  13319. } else if (ch === '\\') {
  13320. escape = true;
  13321. } else if (ch === quote) {
  13322. this.index++;
  13323. this.tokens.push({
  13324. index: start,
  13325. text: rawString,
  13326. constant: true,
  13327. value: string
  13328. });
  13329. return;
  13330. } else {
  13331. string += ch;
  13332. }
  13333. this.index++;
  13334. }
  13335. this.throwError('Unterminated quote', start);
  13336. }
  13337. };
  13338. var AST = function AST(lexer, options) {
  13339. this.lexer = lexer;
  13340. this.options = options;
  13341. };
  13342. AST.Program = 'Program';
  13343. AST.ExpressionStatement = 'ExpressionStatement';
  13344. AST.AssignmentExpression = 'AssignmentExpression';
  13345. AST.ConditionalExpression = 'ConditionalExpression';
  13346. AST.LogicalExpression = 'LogicalExpression';
  13347. AST.BinaryExpression = 'BinaryExpression';
  13348. AST.UnaryExpression = 'UnaryExpression';
  13349. AST.CallExpression = 'CallExpression';
  13350. AST.MemberExpression = 'MemberExpression';
  13351. AST.Identifier = 'Identifier';
  13352. AST.Literal = 'Literal';
  13353. AST.ArrayExpression = 'ArrayExpression';
  13354. AST.Property = 'Property';
  13355. AST.ObjectExpression = 'ObjectExpression';
  13356. AST.ThisExpression = 'ThisExpression';
  13357. AST.LocalsExpression = 'LocalsExpression';
  13358. // Internal use only
  13359. AST.NGValueParameter = 'NGValueParameter';
  13360. AST.prototype = {
  13361. ast: function(text) {
  13362. this.text = text;
  13363. this.tokens = this.lexer.lex(text);
  13364. var value = this.program();
  13365. if (this.tokens.length !== 0) {
  13366. this.throwError('is an unexpected token', this.tokens[0]);
  13367. }
  13368. return value;
  13369. },
  13370. program: function() {
  13371. var body = [];
  13372. while (true) {
  13373. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  13374. body.push(this.expressionStatement());
  13375. if (!this.expect(';')) {
  13376. return { type: AST.Program, body: body};
  13377. }
  13378. }
  13379. },
  13380. expressionStatement: function() {
  13381. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  13382. },
  13383. filterChain: function() {
  13384. var left = this.expression();
  13385. while (this.expect('|')) {
  13386. left = this.filter(left);
  13387. }
  13388. return left;
  13389. },
  13390. expression: function() {
  13391. return this.assignment();
  13392. },
  13393. assignment: function() {
  13394. var result = this.ternary();
  13395. if (this.expect('=')) {
  13396. if (!isAssignable(result)) {
  13397. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  13398. }
  13399. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  13400. }
  13401. return result;
  13402. },
  13403. ternary: function() {
  13404. var test = this.logicalOR();
  13405. var alternate;
  13406. var consequent;
  13407. if (this.expect('?')) {
  13408. alternate = this.expression();
  13409. if (this.consume(':')) {
  13410. consequent = this.expression();
  13411. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  13412. }
  13413. }
  13414. return test;
  13415. },
  13416. logicalOR: function() {
  13417. var left = this.logicalAND();
  13418. while (this.expect('||')) {
  13419. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  13420. }
  13421. return left;
  13422. },
  13423. logicalAND: function() {
  13424. var left = this.equality();
  13425. while (this.expect('&&')) {
  13426. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  13427. }
  13428. return left;
  13429. },
  13430. equality: function() {
  13431. var left = this.relational();
  13432. var token;
  13433. while ((token = this.expect('==','!=','===','!=='))) {
  13434. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  13435. }
  13436. return left;
  13437. },
  13438. relational: function() {
  13439. var left = this.additive();
  13440. var token;
  13441. while ((token = this.expect('<', '>', '<=', '>='))) {
  13442. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  13443. }
  13444. return left;
  13445. },
  13446. additive: function() {
  13447. var left = this.multiplicative();
  13448. var token;
  13449. while ((token = this.expect('+','-'))) {
  13450. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  13451. }
  13452. return left;
  13453. },
  13454. multiplicative: function() {
  13455. var left = this.unary();
  13456. var token;
  13457. while ((token = this.expect('*','/','%'))) {
  13458. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  13459. }
  13460. return left;
  13461. },
  13462. unary: function() {
  13463. var token;
  13464. if ((token = this.expect('+', '-', '!'))) {
  13465. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  13466. } else {
  13467. return this.primary();
  13468. }
  13469. },
  13470. primary: function() {
  13471. var primary;
  13472. if (this.expect('(')) {
  13473. primary = this.filterChain();
  13474. this.consume(')');
  13475. } else if (this.expect('[')) {
  13476. primary = this.arrayDeclaration();
  13477. } else if (this.expect('{')) {
  13478. primary = this.object();
  13479. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  13480. primary = copy(this.selfReferential[this.consume().text]);
  13481. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  13482. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  13483. } else if (this.peek().identifier) {
  13484. primary = this.identifier();
  13485. } else if (this.peek().constant) {
  13486. primary = this.constant();
  13487. } else {
  13488. this.throwError('not a primary expression', this.peek());
  13489. }
  13490. var next;
  13491. while ((next = this.expect('(', '[', '.'))) {
  13492. if (next.text === '(') {
  13493. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  13494. this.consume(')');
  13495. } else if (next.text === '[') {
  13496. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  13497. this.consume(']');
  13498. } else if (next.text === '.') {
  13499. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  13500. } else {
  13501. this.throwError('IMPOSSIBLE');
  13502. }
  13503. }
  13504. return primary;
  13505. },
  13506. filter: function(baseExpression) {
  13507. var args = [baseExpression];
  13508. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  13509. while (this.expect(':')) {
  13510. args.push(this.expression());
  13511. }
  13512. return result;
  13513. },
  13514. parseArguments: function() {
  13515. var args = [];
  13516. if (this.peekToken().text !== ')') {
  13517. do {
  13518. args.push(this.filterChain());
  13519. } while (this.expect(','));
  13520. }
  13521. return args;
  13522. },
  13523. identifier: function() {
  13524. var token = this.consume();
  13525. if (!token.identifier) {
  13526. this.throwError('is not a valid identifier', token);
  13527. }
  13528. return { type: AST.Identifier, name: token.text };
  13529. },
  13530. constant: function() {
  13531. // TODO check that it is a constant
  13532. return { type: AST.Literal, value: this.consume().value };
  13533. },
  13534. arrayDeclaration: function() {
  13535. var elements = [];
  13536. if (this.peekToken().text !== ']') {
  13537. do {
  13538. if (this.peek(']')) {
  13539. // Support trailing commas per ES5.1.
  13540. break;
  13541. }
  13542. elements.push(this.expression());
  13543. } while (this.expect(','));
  13544. }
  13545. this.consume(']');
  13546. return { type: AST.ArrayExpression, elements: elements };
  13547. },
  13548. object: function() {
  13549. var properties = [], property;
  13550. if (this.peekToken().text !== '}') {
  13551. do {
  13552. if (this.peek('}')) {
  13553. // Support trailing commas per ES5.1.
  13554. break;
  13555. }
  13556. property = {type: AST.Property, kind: 'init'};
  13557. if (this.peek().constant) {
  13558. property.key = this.constant();
  13559. property.computed = false;
  13560. this.consume(':');
  13561. property.value = this.expression();
  13562. } else if (this.peek().identifier) {
  13563. property.key = this.identifier();
  13564. property.computed = false;
  13565. if (this.peek(':')) {
  13566. this.consume(':');
  13567. property.value = this.expression();
  13568. } else {
  13569. property.value = property.key;
  13570. }
  13571. } else if (this.peek('[')) {
  13572. this.consume('[');
  13573. property.key = this.expression();
  13574. this.consume(']');
  13575. property.computed = true;
  13576. this.consume(':');
  13577. property.value = this.expression();
  13578. } else {
  13579. this.throwError('invalid key', this.peek());
  13580. }
  13581. properties.push(property);
  13582. } while (this.expect(','));
  13583. }
  13584. this.consume('}');
  13585. return {type: AST.ObjectExpression, properties: properties };
  13586. },
  13587. throwError: function(msg, token) {
  13588. throw $parseMinErr('syntax',
  13589. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  13590. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  13591. },
  13592. consume: function(e1) {
  13593. if (this.tokens.length === 0) {
  13594. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13595. }
  13596. var token = this.expect(e1);
  13597. if (!token) {
  13598. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  13599. }
  13600. return token;
  13601. },
  13602. peekToken: function() {
  13603. if (this.tokens.length === 0) {
  13604. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13605. }
  13606. return this.tokens[0];
  13607. },
  13608. peek: function(e1, e2, e3, e4) {
  13609. return this.peekAhead(0, e1, e2, e3, e4);
  13610. },
  13611. peekAhead: function(i, e1, e2, e3, e4) {
  13612. if (this.tokens.length > i) {
  13613. var token = this.tokens[i];
  13614. var t = token.text;
  13615. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  13616. (!e1 && !e2 && !e3 && !e4)) {
  13617. return token;
  13618. }
  13619. }
  13620. return false;
  13621. },
  13622. expect: function(e1, e2, e3, e4) {
  13623. var token = this.peek(e1, e2, e3, e4);
  13624. if (token) {
  13625. this.tokens.shift();
  13626. return token;
  13627. }
  13628. return false;
  13629. },
  13630. selfReferential: {
  13631. 'this': {type: AST.ThisExpression },
  13632. '$locals': {type: AST.LocalsExpression }
  13633. }
  13634. };
  13635. function ifDefined(v, d) {
  13636. return typeof v !== 'undefined' ? v : d;
  13637. }
  13638. function plusFn(l, r) {
  13639. if (typeof l === 'undefined') return r;
  13640. if (typeof r === 'undefined') return l;
  13641. return l + r;
  13642. }
  13643. function isStateless($filter, filterName) {
  13644. var fn = $filter(filterName);
  13645. return !fn.$stateful;
  13646. }
  13647. function findConstantAndWatchExpressions(ast, $filter) {
  13648. var allConstants;
  13649. var argsToWatch;
  13650. var isStatelessFilter;
  13651. switch (ast.type) {
  13652. case AST.Program:
  13653. allConstants = true;
  13654. forEach(ast.body, function(expr) {
  13655. findConstantAndWatchExpressions(expr.expression, $filter);
  13656. allConstants = allConstants && expr.expression.constant;
  13657. });
  13658. ast.constant = allConstants;
  13659. break;
  13660. case AST.Literal:
  13661. ast.constant = true;
  13662. ast.toWatch = [];
  13663. break;
  13664. case AST.UnaryExpression:
  13665. findConstantAndWatchExpressions(ast.argument, $filter);
  13666. ast.constant = ast.argument.constant;
  13667. ast.toWatch = ast.argument.toWatch;
  13668. break;
  13669. case AST.BinaryExpression:
  13670. findConstantAndWatchExpressions(ast.left, $filter);
  13671. findConstantAndWatchExpressions(ast.right, $filter);
  13672. ast.constant = ast.left.constant && ast.right.constant;
  13673. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  13674. break;
  13675. case AST.LogicalExpression:
  13676. findConstantAndWatchExpressions(ast.left, $filter);
  13677. findConstantAndWatchExpressions(ast.right, $filter);
  13678. ast.constant = ast.left.constant && ast.right.constant;
  13679. ast.toWatch = ast.constant ? [] : [ast];
  13680. break;
  13681. case AST.ConditionalExpression:
  13682. findConstantAndWatchExpressions(ast.test, $filter);
  13683. findConstantAndWatchExpressions(ast.alternate, $filter);
  13684. findConstantAndWatchExpressions(ast.consequent, $filter);
  13685. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  13686. ast.toWatch = ast.constant ? [] : [ast];
  13687. break;
  13688. case AST.Identifier:
  13689. ast.constant = false;
  13690. ast.toWatch = [ast];
  13691. break;
  13692. case AST.MemberExpression:
  13693. findConstantAndWatchExpressions(ast.object, $filter);
  13694. if (ast.computed) {
  13695. findConstantAndWatchExpressions(ast.property, $filter);
  13696. }
  13697. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  13698. ast.toWatch = [ast];
  13699. break;
  13700. case AST.CallExpression:
  13701. isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
  13702. allConstants = isStatelessFilter;
  13703. argsToWatch = [];
  13704. forEach(ast.arguments, function(expr) {
  13705. findConstantAndWatchExpressions(expr, $filter);
  13706. allConstants = allConstants && expr.constant;
  13707. if (!expr.constant) {
  13708. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13709. }
  13710. });
  13711. ast.constant = allConstants;
  13712. ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
  13713. break;
  13714. case AST.AssignmentExpression:
  13715. findConstantAndWatchExpressions(ast.left, $filter);
  13716. findConstantAndWatchExpressions(ast.right, $filter);
  13717. ast.constant = ast.left.constant && ast.right.constant;
  13718. ast.toWatch = [ast];
  13719. break;
  13720. case AST.ArrayExpression:
  13721. allConstants = true;
  13722. argsToWatch = [];
  13723. forEach(ast.elements, function(expr) {
  13724. findConstantAndWatchExpressions(expr, $filter);
  13725. allConstants = allConstants && expr.constant;
  13726. if (!expr.constant) {
  13727. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13728. }
  13729. });
  13730. ast.constant = allConstants;
  13731. ast.toWatch = argsToWatch;
  13732. break;
  13733. case AST.ObjectExpression:
  13734. allConstants = true;
  13735. argsToWatch = [];
  13736. forEach(ast.properties, function(property) {
  13737. findConstantAndWatchExpressions(property.value, $filter);
  13738. allConstants = allConstants && property.value.constant && !property.computed;
  13739. if (!property.value.constant) {
  13740. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  13741. }
  13742. if (property.computed) {
  13743. findConstantAndWatchExpressions(property.key, $filter);
  13744. if (!property.key.constant) {
  13745. argsToWatch.push.apply(argsToWatch, property.key.toWatch);
  13746. }
  13747. }
  13748. });
  13749. ast.constant = allConstants;
  13750. ast.toWatch = argsToWatch;
  13751. break;
  13752. case AST.ThisExpression:
  13753. ast.constant = false;
  13754. ast.toWatch = [];
  13755. break;
  13756. case AST.LocalsExpression:
  13757. ast.constant = false;
  13758. ast.toWatch = [];
  13759. break;
  13760. }
  13761. }
  13762. function getInputs(body) {
  13763. if (body.length !== 1) return;
  13764. var lastExpression = body[0].expression;
  13765. var candidate = lastExpression.toWatch;
  13766. if (candidate.length !== 1) return candidate;
  13767. return candidate[0] !== lastExpression ? candidate : undefined;
  13768. }
  13769. function isAssignable(ast) {
  13770. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  13771. }
  13772. function assignableAST(ast) {
  13773. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  13774. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  13775. }
  13776. }
  13777. function isLiteral(ast) {
  13778. return ast.body.length === 0 ||
  13779. ast.body.length === 1 && (
  13780. ast.body[0].expression.type === AST.Literal ||
  13781. ast.body[0].expression.type === AST.ArrayExpression ||
  13782. ast.body[0].expression.type === AST.ObjectExpression);
  13783. }
  13784. function isConstant(ast) {
  13785. return ast.constant;
  13786. }
  13787. function ASTCompiler(astBuilder, $filter) {
  13788. this.astBuilder = astBuilder;
  13789. this.$filter = $filter;
  13790. }
  13791. ASTCompiler.prototype = {
  13792. compile: function(expression) {
  13793. var self = this;
  13794. var ast = this.astBuilder.ast(expression);
  13795. this.state = {
  13796. nextId: 0,
  13797. filters: {},
  13798. fn: {vars: [], body: [], own: {}},
  13799. assign: {vars: [], body: [], own: {}},
  13800. inputs: []
  13801. };
  13802. findConstantAndWatchExpressions(ast, self.$filter);
  13803. var extra = '';
  13804. var assignable;
  13805. this.stage = 'assign';
  13806. if ((assignable = assignableAST(ast))) {
  13807. this.state.computing = 'assign';
  13808. var result = this.nextId();
  13809. this.recurse(assignable, result);
  13810. this.return_(result);
  13811. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  13812. }
  13813. var toWatch = getInputs(ast.body);
  13814. self.stage = 'inputs';
  13815. forEach(toWatch, function(watch, key) {
  13816. var fnKey = 'fn' + key;
  13817. self.state[fnKey] = {vars: [], body: [], own: {}};
  13818. self.state.computing = fnKey;
  13819. var intoId = self.nextId();
  13820. self.recurse(watch, intoId);
  13821. self.return_(intoId);
  13822. self.state.inputs.push(fnKey);
  13823. watch.watchId = key;
  13824. });
  13825. this.state.computing = 'fn';
  13826. this.stage = 'main';
  13827. this.recurse(ast);
  13828. var fnString =
  13829. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  13830. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  13831. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  13832. this.filterPrefix() +
  13833. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  13834. extra +
  13835. this.watchFns() +
  13836. 'return fn;';
  13837. // eslint-disable-next-line no-new-func
  13838. var fn = (new Function('$filter',
  13839. 'getStringValue',
  13840. 'ifDefined',
  13841. 'plus',
  13842. fnString))(
  13843. this.$filter,
  13844. getStringValue,
  13845. ifDefined,
  13846. plusFn);
  13847. this.state = this.stage = undefined;
  13848. fn.literal = isLiteral(ast);
  13849. fn.constant = isConstant(ast);
  13850. return fn;
  13851. },
  13852. USE: 'use',
  13853. STRICT: 'strict',
  13854. watchFns: function() {
  13855. var result = [];
  13856. var fns = this.state.inputs;
  13857. var self = this;
  13858. forEach(fns, function(name) {
  13859. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  13860. });
  13861. if (fns.length) {
  13862. result.push('fn.inputs=[' + fns.join(',') + '];');
  13863. }
  13864. return result.join('');
  13865. },
  13866. generateFunction: function(name, params) {
  13867. return 'function(' + params + '){' +
  13868. this.varsPrefix(name) +
  13869. this.body(name) +
  13870. '};';
  13871. },
  13872. filterPrefix: function() {
  13873. var parts = [];
  13874. var self = this;
  13875. forEach(this.state.filters, function(id, filter) {
  13876. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  13877. });
  13878. if (parts.length) return 'var ' + parts.join(',') + ';';
  13879. return '';
  13880. },
  13881. varsPrefix: function(section) {
  13882. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  13883. },
  13884. body: function(section) {
  13885. return this.state[section].body.join('');
  13886. },
  13887. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  13888. var left, right, self = this, args, expression, computed;
  13889. recursionFn = recursionFn || noop;
  13890. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  13891. intoId = intoId || this.nextId();
  13892. this.if_('i',
  13893. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  13894. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  13895. );
  13896. return;
  13897. }
  13898. switch (ast.type) {
  13899. case AST.Program:
  13900. forEach(ast.body, function(expression, pos) {
  13901. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  13902. if (pos !== ast.body.length - 1) {
  13903. self.current().body.push(right, ';');
  13904. } else {
  13905. self.return_(right);
  13906. }
  13907. });
  13908. break;
  13909. case AST.Literal:
  13910. expression = this.escape(ast.value);
  13911. this.assign(intoId, expression);
  13912. recursionFn(intoId || expression);
  13913. break;
  13914. case AST.UnaryExpression:
  13915. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  13916. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  13917. this.assign(intoId, expression);
  13918. recursionFn(expression);
  13919. break;
  13920. case AST.BinaryExpression:
  13921. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  13922. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  13923. if (ast.operator === '+') {
  13924. expression = this.plus(left, right);
  13925. } else if (ast.operator === '-') {
  13926. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  13927. } else {
  13928. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  13929. }
  13930. this.assign(intoId, expression);
  13931. recursionFn(expression);
  13932. break;
  13933. case AST.LogicalExpression:
  13934. intoId = intoId || this.nextId();
  13935. self.recurse(ast.left, intoId);
  13936. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  13937. recursionFn(intoId);
  13938. break;
  13939. case AST.ConditionalExpression:
  13940. intoId = intoId || this.nextId();
  13941. self.recurse(ast.test, intoId);
  13942. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  13943. recursionFn(intoId);
  13944. break;
  13945. case AST.Identifier:
  13946. intoId = intoId || this.nextId();
  13947. if (nameId) {
  13948. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  13949. nameId.computed = false;
  13950. nameId.name = ast.name;
  13951. }
  13952. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  13953. function() {
  13954. self.if_(self.stage === 'inputs' || 's', function() {
  13955. if (create && create !== 1) {
  13956. self.if_(
  13957. self.isNull(self.nonComputedMember('s', ast.name)),
  13958. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  13959. }
  13960. self.assign(intoId, self.nonComputedMember('s', ast.name));
  13961. });
  13962. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  13963. );
  13964. recursionFn(intoId);
  13965. break;
  13966. case AST.MemberExpression:
  13967. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  13968. intoId = intoId || this.nextId();
  13969. self.recurse(ast.object, left, undefined, function() {
  13970. self.if_(self.notNull(left), function() {
  13971. if (ast.computed) {
  13972. right = self.nextId();
  13973. self.recurse(ast.property, right);
  13974. self.getStringValue(right);
  13975. if (create && create !== 1) {
  13976. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  13977. }
  13978. expression = self.computedMember(left, right);
  13979. self.assign(intoId, expression);
  13980. if (nameId) {
  13981. nameId.computed = true;
  13982. nameId.name = right;
  13983. }
  13984. } else {
  13985. if (create && create !== 1) {
  13986. self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  13987. }
  13988. expression = self.nonComputedMember(left, ast.property.name);
  13989. self.assign(intoId, expression);
  13990. if (nameId) {
  13991. nameId.computed = false;
  13992. nameId.name = ast.property.name;
  13993. }
  13994. }
  13995. }, function() {
  13996. self.assign(intoId, 'undefined');
  13997. });
  13998. recursionFn(intoId);
  13999. }, !!create);
  14000. break;
  14001. case AST.CallExpression:
  14002. intoId = intoId || this.nextId();
  14003. if (ast.filter) {
  14004. right = self.filter(ast.callee.name);
  14005. args = [];
  14006. forEach(ast.arguments, function(expr) {
  14007. var argument = self.nextId();
  14008. self.recurse(expr, argument);
  14009. args.push(argument);
  14010. });
  14011. expression = right + '(' + args.join(',') + ')';
  14012. self.assign(intoId, expression);
  14013. recursionFn(intoId);
  14014. } else {
  14015. right = self.nextId();
  14016. left = {};
  14017. args = [];
  14018. self.recurse(ast.callee, right, left, function() {
  14019. self.if_(self.notNull(right), function() {
  14020. forEach(ast.arguments, function(expr) {
  14021. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  14022. args.push(argument);
  14023. });
  14024. });
  14025. if (left.name) {
  14026. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  14027. } else {
  14028. expression = right + '(' + args.join(',') + ')';
  14029. }
  14030. self.assign(intoId, expression);
  14031. }, function() {
  14032. self.assign(intoId, 'undefined');
  14033. });
  14034. recursionFn(intoId);
  14035. });
  14036. }
  14037. break;
  14038. case AST.AssignmentExpression:
  14039. right = this.nextId();
  14040. left = {};
  14041. this.recurse(ast.left, undefined, left, function() {
  14042. self.if_(self.notNull(left.context), function() {
  14043. self.recurse(ast.right, right);
  14044. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  14045. self.assign(intoId, expression);
  14046. recursionFn(intoId || expression);
  14047. });
  14048. }, 1);
  14049. break;
  14050. case AST.ArrayExpression:
  14051. args = [];
  14052. forEach(ast.elements, function(expr) {
  14053. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  14054. args.push(argument);
  14055. });
  14056. });
  14057. expression = '[' + args.join(',') + ']';
  14058. this.assign(intoId, expression);
  14059. recursionFn(intoId || expression);
  14060. break;
  14061. case AST.ObjectExpression:
  14062. args = [];
  14063. computed = false;
  14064. forEach(ast.properties, function(property) {
  14065. if (property.computed) {
  14066. computed = true;
  14067. }
  14068. });
  14069. if (computed) {
  14070. intoId = intoId || this.nextId();
  14071. this.assign(intoId, '{}');
  14072. forEach(ast.properties, function(property) {
  14073. if (property.computed) {
  14074. left = self.nextId();
  14075. self.recurse(property.key, left);
  14076. } else {
  14077. left = property.key.type === AST.Identifier ?
  14078. property.key.name :
  14079. ('' + property.key.value);
  14080. }
  14081. right = self.nextId();
  14082. self.recurse(property.value, right);
  14083. self.assign(self.member(intoId, left, property.computed), right);
  14084. });
  14085. } else {
  14086. forEach(ast.properties, function(property) {
  14087. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  14088. args.push(self.escape(
  14089. property.key.type === AST.Identifier ? property.key.name :
  14090. ('' + property.key.value)) +
  14091. ':' + expr);
  14092. });
  14093. });
  14094. expression = '{' + args.join(',') + '}';
  14095. this.assign(intoId, expression);
  14096. }
  14097. recursionFn(intoId || expression);
  14098. break;
  14099. case AST.ThisExpression:
  14100. this.assign(intoId, 's');
  14101. recursionFn(intoId || 's');
  14102. break;
  14103. case AST.LocalsExpression:
  14104. this.assign(intoId, 'l');
  14105. recursionFn(intoId || 'l');
  14106. break;
  14107. case AST.NGValueParameter:
  14108. this.assign(intoId, 'v');
  14109. recursionFn(intoId || 'v');
  14110. break;
  14111. }
  14112. },
  14113. getHasOwnProperty: function(element, property) {
  14114. var key = element + '.' + property;
  14115. var own = this.current().own;
  14116. if (!own.hasOwnProperty(key)) {
  14117. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  14118. }
  14119. return own[key];
  14120. },
  14121. assign: function(id, value) {
  14122. if (!id) return;
  14123. this.current().body.push(id, '=', value, ';');
  14124. return id;
  14125. },
  14126. filter: function(filterName) {
  14127. if (!this.state.filters.hasOwnProperty(filterName)) {
  14128. this.state.filters[filterName] = this.nextId(true);
  14129. }
  14130. return this.state.filters[filterName];
  14131. },
  14132. ifDefined: function(id, defaultValue) {
  14133. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  14134. },
  14135. plus: function(left, right) {
  14136. return 'plus(' + left + ',' + right + ')';
  14137. },
  14138. return_: function(id) {
  14139. this.current().body.push('return ', id, ';');
  14140. },
  14141. if_: function(test, alternate, consequent) {
  14142. if (test === true) {
  14143. alternate();
  14144. } else {
  14145. var body = this.current().body;
  14146. body.push('if(', test, '){');
  14147. alternate();
  14148. body.push('}');
  14149. if (consequent) {
  14150. body.push('else{');
  14151. consequent();
  14152. body.push('}');
  14153. }
  14154. }
  14155. },
  14156. not: function(expression) {
  14157. return '!(' + expression + ')';
  14158. },
  14159. isNull: function(expression) {
  14160. return expression + '==null';
  14161. },
  14162. notNull: function(expression) {
  14163. return expression + '!=null';
  14164. },
  14165. nonComputedMember: function(left, right) {
  14166. var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
  14167. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  14168. if (SAFE_IDENTIFIER.test(right)) {
  14169. return left + '.' + right;
  14170. } else {
  14171. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  14172. }
  14173. },
  14174. computedMember: function(left, right) {
  14175. return left + '[' + right + ']';
  14176. },
  14177. member: function(left, right, computed) {
  14178. if (computed) return this.computedMember(left, right);
  14179. return this.nonComputedMember(left, right);
  14180. },
  14181. getStringValue: function(item) {
  14182. this.assign(item, 'getStringValue(' + item + ')');
  14183. },
  14184. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14185. var self = this;
  14186. return function() {
  14187. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  14188. };
  14189. },
  14190. lazyAssign: function(id, value) {
  14191. var self = this;
  14192. return function() {
  14193. self.assign(id, value);
  14194. };
  14195. },
  14196. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  14197. stringEscapeFn: function(c) {
  14198. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  14199. },
  14200. escape: function(value) {
  14201. if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
  14202. if (isNumber(value)) return value.toString();
  14203. if (value === true) return 'true';
  14204. if (value === false) return 'false';
  14205. if (value === null) return 'null';
  14206. if (typeof value === 'undefined') return 'undefined';
  14207. throw $parseMinErr('esc', 'IMPOSSIBLE');
  14208. },
  14209. nextId: function(skip, init) {
  14210. var id = 'v' + (this.state.nextId++);
  14211. if (!skip) {
  14212. this.current().vars.push(id + (init ? '=' + init : ''));
  14213. }
  14214. return id;
  14215. },
  14216. current: function() {
  14217. return this.state[this.state.computing];
  14218. }
  14219. };
  14220. function ASTInterpreter(astBuilder, $filter) {
  14221. this.astBuilder = astBuilder;
  14222. this.$filter = $filter;
  14223. }
  14224. ASTInterpreter.prototype = {
  14225. compile: function(expression) {
  14226. var self = this;
  14227. var ast = this.astBuilder.ast(expression);
  14228. findConstantAndWatchExpressions(ast, self.$filter);
  14229. var assignable;
  14230. var assign;
  14231. if ((assignable = assignableAST(ast))) {
  14232. assign = this.recurse(assignable);
  14233. }
  14234. var toWatch = getInputs(ast.body);
  14235. var inputs;
  14236. if (toWatch) {
  14237. inputs = [];
  14238. forEach(toWatch, function(watch, key) {
  14239. var input = self.recurse(watch);
  14240. watch.input = input;
  14241. inputs.push(input);
  14242. watch.watchId = key;
  14243. });
  14244. }
  14245. var expressions = [];
  14246. forEach(ast.body, function(expression) {
  14247. expressions.push(self.recurse(expression.expression));
  14248. });
  14249. var fn = ast.body.length === 0 ? noop :
  14250. ast.body.length === 1 ? expressions[0] :
  14251. function(scope, locals) {
  14252. var lastValue;
  14253. forEach(expressions, function(exp) {
  14254. lastValue = exp(scope, locals);
  14255. });
  14256. return lastValue;
  14257. };
  14258. if (assign) {
  14259. fn.assign = function(scope, value, locals) {
  14260. return assign(scope, locals, value);
  14261. };
  14262. }
  14263. if (inputs) {
  14264. fn.inputs = inputs;
  14265. }
  14266. fn.literal = isLiteral(ast);
  14267. fn.constant = isConstant(ast);
  14268. return fn;
  14269. },
  14270. recurse: function(ast, context, create) {
  14271. var left, right, self = this, args;
  14272. if (ast.input) {
  14273. return this.inputs(ast.input, ast.watchId);
  14274. }
  14275. switch (ast.type) {
  14276. case AST.Literal:
  14277. return this.value(ast.value, context);
  14278. case AST.UnaryExpression:
  14279. right = this.recurse(ast.argument);
  14280. return this['unary' + ast.operator](right, context);
  14281. case AST.BinaryExpression:
  14282. left = this.recurse(ast.left);
  14283. right = this.recurse(ast.right);
  14284. return this['binary' + ast.operator](left, right, context);
  14285. case AST.LogicalExpression:
  14286. left = this.recurse(ast.left);
  14287. right = this.recurse(ast.right);
  14288. return this['binary' + ast.operator](left, right, context);
  14289. case AST.ConditionalExpression:
  14290. return this['ternary?:'](
  14291. this.recurse(ast.test),
  14292. this.recurse(ast.alternate),
  14293. this.recurse(ast.consequent),
  14294. context
  14295. );
  14296. case AST.Identifier:
  14297. return self.identifier(ast.name, context, create);
  14298. case AST.MemberExpression:
  14299. left = this.recurse(ast.object, false, !!create);
  14300. if (!ast.computed) {
  14301. right = ast.property.name;
  14302. }
  14303. if (ast.computed) right = this.recurse(ast.property);
  14304. return ast.computed ?
  14305. this.computedMember(left, right, context, create) :
  14306. this.nonComputedMember(left, right, context, create);
  14307. case AST.CallExpression:
  14308. args = [];
  14309. forEach(ast.arguments, function(expr) {
  14310. args.push(self.recurse(expr));
  14311. });
  14312. if (ast.filter) right = this.$filter(ast.callee.name);
  14313. if (!ast.filter) right = this.recurse(ast.callee, true);
  14314. return ast.filter ?
  14315. function(scope, locals, assign, inputs) {
  14316. var values = [];
  14317. for (var i = 0; i < args.length; ++i) {
  14318. values.push(args[i](scope, locals, assign, inputs));
  14319. }
  14320. var value = right.apply(undefined, values, inputs);
  14321. return context ? {context: undefined, name: undefined, value: value} : value;
  14322. } :
  14323. function(scope, locals, assign, inputs) {
  14324. var rhs = right(scope, locals, assign, inputs);
  14325. var value;
  14326. if (rhs.value != null) {
  14327. var values = [];
  14328. for (var i = 0; i < args.length; ++i) {
  14329. values.push(args[i](scope, locals, assign, inputs));
  14330. }
  14331. value = rhs.value.apply(rhs.context, values);
  14332. }
  14333. return context ? {value: value} : value;
  14334. };
  14335. case AST.AssignmentExpression:
  14336. left = this.recurse(ast.left, true, 1);
  14337. right = this.recurse(ast.right);
  14338. return function(scope, locals, assign, inputs) {
  14339. var lhs = left(scope, locals, assign, inputs);
  14340. var rhs = right(scope, locals, assign, inputs);
  14341. lhs.context[lhs.name] = rhs;
  14342. return context ? {value: rhs} : rhs;
  14343. };
  14344. case AST.ArrayExpression:
  14345. args = [];
  14346. forEach(ast.elements, function(expr) {
  14347. args.push(self.recurse(expr));
  14348. });
  14349. return function(scope, locals, assign, inputs) {
  14350. var value = [];
  14351. for (var i = 0; i < args.length; ++i) {
  14352. value.push(args[i](scope, locals, assign, inputs));
  14353. }
  14354. return context ? {value: value} : value;
  14355. };
  14356. case AST.ObjectExpression:
  14357. args = [];
  14358. forEach(ast.properties, function(property) {
  14359. if (property.computed) {
  14360. args.push({key: self.recurse(property.key),
  14361. computed: true,
  14362. value: self.recurse(property.value)
  14363. });
  14364. } else {
  14365. args.push({key: property.key.type === AST.Identifier ?
  14366. property.key.name :
  14367. ('' + property.key.value),
  14368. computed: false,
  14369. value: self.recurse(property.value)
  14370. });
  14371. }
  14372. });
  14373. return function(scope, locals, assign, inputs) {
  14374. var value = {};
  14375. for (var i = 0; i < args.length; ++i) {
  14376. if (args[i].computed) {
  14377. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  14378. } else {
  14379. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  14380. }
  14381. }
  14382. return context ? {value: value} : value;
  14383. };
  14384. case AST.ThisExpression:
  14385. return function(scope) {
  14386. return context ? {value: scope} : scope;
  14387. };
  14388. case AST.LocalsExpression:
  14389. return function(scope, locals) {
  14390. return context ? {value: locals} : locals;
  14391. };
  14392. case AST.NGValueParameter:
  14393. return function(scope, locals, assign) {
  14394. return context ? {value: assign} : assign;
  14395. };
  14396. }
  14397. },
  14398. 'unary+': function(argument, context) {
  14399. return function(scope, locals, assign, inputs) {
  14400. var arg = argument(scope, locals, assign, inputs);
  14401. if (isDefined(arg)) {
  14402. arg = +arg;
  14403. } else {
  14404. arg = 0;
  14405. }
  14406. return context ? {value: arg} : arg;
  14407. };
  14408. },
  14409. 'unary-': function(argument, context) {
  14410. return function(scope, locals, assign, inputs) {
  14411. var arg = argument(scope, locals, assign, inputs);
  14412. if (isDefined(arg)) {
  14413. arg = -arg;
  14414. } else {
  14415. arg = -0;
  14416. }
  14417. return context ? {value: arg} : arg;
  14418. };
  14419. },
  14420. 'unary!': function(argument, context) {
  14421. return function(scope, locals, assign, inputs) {
  14422. var arg = !argument(scope, locals, assign, inputs);
  14423. return context ? {value: arg} : arg;
  14424. };
  14425. },
  14426. 'binary+': function(left, right, context) {
  14427. return function(scope, locals, assign, inputs) {
  14428. var lhs = left(scope, locals, assign, inputs);
  14429. var rhs = right(scope, locals, assign, inputs);
  14430. var arg = plusFn(lhs, rhs);
  14431. return context ? {value: arg} : arg;
  14432. };
  14433. },
  14434. 'binary-': function(left, right, context) {
  14435. return function(scope, locals, assign, inputs) {
  14436. var lhs = left(scope, locals, assign, inputs);
  14437. var rhs = right(scope, locals, assign, inputs);
  14438. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  14439. return context ? {value: arg} : arg;
  14440. };
  14441. },
  14442. 'binary*': function(left, right, context) {
  14443. return function(scope, locals, assign, inputs) {
  14444. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  14445. return context ? {value: arg} : arg;
  14446. };
  14447. },
  14448. 'binary/': function(left, right, context) {
  14449. return function(scope, locals, assign, inputs) {
  14450. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  14451. return context ? {value: arg} : arg;
  14452. };
  14453. },
  14454. 'binary%': function(left, right, context) {
  14455. return function(scope, locals, assign, inputs) {
  14456. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  14457. return context ? {value: arg} : arg;
  14458. };
  14459. },
  14460. 'binary===': function(left, right, context) {
  14461. return function(scope, locals, assign, inputs) {
  14462. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  14463. return context ? {value: arg} : arg;
  14464. };
  14465. },
  14466. 'binary!==': function(left, right, context) {
  14467. return function(scope, locals, assign, inputs) {
  14468. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  14469. return context ? {value: arg} : arg;
  14470. };
  14471. },
  14472. 'binary==': function(left, right, context) {
  14473. return function(scope, locals, assign, inputs) {
  14474. // eslint-disable-next-line eqeqeq
  14475. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  14476. return context ? {value: arg} : arg;
  14477. };
  14478. },
  14479. 'binary!=': function(left, right, context) {
  14480. return function(scope, locals, assign, inputs) {
  14481. // eslint-disable-next-line eqeqeq
  14482. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  14483. return context ? {value: arg} : arg;
  14484. };
  14485. },
  14486. 'binary<': function(left, right, context) {
  14487. return function(scope, locals, assign, inputs) {
  14488. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  14489. return context ? {value: arg} : arg;
  14490. };
  14491. },
  14492. 'binary>': function(left, right, context) {
  14493. return function(scope, locals, assign, inputs) {
  14494. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  14495. return context ? {value: arg} : arg;
  14496. };
  14497. },
  14498. 'binary<=': function(left, right, context) {
  14499. return function(scope, locals, assign, inputs) {
  14500. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  14501. return context ? {value: arg} : arg;
  14502. };
  14503. },
  14504. 'binary>=': function(left, right, context) {
  14505. return function(scope, locals, assign, inputs) {
  14506. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  14507. return context ? {value: arg} : arg;
  14508. };
  14509. },
  14510. 'binary&&': function(left, right, context) {
  14511. return function(scope, locals, assign, inputs) {
  14512. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  14513. return context ? {value: arg} : arg;
  14514. };
  14515. },
  14516. 'binary||': function(left, right, context) {
  14517. return function(scope, locals, assign, inputs) {
  14518. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  14519. return context ? {value: arg} : arg;
  14520. };
  14521. },
  14522. 'ternary?:': function(test, alternate, consequent, context) {
  14523. return function(scope, locals, assign, inputs) {
  14524. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  14525. return context ? {value: arg} : arg;
  14526. };
  14527. },
  14528. value: function(value, context) {
  14529. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  14530. },
  14531. identifier: function(name, context, create) {
  14532. return function(scope, locals, assign, inputs) {
  14533. var base = locals && (name in locals) ? locals : scope;
  14534. if (create && create !== 1 && base && base[name] == null) {
  14535. base[name] = {};
  14536. }
  14537. var value = base ? base[name] : undefined;
  14538. if (context) {
  14539. return {context: base, name: name, value: value};
  14540. } else {
  14541. return value;
  14542. }
  14543. };
  14544. },
  14545. computedMember: function(left, right, context, create) {
  14546. return function(scope, locals, assign, inputs) {
  14547. var lhs = left(scope, locals, assign, inputs);
  14548. var rhs;
  14549. var value;
  14550. if (lhs != null) {
  14551. rhs = right(scope, locals, assign, inputs);
  14552. rhs = getStringValue(rhs);
  14553. if (create && create !== 1) {
  14554. if (lhs && !(lhs[rhs])) {
  14555. lhs[rhs] = {};
  14556. }
  14557. }
  14558. value = lhs[rhs];
  14559. }
  14560. if (context) {
  14561. return {context: lhs, name: rhs, value: value};
  14562. } else {
  14563. return value;
  14564. }
  14565. };
  14566. },
  14567. nonComputedMember: function(left, right, context, create) {
  14568. return function(scope, locals, assign, inputs) {
  14569. var lhs = left(scope, locals, assign, inputs);
  14570. if (create && create !== 1) {
  14571. if (lhs && lhs[right] == null) {
  14572. lhs[right] = {};
  14573. }
  14574. }
  14575. var value = lhs != null ? lhs[right] : undefined;
  14576. if (context) {
  14577. return {context: lhs, name: right, value: value};
  14578. } else {
  14579. return value;
  14580. }
  14581. };
  14582. },
  14583. inputs: function(input, watchId) {
  14584. return function(scope, value, locals, inputs) {
  14585. if (inputs) return inputs[watchId];
  14586. return input(scope, value, locals);
  14587. };
  14588. }
  14589. };
  14590. /**
  14591. * @constructor
  14592. */
  14593. var Parser = function Parser(lexer, $filter, options) {
  14594. this.lexer = lexer;
  14595. this.$filter = $filter;
  14596. this.options = options;
  14597. this.ast = new AST(lexer, options);
  14598. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  14599. new ASTCompiler(this.ast, $filter);
  14600. };
  14601. Parser.prototype = {
  14602. constructor: Parser,
  14603. parse: function(text) {
  14604. return this.astCompiler.compile(text);
  14605. }
  14606. };
  14607. function getValueOf(value) {
  14608. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  14609. }
  14610. ///////////////////////////////////
  14611. /**
  14612. * @ngdoc service
  14613. * @name $parse
  14614. * @kind function
  14615. *
  14616. * @description
  14617. *
  14618. * Converts Angular {@link guide/expression expression} into a function.
  14619. *
  14620. * ```js
  14621. * var getter = $parse('user.name');
  14622. * var setter = getter.assign;
  14623. * var context = {user:{name:'angular'}};
  14624. * var locals = {user:{name:'local'}};
  14625. *
  14626. * expect(getter(context)).toEqual('angular');
  14627. * setter(context, 'newValue');
  14628. * expect(context.user.name).toEqual('newValue');
  14629. * expect(getter(context, locals)).toEqual('local');
  14630. * ```
  14631. *
  14632. *
  14633. * @param {string} expression String expression to compile.
  14634. * @returns {function(context, locals)} a function which represents the compiled expression:
  14635. *
  14636. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14637. * are evaluated against (typically a scope object).
  14638. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14639. * `context`.
  14640. *
  14641. * The returned function also has the following properties:
  14642. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  14643. * literal.
  14644. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  14645. * constant literals.
  14646. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  14647. * set to a function to change its value on the given context.
  14648. *
  14649. */
  14650. /**
  14651. * @ngdoc provider
  14652. * @name $parseProvider
  14653. * @this
  14654. *
  14655. * @description
  14656. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  14657. * service.
  14658. */
  14659. function $ParseProvider() {
  14660. var cache = createMap();
  14661. var literals = {
  14662. 'true': true,
  14663. 'false': false,
  14664. 'null': null,
  14665. 'undefined': undefined
  14666. };
  14667. var identStart, identContinue;
  14668. /**
  14669. * @ngdoc method
  14670. * @name $parseProvider#addLiteral
  14671. * @description
  14672. *
  14673. * Configure $parse service to add literal values that will be present as literal at expressions.
  14674. *
  14675. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  14676. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  14677. *
  14678. **/
  14679. this.addLiteral = function(literalName, literalValue) {
  14680. literals[literalName] = literalValue;
  14681. };
  14682. /**
  14683. * @ngdoc method
  14684. * @name $parseProvider#setIdentifierFns
  14685. *
  14686. * @description
  14687. *
  14688. * Allows defining the set of characters that are allowed in Angular expressions. The function
  14689. * `identifierStart` will get called to know if a given character is a valid character to be the
  14690. * first character for an identifier. The function `identifierContinue` will get called to know if
  14691. * a given character is a valid character to be a follow-up identifier character. The functions
  14692. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  14693. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  14694. * mind that the `string` parameter can be two characters long depending on the character
  14695. * representation. It is expected for the function to return `true` or `false`, whether that
  14696. * character is allowed or not.
  14697. *
  14698. * Since this function will be called extensively, keep the implementation of these functions fast,
  14699. * as the performance of these functions have a direct impact on the expressions parsing speed.
  14700. *
  14701. * @param {function=} identifierStart The function that will decide whether the given character is
  14702. * a valid identifier start character.
  14703. * @param {function=} identifierContinue The function that will decide whether the given character is
  14704. * a valid identifier continue character.
  14705. */
  14706. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  14707. identStart = identifierStart;
  14708. identContinue = identifierContinue;
  14709. return this;
  14710. };
  14711. this.$get = ['$filter', function($filter) {
  14712. var noUnsafeEval = csp().noUnsafeEval;
  14713. var $parseOptions = {
  14714. csp: noUnsafeEval,
  14715. literals: copy(literals),
  14716. isIdentifierStart: isFunction(identStart) && identStart,
  14717. isIdentifierContinue: isFunction(identContinue) && identContinue
  14718. };
  14719. return $parse;
  14720. function $parse(exp, interceptorFn) {
  14721. var parsedExpression, oneTime, cacheKey;
  14722. switch (typeof exp) {
  14723. case 'string':
  14724. exp = exp.trim();
  14725. cacheKey = exp;
  14726. parsedExpression = cache[cacheKey];
  14727. if (!parsedExpression) {
  14728. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  14729. oneTime = true;
  14730. exp = exp.substring(2);
  14731. }
  14732. var lexer = new Lexer($parseOptions);
  14733. var parser = new Parser(lexer, $filter, $parseOptions);
  14734. parsedExpression = parser.parse(exp);
  14735. if (parsedExpression.constant) {
  14736. parsedExpression.$$watchDelegate = constantWatchDelegate;
  14737. } else if (oneTime) {
  14738. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  14739. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  14740. } else if (parsedExpression.inputs) {
  14741. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  14742. }
  14743. cache[cacheKey] = parsedExpression;
  14744. }
  14745. return addInterceptor(parsedExpression, interceptorFn);
  14746. case 'function':
  14747. return addInterceptor(exp, interceptorFn);
  14748. default:
  14749. return addInterceptor(noop, interceptorFn);
  14750. }
  14751. }
  14752. function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) {
  14753. if (newValue == null || oldValueOfValue == null) { // null/undefined
  14754. return newValue === oldValueOfValue;
  14755. }
  14756. if (typeof newValue === 'object' && !compareObjectIdentity) {
  14757. // attempt to convert the value to a primitive type
  14758. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  14759. // be cheaply dirty-checked
  14760. newValue = getValueOf(newValue);
  14761. if (typeof newValue === 'object') {
  14762. // objects/arrays are not supported - deep-watching them would be too expensive
  14763. return false;
  14764. }
  14765. // fall-through to the primitive equality check
  14766. }
  14767. //Primitive or NaN
  14768. // eslint-disable-next-line no-self-compare
  14769. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  14770. }
  14771. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14772. var inputExpressions = parsedExpression.inputs;
  14773. var lastResult;
  14774. if (inputExpressions.length === 1) {
  14775. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14776. inputExpressions = inputExpressions[0];
  14777. return scope.$watch(function expressionInputWatch(scope) {
  14778. var newInputValue = inputExpressions(scope);
  14779. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, parsedExpression.literal)) {
  14780. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  14781. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  14782. }
  14783. return lastResult;
  14784. }, listener, objectEquality, prettyPrintExpression);
  14785. }
  14786. var oldInputValueOfValues = [];
  14787. var oldInputValues = [];
  14788. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14789. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14790. oldInputValues[i] = null;
  14791. }
  14792. return scope.$watch(function expressionInputsWatch(scope) {
  14793. var changed = false;
  14794. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14795. var newInputValue = inputExpressions[i](scope);
  14796. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], parsedExpression.literal))) {
  14797. oldInputValues[i] = newInputValue;
  14798. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  14799. }
  14800. }
  14801. if (changed) {
  14802. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  14803. }
  14804. return lastResult;
  14805. }, listener, objectEquality, prettyPrintExpression);
  14806. }
  14807. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14808. var unwatch, lastValue;
  14809. if (parsedExpression.inputs) {
  14810. unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);
  14811. } else {
  14812. unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);
  14813. }
  14814. return unwatch;
  14815. function oneTimeWatch(scope) {
  14816. return parsedExpression(scope);
  14817. }
  14818. function oneTimeListener(value, old, scope) {
  14819. lastValue = value;
  14820. if (isFunction(listener)) {
  14821. listener(value, old, scope);
  14822. }
  14823. if (isDefined(value)) {
  14824. scope.$$postDigest(function() {
  14825. if (isDefined(lastValue)) {
  14826. unwatch();
  14827. }
  14828. });
  14829. }
  14830. }
  14831. }
  14832. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14833. var unwatch, lastValue;
  14834. unwatch = scope.$watch(function oneTimeWatch(scope) {
  14835. return parsedExpression(scope);
  14836. }, function oneTimeListener(value, old, scope) {
  14837. lastValue = value;
  14838. if (isFunction(listener)) {
  14839. listener(value, old, scope);
  14840. }
  14841. if (isAllDefined(value)) {
  14842. scope.$$postDigest(function() {
  14843. if (isAllDefined(lastValue)) unwatch();
  14844. });
  14845. }
  14846. }, objectEquality);
  14847. return unwatch;
  14848. function isAllDefined(value) {
  14849. var allDefined = true;
  14850. forEach(value, function(val) {
  14851. if (!isDefined(val)) allDefined = false;
  14852. });
  14853. return allDefined;
  14854. }
  14855. }
  14856. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14857. var unwatch = scope.$watch(function constantWatch(scope) {
  14858. unwatch();
  14859. return parsedExpression(scope);
  14860. }, listener, objectEquality);
  14861. return unwatch;
  14862. }
  14863. function addInterceptor(parsedExpression, interceptorFn) {
  14864. if (!interceptorFn) return parsedExpression;
  14865. var watchDelegate = parsedExpression.$$watchDelegate;
  14866. var useInputs = false;
  14867. var regularWatch =
  14868. watchDelegate !== oneTimeLiteralWatchDelegate &&
  14869. watchDelegate !== oneTimeWatchDelegate;
  14870. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  14871. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  14872. return interceptorFn(value, scope, locals);
  14873. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  14874. var value = parsedExpression(scope, locals, assign, inputs);
  14875. var result = interceptorFn(value, scope, locals);
  14876. // we only return the interceptor's result if the
  14877. // initial value is defined (for bind-once)
  14878. return isDefined(value) ? result : value;
  14879. };
  14880. // Propagate $$watchDelegates other then inputsWatchDelegate
  14881. useInputs = !parsedExpression.inputs;
  14882. if (parsedExpression.$$watchDelegate &&
  14883. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  14884. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  14885. fn.inputs = parsedExpression.inputs;
  14886. } else if (!interceptorFn.$stateful) {
  14887. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  14888. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  14889. fn.$$watchDelegate = inputsWatchDelegate;
  14890. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  14891. }
  14892. return fn;
  14893. }
  14894. }];
  14895. }
  14896. /**
  14897. * @ngdoc service
  14898. * @name $q
  14899. * @requires $rootScope
  14900. *
  14901. * @description
  14902. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  14903. * when they are done processing.
  14904. *
  14905. * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred
  14906. * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  14907. *
  14908. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  14909. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  14910. *
  14911. * # $q constructor
  14912. *
  14913. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  14914. * function as the first argument. This is similar to the native Promise implementation from ES6,
  14915. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  14916. *
  14917. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  14918. * available yet.
  14919. *
  14920. * It can be used like so:
  14921. *
  14922. * ```js
  14923. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14924. * // are available in the current lexical scope (they could have been injected or passed in).
  14925. *
  14926. * function asyncGreet(name) {
  14927. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  14928. * return $q(function(resolve, reject) {
  14929. * setTimeout(function() {
  14930. * if (okToGreet(name)) {
  14931. * resolve('Hello, ' + name + '!');
  14932. * } else {
  14933. * reject('Greeting ' + name + ' is not allowed.');
  14934. * }
  14935. * }, 1000);
  14936. * });
  14937. * }
  14938. *
  14939. * var promise = asyncGreet('Robin Hood');
  14940. * promise.then(function(greeting) {
  14941. * alert('Success: ' + greeting);
  14942. * }, function(reason) {
  14943. * alert('Failed: ' + reason);
  14944. * });
  14945. * ```
  14946. *
  14947. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  14948. *
  14949. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  14950. *
  14951. * However, the more traditional CommonJS-style usage is still available, and documented below.
  14952. *
  14953. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  14954. * interface for interacting with an object that represents the result of an action that is
  14955. * performed asynchronously, and may or may not be finished at any given point in time.
  14956. *
  14957. * From the perspective of dealing with error handling, deferred and promise APIs are to
  14958. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  14959. *
  14960. * ```js
  14961. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14962. * // are available in the current lexical scope (they could have been injected or passed in).
  14963. *
  14964. * function asyncGreet(name) {
  14965. * var deferred = $q.defer();
  14966. *
  14967. * setTimeout(function() {
  14968. * deferred.notify('About to greet ' + name + '.');
  14969. *
  14970. * if (okToGreet(name)) {
  14971. * deferred.resolve('Hello, ' + name + '!');
  14972. * } else {
  14973. * deferred.reject('Greeting ' + name + ' is not allowed.');
  14974. * }
  14975. * }, 1000);
  14976. *
  14977. * return deferred.promise;
  14978. * }
  14979. *
  14980. * var promise = asyncGreet('Robin Hood');
  14981. * promise.then(function(greeting) {
  14982. * alert('Success: ' + greeting);
  14983. * }, function(reason) {
  14984. * alert('Failed: ' + reason);
  14985. * }, function(update) {
  14986. * alert('Got notification: ' + update);
  14987. * });
  14988. * ```
  14989. *
  14990. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  14991. * comes in the way of guarantees that promise and deferred APIs make, see
  14992. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  14993. *
  14994. * Additionally the promise api allows for composition that is very hard to do with the
  14995. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  14996. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  14997. * section on serial or parallel joining of promises.
  14998. *
  14999. * # The Deferred API
  15000. *
  15001. * A new instance of deferred is constructed by calling `$q.defer()`.
  15002. *
  15003. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  15004. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  15005. * of the task.
  15006. *
  15007. * **Methods**
  15008. *
  15009. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  15010. * constructed via `$q.reject`, the promise will be rejected instead.
  15011. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  15012. * resolving it with a rejection constructed via `$q.reject`.
  15013. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  15014. * multiple times before the promise is either resolved or rejected.
  15015. *
  15016. * **Properties**
  15017. *
  15018. * - promise – `{Promise}` – promise object associated with this deferred.
  15019. *
  15020. *
  15021. * # The Promise API
  15022. *
  15023. * A new promise instance is created when a deferred instance is created and can be retrieved by
  15024. * calling `deferred.promise`.
  15025. *
  15026. * The purpose of the promise object is to allow for interested parties to get access to the result
  15027. * of the deferred task when it completes.
  15028. *
  15029. * **Methods**
  15030. *
  15031. * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
  15032. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  15033. * as soon as the result is available. The callbacks are called with a single argument: the result
  15034. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  15035. * provide a progress indication, before the promise is resolved or rejected.
  15036. *
  15037. * This method *returns a new promise* which is resolved or rejected via the return value of the
  15038. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  15039. * with the value which is resolved in that promise using
  15040. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  15041. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  15042. * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
  15043. * arguments are optional.
  15044. *
  15045. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  15046. *
  15047. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  15048. * but to do so without modifying the final value. This is useful to release resources or do some
  15049. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  15050. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  15051. * more information.
  15052. *
  15053. * # Chaining promises
  15054. *
  15055. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  15056. * possible to create a chain of promises:
  15057. *
  15058. * ```js
  15059. * promiseB = promiseA.then(function(result) {
  15060. * return result + 1;
  15061. * });
  15062. *
  15063. * // promiseB will be resolved immediately after promiseA is resolved and its value
  15064. * // will be the result of promiseA incremented by 1
  15065. * ```
  15066. *
  15067. * It is possible to create chains of any length and since a promise can be resolved with another
  15068. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  15069. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  15070. * $http's response interceptors.
  15071. *
  15072. *
  15073. * # Differences between Kris Kowal's Q and $q
  15074. *
  15075. * There are two main differences:
  15076. *
  15077. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  15078. * mechanism in angular, which means faster propagation of resolution or rejection into your
  15079. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  15080. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  15081. * all the important functionality needed for common async tasks.
  15082. *
  15083. * # Testing
  15084. *
  15085. * ```js
  15086. * it('should simulate promise', inject(function($q, $rootScope) {
  15087. * var deferred = $q.defer();
  15088. * var promise = deferred.promise;
  15089. * var resolvedValue;
  15090. *
  15091. * promise.then(function(value) { resolvedValue = value; });
  15092. * expect(resolvedValue).toBeUndefined();
  15093. *
  15094. * // Simulate resolving of promise
  15095. * deferred.resolve(123);
  15096. * // Note that the 'then' function does not get called synchronously.
  15097. * // This is because we want the promise API to always be async, whether or not
  15098. * // it got called synchronously or asynchronously.
  15099. * expect(resolvedValue).toBeUndefined();
  15100. *
  15101. * // Propagate promise resolution to 'then' functions using $apply().
  15102. * $rootScope.$apply();
  15103. * expect(resolvedValue).toEqual(123);
  15104. * }));
  15105. * ```
  15106. *
  15107. * @param {function(function, function)} resolver Function which is responsible for resolving or
  15108. * rejecting the newly created promise. The first parameter is a function which resolves the
  15109. * promise, the second parameter is a function which rejects the promise.
  15110. *
  15111. * @returns {Promise} The newly created promise.
  15112. */
  15113. /**
  15114. * @ngdoc provider
  15115. * @name $qProvider
  15116. * @this
  15117. *
  15118. * @description
  15119. */
  15120. function $QProvider() {
  15121. var errorOnUnhandledRejections = true;
  15122. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  15123. return qFactory(function(callback) {
  15124. $rootScope.$evalAsync(callback);
  15125. }, $exceptionHandler, errorOnUnhandledRejections);
  15126. }];
  15127. /**
  15128. * @ngdoc method
  15129. * @name $qProvider#errorOnUnhandledRejections
  15130. * @kind function
  15131. *
  15132. * @description
  15133. * Retrieves or overrides whether to generate an error when a rejected promise is not handled.
  15134. * This feature is enabled by default.
  15135. *
  15136. * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.
  15137. * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for
  15138. * chaining otherwise.
  15139. */
  15140. this.errorOnUnhandledRejections = function(value) {
  15141. if (isDefined(value)) {
  15142. errorOnUnhandledRejections = value;
  15143. return this;
  15144. } else {
  15145. return errorOnUnhandledRejections;
  15146. }
  15147. };
  15148. }
  15149. /** @this */
  15150. function $$QProvider() {
  15151. var errorOnUnhandledRejections = true;
  15152. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  15153. return qFactory(function(callback) {
  15154. $browser.defer(callback);
  15155. }, $exceptionHandler, errorOnUnhandledRejections);
  15156. }];
  15157. this.errorOnUnhandledRejections = function(value) {
  15158. if (isDefined(value)) {
  15159. errorOnUnhandledRejections = value;
  15160. return this;
  15161. } else {
  15162. return errorOnUnhandledRejections;
  15163. }
  15164. };
  15165. }
  15166. /**
  15167. * Constructs a promise manager.
  15168. *
  15169. * @param {function(function)} nextTick Function for executing functions in the next turn.
  15170. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  15171. * debugging purposes.
  15172. @ param {=boolean} errorOnUnhandledRejections Whether an error should be generated on unhandled
  15173. * promises rejections.
  15174. * @returns {object} Promise manager.
  15175. */
  15176. function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {
  15177. var $qMinErr = minErr('$q', TypeError);
  15178. var queueSize = 0;
  15179. var checkQueue = [];
  15180. /**
  15181. * @ngdoc method
  15182. * @name ng.$q#defer
  15183. * @kind function
  15184. *
  15185. * @description
  15186. * Creates a `Deferred` object which represents a task which will finish in the future.
  15187. *
  15188. * @returns {Deferred} Returns a new instance of deferred.
  15189. */
  15190. function defer() {
  15191. return new Deferred();
  15192. }
  15193. function Deferred() {
  15194. var promise = this.promise = new Promise();
  15195. //Non prototype methods necessary to support unbound execution :/
  15196. this.resolve = function(val) { resolvePromise(promise, val); };
  15197. this.reject = function(reason) { rejectPromise(promise, reason); };
  15198. this.notify = function(progress) { notifyPromise(promise, progress); };
  15199. }
  15200. function Promise() {
  15201. this.$$state = { status: 0 };
  15202. }
  15203. extend(Promise.prototype, {
  15204. then: function(onFulfilled, onRejected, progressBack) {
  15205. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  15206. return this;
  15207. }
  15208. var result = new Promise();
  15209. this.$$state.pending = this.$$state.pending || [];
  15210. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  15211. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  15212. return result;
  15213. },
  15214. 'catch': function(callback) {
  15215. return this.then(null, callback);
  15216. },
  15217. 'finally': function(callback, progressBack) {
  15218. return this.then(function(value) {
  15219. return handleCallback(value, resolve, callback);
  15220. }, function(error) {
  15221. return handleCallback(error, reject, callback);
  15222. }, progressBack);
  15223. }
  15224. });
  15225. function processQueue(state) {
  15226. var fn, promise, pending;
  15227. pending = state.pending;
  15228. state.processScheduled = false;
  15229. state.pending = undefined;
  15230. try {
  15231. for (var i = 0, ii = pending.length; i < ii; ++i) {
  15232. state.pur = true;
  15233. promise = pending[i][0];
  15234. fn = pending[i][state.status];
  15235. try {
  15236. if (isFunction(fn)) {
  15237. resolvePromise(promise, fn(state.value));
  15238. } else if (state.status === 1) {
  15239. resolvePromise(promise, state.value);
  15240. } else {
  15241. rejectPromise(promise, state.value);
  15242. }
  15243. } catch (e) {
  15244. rejectPromise(promise, e);
  15245. }
  15246. }
  15247. } finally {
  15248. --queueSize;
  15249. if (errorOnUnhandledRejections && queueSize === 0) {
  15250. nextTick(processChecks);
  15251. }
  15252. }
  15253. }
  15254. function processChecks() {
  15255. // eslint-disable-next-line no-unmodified-loop-condition
  15256. while (!queueSize && checkQueue.length) {
  15257. var toCheck = checkQueue.shift();
  15258. if (!toCheck.pur) {
  15259. toCheck.pur = true;
  15260. var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);
  15261. if (toCheck.value instanceof Error) {
  15262. exceptionHandler(toCheck.value, errorMessage);
  15263. } else {
  15264. exceptionHandler(errorMessage);
  15265. }
  15266. }
  15267. }
  15268. }
  15269. function scheduleProcessQueue(state) {
  15270. if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !state.pur) {
  15271. if (queueSize === 0 && checkQueue.length === 0) {
  15272. nextTick(processChecks);
  15273. }
  15274. checkQueue.push(state);
  15275. }
  15276. if (state.processScheduled || !state.pending) return;
  15277. state.processScheduled = true;
  15278. ++queueSize;
  15279. nextTick(function() { processQueue(state); });
  15280. }
  15281. function resolvePromise(promise, val) {
  15282. if (promise.$$state.status) return;
  15283. if (val === promise) {
  15284. $$reject(promise, $qMinErr(
  15285. 'qcycle',
  15286. 'Expected promise to be resolved with value other than itself \'{0}\'',
  15287. val));
  15288. } else {
  15289. $$resolve(promise, val);
  15290. }
  15291. }
  15292. function $$resolve(promise, val) {
  15293. var then;
  15294. var done = false;
  15295. try {
  15296. if (isObject(val) || isFunction(val)) then = val.then;
  15297. if (isFunction(then)) {
  15298. promise.$$state.status = -1;
  15299. then.call(val, doResolve, doReject, doNotify);
  15300. } else {
  15301. promise.$$state.value = val;
  15302. promise.$$state.status = 1;
  15303. scheduleProcessQueue(promise.$$state);
  15304. }
  15305. } catch (e) {
  15306. doReject(e);
  15307. }
  15308. function doResolve(val) {
  15309. if (done) return;
  15310. done = true;
  15311. $$resolve(promise, val);
  15312. }
  15313. function doReject(val) {
  15314. if (done) return;
  15315. done = true;
  15316. $$reject(promise, val);
  15317. }
  15318. function doNotify(progress) {
  15319. notifyPromise(promise, progress);
  15320. }
  15321. }
  15322. function rejectPromise(promise, reason) {
  15323. if (promise.$$state.status) return;
  15324. $$reject(promise, reason);
  15325. }
  15326. function $$reject(promise, reason) {
  15327. promise.$$state.value = reason;
  15328. promise.$$state.status = 2;
  15329. scheduleProcessQueue(promise.$$state);
  15330. }
  15331. function notifyPromise(promise, progress) {
  15332. var callbacks = promise.$$state.pending;
  15333. if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {
  15334. nextTick(function() {
  15335. var callback, result;
  15336. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  15337. result = callbacks[i][0];
  15338. callback = callbacks[i][3];
  15339. try {
  15340. notifyPromise(result, isFunction(callback) ? callback(progress) : progress);
  15341. } catch (e) {
  15342. exceptionHandler(e);
  15343. }
  15344. }
  15345. });
  15346. }
  15347. }
  15348. /**
  15349. * @ngdoc method
  15350. * @name $q#reject
  15351. * @kind function
  15352. *
  15353. * @description
  15354. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  15355. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  15356. * a promise chain, you don't need to worry about it.
  15357. *
  15358. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  15359. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  15360. * a promise error callback and you want to forward the error to the promise derived from the
  15361. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  15362. * `reject`.
  15363. *
  15364. * ```js
  15365. * promiseB = promiseA.then(function(result) {
  15366. * // success: do something and resolve promiseB
  15367. * // with the old or a new result
  15368. * return result;
  15369. * }, function(reason) {
  15370. * // error: handle the error if possible and
  15371. * // resolve promiseB with newPromiseOrValue,
  15372. * // otherwise forward the rejection to promiseB
  15373. * if (canHandle(reason)) {
  15374. * // handle the error and recover
  15375. * return newPromiseOrValue;
  15376. * }
  15377. * return $q.reject(reason);
  15378. * });
  15379. * ```
  15380. *
  15381. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  15382. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  15383. */
  15384. function reject(reason) {
  15385. var result = new Promise();
  15386. rejectPromise(result, reason);
  15387. return result;
  15388. }
  15389. function handleCallback(value, resolver, callback) {
  15390. var callbackOutput = null;
  15391. try {
  15392. if (isFunction(callback)) callbackOutput = callback();
  15393. } catch (e) {
  15394. return reject(e);
  15395. }
  15396. if (isPromiseLike(callbackOutput)) {
  15397. return callbackOutput.then(function() {
  15398. return resolver(value);
  15399. }, reject);
  15400. } else {
  15401. return resolver(value);
  15402. }
  15403. }
  15404. /**
  15405. * @ngdoc method
  15406. * @name $q#when
  15407. * @kind function
  15408. *
  15409. * @description
  15410. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  15411. * This is useful when you are dealing with an object that might or might not be a promise, or if
  15412. * the promise comes from a source that can't be trusted.
  15413. *
  15414. * @param {*} value Value or a promise
  15415. * @param {Function=} successCallback
  15416. * @param {Function=} errorCallback
  15417. * @param {Function=} progressCallback
  15418. * @returns {Promise} Returns a promise of the passed value or promise
  15419. */
  15420. function when(value, callback, errback, progressBack) {
  15421. var result = new Promise();
  15422. resolvePromise(result, value);
  15423. return result.then(callback, errback, progressBack);
  15424. }
  15425. /**
  15426. * @ngdoc method
  15427. * @name $q#resolve
  15428. * @kind function
  15429. *
  15430. * @description
  15431. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  15432. *
  15433. * @param {*} value Value or a promise
  15434. * @param {Function=} successCallback
  15435. * @param {Function=} errorCallback
  15436. * @param {Function=} progressCallback
  15437. * @returns {Promise} Returns a promise of the passed value or promise
  15438. */
  15439. var resolve = when;
  15440. /**
  15441. * @ngdoc method
  15442. * @name $q#all
  15443. * @kind function
  15444. *
  15445. * @description
  15446. * Combines multiple promises into a single promise that is resolved when all of the input
  15447. * promises are resolved.
  15448. *
  15449. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15450. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  15451. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  15452. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  15453. * with the same rejection value.
  15454. */
  15455. function all(promises) {
  15456. var result = new Promise(),
  15457. counter = 0,
  15458. results = isArray(promises) ? [] : {};
  15459. forEach(promises, function(promise, key) {
  15460. counter++;
  15461. when(promise).then(function(value) {
  15462. results[key] = value;
  15463. if (!(--counter)) resolvePromise(result, results);
  15464. }, function(reason) {
  15465. rejectPromise(result, reason);
  15466. });
  15467. });
  15468. if (counter === 0) {
  15469. resolvePromise(result, results);
  15470. }
  15471. return result;
  15472. }
  15473. /**
  15474. * @ngdoc method
  15475. * @name $q#race
  15476. * @kind function
  15477. *
  15478. * @description
  15479. * Returns a promise that resolves or rejects as soon as one of those promises
  15480. * resolves or rejects, with the value or reason from that promise.
  15481. *
  15482. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15483. * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
  15484. * resolves or rejects, with the value or reason from that promise.
  15485. */
  15486. function race(promises) {
  15487. var deferred = defer();
  15488. forEach(promises, function(promise) {
  15489. when(promise).then(deferred.resolve, deferred.reject);
  15490. });
  15491. return deferred.promise;
  15492. }
  15493. function $Q(resolver) {
  15494. if (!isFunction(resolver)) {
  15495. throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
  15496. }
  15497. var promise = new Promise();
  15498. function resolveFn(value) {
  15499. resolvePromise(promise, value);
  15500. }
  15501. function rejectFn(reason) {
  15502. rejectPromise(promise, reason);
  15503. }
  15504. resolver(resolveFn, rejectFn);
  15505. return promise;
  15506. }
  15507. // Let's make the instanceof operator work for promises, so that
  15508. // `new $q(fn) instanceof $q` would evaluate to true.
  15509. $Q.prototype = Promise.prototype;
  15510. $Q.defer = defer;
  15511. $Q.reject = reject;
  15512. $Q.when = when;
  15513. $Q.resolve = resolve;
  15514. $Q.all = all;
  15515. $Q.race = race;
  15516. return $Q;
  15517. }
  15518. /** @this */
  15519. function $$RAFProvider() { //rAF
  15520. this.$get = ['$window', '$timeout', function($window, $timeout) {
  15521. var requestAnimationFrame = $window.requestAnimationFrame ||
  15522. $window.webkitRequestAnimationFrame;
  15523. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  15524. $window.webkitCancelAnimationFrame ||
  15525. $window.webkitCancelRequestAnimationFrame;
  15526. var rafSupported = !!requestAnimationFrame;
  15527. var raf = rafSupported
  15528. ? function(fn) {
  15529. var id = requestAnimationFrame(fn);
  15530. return function() {
  15531. cancelAnimationFrame(id);
  15532. };
  15533. }
  15534. : function(fn) {
  15535. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  15536. return function() {
  15537. $timeout.cancel(timer);
  15538. };
  15539. };
  15540. raf.supported = rafSupported;
  15541. return raf;
  15542. }];
  15543. }
  15544. /**
  15545. * DESIGN NOTES
  15546. *
  15547. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  15548. *
  15549. * The typical use of scope is to watch the expressions, which most of the time return the same
  15550. * value as last time so we optimize the operation.
  15551. *
  15552. * Closures construction is expensive in terms of speed as well as memory:
  15553. * - No closures, instead use prototypical inheritance for API
  15554. * - Internal state needs to be stored on scope directly, which means that private state is
  15555. * exposed as $$____ properties
  15556. *
  15557. * Loop operations are optimized by using while(count--) { ... }
  15558. * - This means that in order to keep the same order of execution as addition we have to add
  15559. * items to the array at the beginning (unshift) instead of at the end (push)
  15560. *
  15561. * Child scopes are created and removed often
  15562. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  15563. *
  15564. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  15565. * in the same way as watch. Watch requires return of the initialization function which is expensive
  15566. * to construct.
  15567. */
  15568. /**
  15569. * @ngdoc provider
  15570. * @name $rootScopeProvider
  15571. * @description
  15572. *
  15573. * Provider for the $rootScope service.
  15574. */
  15575. /**
  15576. * @ngdoc method
  15577. * @name $rootScopeProvider#digestTtl
  15578. * @description
  15579. *
  15580. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  15581. * assuming that the model is unstable.
  15582. *
  15583. * The current default is 10 iterations.
  15584. *
  15585. * In complex applications it's possible that the dependencies between `$watch`s will result in
  15586. * several digest iterations. However if an application needs more than the default 10 digest
  15587. * iterations for its model to stabilize then you should investigate what is causing the model to
  15588. * continuously change during the digest.
  15589. *
  15590. * Increasing the TTL could have performance implications, so you should not change it without
  15591. * proper justification.
  15592. *
  15593. * @param {number} limit The number of digest iterations.
  15594. */
  15595. /**
  15596. * @ngdoc service
  15597. * @name $rootScope
  15598. * @this
  15599. *
  15600. * @description
  15601. *
  15602. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  15603. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  15604. * between the model and the view, via a mechanism for watching the model for changes.
  15605. * They also provide event emission/broadcast and subscription facility. See the
  15606. * {@link guide/scope developer guide on scopes}.
  15607. */
  15608. function $RootScopeProvider() {
  15609. var TTL = 10;
  15610. var $rootScopeMinErr = minErr('$rootScope');
  15611. var lastDirtyWatch = null;
  15612. var applyAsyncId = null;
  15613. this.digestTtl = function(value) {
  15614. if (arguments.length) {
  15615. TTL = value;
  15616. }
  15617. return TTL;
  15618. };
  15619. function createChildScopeClass(parent) {
  15620. function ChildScope() {
  15621. this.$$watchers = this.$$nextSibling =
  15622. this.$$childHead = this.$$childTail = null;
  15623. this.$$listeners = {};
  15624. this.$$listenerCount = {};
  15625. this.$$watchersCount = 0;
  15626. this.$id = nextUid();
  15627. this.$$ChildScope = null;
  15628. }
  15629. ChildScope.prototype = parent;
  15630. return ChildScope;
  15631. }
  15632. this.$get = ['$exceptionHandler', '$parse', '$browser',
  15633. function($exceptionHandler, $parse, $browser) {
  15634. function destroyChildScope($event) {
  15635. $event.currentScope.$$destroyed = true;
  15636. }
  15637. function cleanUpScope($scope) {
  15638. // Support: IE 9 only
  15639. if (msie === 9) {
  15640. // There is a memory leak in IE9 if all child scopes are not disconnected
  15641. // completely when a scope is destroyed. So this code will recurse up through
  15642. // all this scopes children
  15643. //
  15644. // See issue https://github.com/angular/angular.js/issues/10706
  15645. if ($scope.$$childHead) {
  15646. cleanUpScope($scope.$$childHead);
  15647. }
  15648. if ($scope.$$nextSibling) {
  15649. cleanUpScope($scope.$$nextSibling);
  15650. }
  15651. }
  15652. // The code below works around IE9 and V8's memory leaks
  15653. //
  15654. // See:
  15655. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  15656. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  15657. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  15658. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  15659. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  15660. }
  15661. /**
  15662. * @ngdoc type
  15663. * @name $rootScope.Scope
  15664. *
  15665. * @description
  15666. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  15667. * {@link auto.$injector $injector}. Child scopes are created using the
  15668. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  15669. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  15670. * an in-depth introduction and usage examples.
  15671. *
  15672. *
  15673. * # Inheritance
  15674. * A scope can inherit from a parent scope, as in this example:
  15675. * ```js
  15676. var parent = $rootScope;
  15677. var child = parent.$new();
  15678. parent.salutation = "Hello";
  15679. expect(child.salutation).toEqual('Hello');
  15680. child.salutation = "Welcome";
  15681. expect(child.salutation).toEqual('Welcome');
  15682. expect(parent.salutation).toEqual('Hello');
  15683. * ```
  15684. *
  15685. * When interacting with `Scope` in tests, additional helper methods are available on the
  15686. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  15687. * details.
  15688. *
  15689. *
  15690. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  15691. * provided for the current scope. Defaults to {@link ng}.
  15692. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  15693. * append/override services provided by `providers`. This is handy
  15694. * when unit-testing and having the need to override a default
  15695. * service.
  15696. * @returns {Object} Newly created scope.
  15697. *
  15698. */
  15699. function Scope() {
  15700. this.$id = nextUid();
  15701. this.$$phase = this.$parent = this.$$watchers =
  15702. this.$$nextSibling = this.$$prevSibling =
  15703. this.$$childHead = this.$$childTail = null;
  15704. this.$root = this;
  15705. this.$$destroyed = false;
  15706. this.$$listeners = {};
  15707. this.$$listenerCount = {};
  15708. this.$$watchersCount = 0;
  15709. this.$$isolateBindings = null;
  15710. }
  15711. /**
  15712. * @ngdoc property
  15713. * @name $rootScope.Scope#$id
  15714. *
  15715. * @description
  15716. * Unique scope ID (monotonically increasing) useful for debugging.
  15717. */
  15718. /**
  15719. * @ngdoc property
  15720. * @name $rootScope.Scope#$parent
  15721. *
  15722. * @description
  15723. * Reference to the parent scope.
  15724. */
  15725. /**
  15726. * @ngdoc property
  15727. * @name $rootScope.Scope#$root
  15728. *
  15729. * @description
  15730. * Reference to the root scope.
  15731. */
  15732. Scope.prototype = {
  15733. constructor: Scope,
  15734. /**
  15735. * @ngdoc method
  15736. * @name $rootScope.Scope#$new
  15737. * @kind function
  15738. *
  15739. * @description
  15740. * Creates a new child {@link ng.$rootScope.Scope scope}.
  15741. *
  15742. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  15743. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  15744. *
  15745. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  15746. * desired for the scope and its child scopes to be permanently detached from the parent and
  15747. * thus stop participating in model change detection and listener notification by invoking.
  15748. *
  15749. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  15750. * parent scope. The scope is isolated, as it can not see parent scope properties.
  15751. * When creating widgets, it is useful for the widget to not accidentally read parent
  15752. * state.
  15753. *
  15754. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  15755. * of the newly created scope. Defaults to `this` scope if not provided.
  15756. * This is used when creating a transclude scope to correctly place it
  15757. * in the scope hierarchy while maintaining the correct prototypical
  15758. * inheritance.
  15759. *
  15760. * @returns {Object} The newly created child scope.
  15761. *
  15762. */
  15763. $new: function(isolate, parent) {
  15764. var child;
  15765. parent = parent || this;
  15766. if (isolate) {
  15767. child = new Scope();
  15768. child.$root = this.$root;
  15769. } else {
  15770. // Only create a child scope class if somebody asks for one,
  15771. // but cache it to allow the VM to optimize lookups.
  15772. if (!this.$$ChildScope) {
  15773. this.$$ChildScope = createChildScopeClass(this);
  15774. }
  15775. child = new this.$$ChildScope();
  15776. }
  15777. child.$parent = parent;
  15778. child.$$prevSibling = parent.$$childTail;
  15779. if (parent.$$childHead) {
  15780. parent.$$childTail.$$nextSibling = child;
  15781. parent.$$childTail = child;
  15782. } else {
  15783. parent.$$childHead = parent.$$childTail = child;
  15784. }
  15785. // When the new scope is not isolated or we inherit from `this`, and
  15786. // the parent scope is destroyed, the property `$$destroyed` is inherited
  15787. // prototypically. In all other cases, this property needs to be set
  15788. // when the parent scope is destroyed.
  15789. // The listener needs to be added after the parent is set
  15790. if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
  15791. return child;
  15792. },
  15793. /**
  15794. * @ngdoc method
  15795. * @name $rootScope.Scope#$watch
  15796. * @kind function
  15797. *
  15798. * @description
  15799. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  15800. *
  15801. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  15802. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  15803. * its value when executed multiple times with the same input because it may be executed multiple
  15804. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  15805. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
  15806. * - The `listener` is called only when the value from the current `watchExpression` and the
  15807. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  15808. * see below). Inequality is determined according to reference inequality,
  15809. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  15810. * via the `!==` Javascript operator, unless `objectEquality == true`
  15811. * (see next point)
  15812. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  15813. * according to the {@link angular.equals} function. To save the value of the object for
  15814. * later comparison, the {@link angular.copy} function is used. This therefore means that
  15815. * watching complex objects will have adverse memory and performance implications.
  15816. * - This should not be used to watch for changes in objects that are
  15817. * or contain [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.
  15818. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  15819. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  15820. * iteration limit is 10 to prevent an infinite loop deadlock.
  15821. *
  15822. *
  15823. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  15824. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  15825. * multiple calls to your `watchExpression` because it will execute multiple times in a
  15826. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  15827. *
  15828. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  15829. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  15830. * watcher. In rare cases, this is undesirable because the listener is called when the result
  15831. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  15832. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  15833. * listener was called due to initialization.
  15834. *
  15835. *
  15836. *
  15837. * # Example
  15838. * ```js
  15839. // let's assume that scope was dependency injected as the $rootScope
  15840. var scope = $rootScope;
  15841. scope.name = 'misko';
  15842. scope.counter = 0;
  15843. expect(scope.counter).toEqual(0);
  15844. scope.$watch('name', function(newValue, oldValue) {
  15845. scope.counter = scope.counter + 1;
  15846. });
  15847. expect(scope.counter).toEqual(0);
  15848. scope.$digest();
  15849. // the listener is always called during the first $digest loop after it was registered
  15850. expect(scope.counter).toEqual(1);
  15851. scope.$digest();
  15852. // but now it will not be called unless the value changes
  15853. expect(scope.counter).toEqual(1);
  15854. scope.name = 'adam';
  15855. scope.$digest();
  15856. expect(scope.counter).toEqual(2);
  15857. // Using a function as a watchExpression
  15858. var food;
  15859. scope.foodCounter = 0;
  15860. expect(scope.foodCounter).toEqual(0);
  15861. scope.$watch(
  15862. // This function returns the value being watched. It is called for each turn of the $digest loop
  15863. function() { return food; },
  15864. // This is the change listener, called when the value returned from the above function changes
  15865. function(newValue, oldValue) {
  15866. if ( newValue !== oldValue ) {
  15867. // Only increment the counter if the value changed
  15868. scope.foodCounter = scope.foodCounter + 1;
  15869. }
  15870. }
  15871. );
  15872. // No digest has been run so the counter will be zero
  15873. expect(scope.foodCounter).toEqual(0);
  15874. // Run the digest but since food has not changed count will still be zero
  15875. scope.$digest();
  15876. expect(scope.foodCounter).toEqual(0);
  15877. // Update food and run digest. Now the counter will increment
  15878. food = 'cheeseburger';
  15879. scope.$digest();
  15880. expect(scope.foodCounter).toEqual(1);
  15881. * ```
  15882. *
  15883. *
  15884. *
  15885. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  15886. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  15887. * a call to the `listener`.
  15888. *
  15889. * - `string`: Evaluated as {@link guide/expression expression}
  15890. * - `function(scope)`: called with current `scope` as a parameter.
  15891. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  15892. * of `watchExpression` changes.
  15893. *
  15894. * - `newVal` contains the current value of the `watchExpression`
  15895. * - `oldVal` contains the previous value of the `watchExpression`
  15896. * - `scope` refers to the current scope
  15897. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  15898. * comparing for reference equality.
  15899. * @returns {function()} Returns a deregistration function for this listener.
  15900. */
  15901. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  15902. var get = $parse(watchExp);
  15903. if (get.$$watchDelegate) {
  15904. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  15905. }
  15906. var scope = this,
  15907. array = scope.$$watchers,
  15908. watcher = {
  15909. fn: listener,
  15910. last: initWatchVal,
  15911. get: get,
  15912. exp: prettyPrintExpression || watchExp,
  15913. eq: !!objectEquality
  15914. };
  15915. lastDirtyWatch = null;
  15916. if (!isFunction(listener)) {
  15917. watcher.fn = noop;
  15918. }
  15919. if (!array) {
  15920. array = scope.$$watchers = [];
  15921. array.$$digestWatchIndex = -1;
  15922. }
  15923. // we use unshift since we use a while loop in $digest for speed.
  15924. // the while loop reads in reverse order.
  15925. array.unshift(watcher);
  15926. array.$$digestWatchIndex++;
  15927. incrementWatchersCount(this, 1);
  15928. return function deregisterWatch() {
  15929. var index = arrayRemove(array, watcher);
  15930. if (index >= 0) {
  15931. incrementWatchersCount(scope, -1);
  15932. if (index < array.$$digestWatchIndex) {
  15933. array.$$digestWatchIndex--;
  15934. }
  15935. }
  15936. lastDirtyWatch = null;
  15937. };
  15938. },
  15939. /**
  15940. * @ngdoc method
  15941. * @name $rootScope.Scope#$watchGroup
  15942. * @kind function
  15943. *
  15944. * @description
  15945. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  15946. * If any one expression in the collection changes the `listener` is executed.
  15947. *
  15948. * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return
  15949. * values are examined for changes on every call to `$digest`.
  15950. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  15951. *
  15952. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  15953. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  15954. *
  15955. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  15956. * expression in `watchExpressions` changes
  15957. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  15958. * those of `watchExpression`
  15959. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  15960. * those of `watchExpression`
  15961. * The `scope` refers to the current scope.
  15962. * @returns {function()} Returns a de-registration function for all listeners.
  15963. */
  15964. $watchGroup: function(watchExpressions, listener) {
  15965. var oldValues = new Array(watchExpressions.length);
  15966. var newValues = new Array(watchExpressions.length);
  15967. var deregisterFns = [];
  15968. var self = this;
  15969. var changeReactionScheduled = false;
  15970. var firstRun = true;
  15971. if (!watchExpressions.length) {
  15972. // No expressions means we call the listener ASAP
  15973. var shouldCall = true;
  15974. self.$evalAsync(function() {
  15975. if (shouldCall) listener(newValues, newValues, self);
  15976. });
  15977. return function deregisterWatchGroup() {
  15978. shouldCall = false;
  15979. };
  15980. }
  15981. if (watchExpressions.length === 1) {
  15982. // Special case size of one
  15983. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  15984. newValues[0] = value;
  15985. oldValues[0] = oldValue;
  15986. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  15987. });
  15988. }
  15989. forEach(watchExpressions, function(expr, i) {
  15990. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  15991. newValues[i] = value;
  15992. oldValues[i] = oldValue;
  15993. if (!changeReactionScheduled) {
  15994. changeReactionScheduled = true;
  15995. self.$evalAsync(watchGroupAction);
  15996. }
  15997. });
  15998. deregisterFns.push(unwatchFn);
  15999. });
  16000. function watchGroupAction() {
  16001. changeReactionScheduled = false;
  16002. if (firstRun) {
  16003. firstRun = false;
  16004. listener(newValues, newValues, self);
  16005. } else {
  16006. listener(newValues, oldValues, self);
  16007. }
  16008. }
  16009. return function deregisterWatchGroup() {
  16010. while (deregisterFns.length) {
  16011. deregisterFns.shift()();
  16012. }
  16013. };
  16014. },
  16015. /**
  16016. * @ngdoc method
  16017. * @name $rootScope.Scope#$watchCollection
  16018. * @kind function
  16019. *
  16020. * @description
  16021. * Shallow watches the properties of an object and fires whenever any of the properties change
  16022. * (for arrays, this implies watching the array items; for object maps, this implies watching
  16023. * the properties). If a change is detected, the `listener` callback is fired.
  16024. *
  16025. * - The `obj` collection is observed via standard $watch operation and is examined on every
  16026. * call to $digest() to see if any items have been added, removed, or moved.
  16027. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  16028. * adding, removing, and moving items belonging to an object or array.
  16029. *
  16030. *
  16031. * # Example
  16032. * ```js
  16033. $scope.names = ['igor', 'matias', 'misko', 'james'];
  16034. $scope.dataCount = 4;
  16035. $scope.$watchCollection('names', function(newNames, oldNames) {
  16036. $scope.dataCount = newNames.length;
  16037. });
  16038. expect($scope.dataCount).toEqual(4);
  16039. $scope.$digest();
  16040. //still at 4 ... no changes
  16041. expect($scope.dataCount).toEqual(4);
  16042. $scope.names.pop();
  16043. $scope.$digest();
  16044. //now there's been a change
  16045. expect($scope.dataCount).toEqual(3);
  16046. * ```
  16047. *
  16048. *
  16049. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  16050. * expression value should evaluate to an object or an array which is observed on each
  16051. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  16052. * collection will trigger a call to the `listener`.
  16053. *
  16054. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  16055. * when a change is detected.
  16056. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  16057. * - The `oldCollection` object is a copy of the former collection data.
  16058. * Due to performance considerations, the`oldCollection` value is computed only if the
  16059. * `listener` function declares two or more arguments.
  16060. * - The `scope` argument refers to the current scope.
  16061. *
  16062. * @returns {function()} Returns a de-registration function for this listener. When the
  16063. * de-registration function is executed, the internal watch operation is terminated.
  16064. */
  16065. $watchCollection: function(obj, listener) {
  16066. $watchCollectionInterceptor.$stateful = true;
  16067. var self = this;
  16068. // the current value, updated on each dirty-check run
  16069. var newValue;
  16070. // a shallow copy of the newValue from the last dirty-check run,
  16071. // updated to match newValue during dirty-check run
  16072. var oldValue;
  16073. // a shallow copy of the newValue from when the last change happened
  16074. var veryOldValue;
  16075. // only track veryOldValue if the listener is asking for it
  16076. var trackVeryOldValue = (listener.length > 1);
  16077. var changeDetected = 0;
  16078. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  16079. var internalArray = [];
  16080. var internalObject = {};
  16081. var initRun = true;
  16082. var oldLength = 0;
  16083. function $watchCollectionInterceptor(_value) {
  16084. newValue = _value;
  16085. var newLength, key, bothNaN, newItem, oldItem;
  16086. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  16087. if (isUndefined(newValue)) return;
  16088. if (!isObject(newValue)) { // if primitive
  16089. if (oldValue !== newValue) {
  16090. oldValue = newValue;
  16091. changeDetected++;
  16092. }
  16093. } else if (isArrayLike(newValue)) {
  16094. if (oldValue !== internalArray) {
  16095. // we are transitioning from something which was not an array into array.
  16096. oldValue = internalArray;
  16097. oldLength = oldValue.length = 0;
  16098. changeDetected++;
  16099. }
  16100. newLength = newValue.length;
  16101. if (oldLength !== newLength) {
  16102. // if lengths do not match we need to trigger change notification
  16103. changeDetected++;
  16104. oldValue.length = oldLength = newLength;
  16105. }
  16106. // copy the items to oldValue and look for changes.
  16107. for (var i = 0; i < newLength; i++) {
  16108. oldItem = oldValue[i];
  16109. newItem = newValue[i];
  16110. // eslint-disable-next-line no-self-compare
  16111. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16112. if (!bothNaN && (oldItem !== newItem)) {
  16113. changeDetected++;
  16114. oldValue[i] = newItem;
  16115. }
  16116. }
  16117. } else {
  16118. if (oldValue !== internalObject) {
  16119. // we are transitioning from something which was not an object into object.
  16120. oldValue = internalObject = {};
  16121. oldLength = 0;
  16122. changeDetected++;
  16123. }
  16124. // copy the items to oldValue and look for changes.
  16125. newLength = 0;
  16126. for (key in newValue) {
  16127. if (hasOwnProperty.call(newValue, key)) {
  16128. newLength++;
  16129. newItem = newValue[key];
  16130. oldItem = oldValue[key];
  16131. if (key in oldValue) {
  16132. // eslint-disable-next-line no-self-compare
  16133. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16134. if (!bothNaN && (oldItem !== newItem)) {
  16135. changeDetected++;
  16136. oldValue[key] = newItem;
  16137. }
  16138. } else {
  16139. oldLength++;
  16140. oldValue[key] = newItem;
  16141. changeDetected++;
  16142. }
  16143. }
  16144. }
  16145. if (oldLength > newLength) {
  16146. // we used to have more keys, need to find them and destroy them.
  16147. changeDetected++;
  16148. for (key in oldValue) {
  16149. if (!hasOwnProperty.call(newValue, key)) {
  16150. oldLength--;
  16151. delete oldValue[key];
  16152. }
  16153. }
  16154. }
  16155. }
  16156. return changeDetected;
  16157. }
  16158. function $watchCollectionAction() {
  16159. if (initRun) {
  16160. initRun = false;
  16161. listener(newValue, newValue, self);
  16162. } else {
  16163. listener(newValue, veryOldValue, self);
  16164. }
  16165. // make a copy for the next time a collection is changed
  16166. if (trackVeryOldValue) {
  16167. if (!isObject(newValue)) {
  16168. //primitive
  16169. veryOldValue = newValue;
  16170. } else if (isArrayLike(newValue)) {
  16171. veryOldValue = new Array(newValue.length);
  16172. for (var i = 0; i < newValue.length; i++) {
  16173. veryOldValue[i] = newValue[i];
  16174. }
  16175. } else { // if object
  16176. veryOldValue = {};
  16177. for (var key in newValue) {
  16178. if (hasOwnProperty.call(newValue, key)) {
  16179. veryOldValue[key] = newValue[key];
  16180. }
  16181. }
  16182. }
  16183. }
  16184. }
  16185. return this.$watch(changeDetector, $watchCollectionAction);
  16186. },
  16187. /**
  16188. * @ngdoc method
  16189. * @name $rootScope.Scope#$digest
  16190. * @kind function
  16191. *
  16192. * @description
  16193. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  16194. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  16195. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  16196. * until no more listeners are firing. This means that it is possible to get into an infinite
  16197. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  16198. * iterations exceeds 10.
  16199. *
  16200. * Usually, you don't call `$digest()` directly in
  16201. * {@link ng.directive:ngController controllers} or in
  16202. * {@link ng.$compileProvider#directive directives}.
  16203. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  16204. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  16205. *
  16206. * If you want to be notified whenever `$digest()` is called,
  16207. * you can register a `watchExpression` function with
  16208. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  16209. *
  16210. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  16211. *
  16212. * # Example
  16213. * ```js
  16214. var scope = ...;
  16215. scope.name = 'misko';
  16216. scope.counter = 0;
  16217. expect(scope.counter).toEqual(0);
  16218. scope.$watch('name', function(newValue, oldValue) {
  16219. scope.counter = scope.counter + 1;
  16220. });
  16221. expect(scope.counter).toEqual(0);
  16222. scope.$digest();
  16223. // the listener is always called during the first $digest loop after it was registered
  16224. expect(scope.counter).toEqual(1);
  16225. scope.$digest();
  16226. // but now it will not be called unless the value changes
  16227. expect(scope.counter).toEqual(1);
  16228. scope.name = 'adam';
  16229. scope.$digest();
  16230. expect(scope.counter).toEqual(2);
  16231. * ```
  16232. *
  16233. */
  16234. $digest: function() {
  16235. var watch, value, last, fn, get,
  16236. watchers,
  16237. dirty, ttl = TTL,
  16238. next, current, target = this,
  16239. watchLog = [],
  16240. logIdx, asyncTask;
  16241. beginPhase('$digest');
  16242. // Check for changes to browser url that happened in sync before the call to $digest
  16243. $browser.$$checkUrlChange();
  16244. if (this === $rootScope && applyAsyncId !== null) {
  16245. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  16246. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  16247. $browser.defer.cancel(applyAsyncId);
  16248. flushApplyAsync();
  16249. }
  16250. lastDirtyWatch = null;
  16251. do { // "while dirty" loop
  16252. dirty = false;
  16253. current = target;
  16254. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  16255. // be reentered recursively. Calling $digest from a function passed to $evalAsync would
  16256. // lead to a '$digest already in progress' error.
  16257. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  16258. try {
  16259. asyncTask = asyncQueue[asyncQueuePosition];
  16260. fn = asyncTask.fn;
  16261. fn(asyncTask.scope, asyncTask.locals);
  16262. } catch (e) {
  16263. $exceptionHandler(e);
  16264. }
  16265. lastDirtyWatch = null;
  16266. }
  16267. asyncQueue.length = 0;
  16268. traverseScopesLoop:
  16269. do { // "traverse the scopes" loop
  16270. if ((watchers = current.$$watchers)) {
  16271. // process our watches
  16272. watchers.$$digestWatchIndex = watchers.length;
  16273. while (watchers.$$digestWatchIndex--) {
  16274. try {
  16275. watch = watchers[watchers.$$digestWatchIndex];
  16276. // Most common watches are on primitives, in which case we can short
  16277. // circuit it with === operator, only when === fails do we use .equals
  16278. if (watch) {
  16279. get = watch.get;
  16280. if ((value = get(current)) !== (last = watch.last) &&
  16281. !(watch.eq
  16282. ? equals(value, last)
  16283. : (isNumberNaN(value) && isNumberNaN(last)))) {
  16284. dirty = true;
  16285. lastDirtyWatch = watch;
  16286. watch.last = watch.eq ? copy(value, null) : value;
  16287. fn = watch.fn;
  16288. fn(value, ((last === initWatchVal) ? value : last), current);
  16289. if (ttl < 5) {
  16290. logIdx = 4 - ttl;
  16291. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  16292. watchLog[logIdx].push({
  16293. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  16294. newVal: value,
  16295. oldVal: last
  16296. });
  16297. }
  16298. } else if (watch === lastDirtyWatch) {
  16299. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  16300. // have already been tested.
  16301. dirty = false;
  16302. break traverseScopesLoop;
  16303. }
  16304. }
  16305. } catch (e) {
  16306. $exceptionHandler(e);
  16307. }
  16308. }
  16309. }
  16310. // Insanity Warning: scope depth-first traversal
  16311. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16312. // this piece should be kept in sync with the traversal in $broadcast
  16313. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  16314. (current !== target && current.$$nextSibling)))) {
  16315. while (current !== target && !(next = current.$$nextSibling)) {
  16316. current = current.$parent;
  16317. }
  16318. }
  16319. } while ((current = next));
  16320. // `break traverseScopesLoop;` takes us to here
  16321. if ((dirty || asyncQueue.length) && !(ttl--)) {
  16322. clearPhase();
  16323. throw $rootScopeMinErr('infdig',
  16324. '{0} $digest() iterations reached. Aborting!\n' +
  16325. 'Watchers fired in the last 5 iterations: {1}',
  16326. TTL, watchLog);
  16327. }
  16328. } while (dirty || asyncQueue.length);
  16329. clearPhase();
  16330. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  16331. while (postDigestQueuePosition < postDigestQueue.length) {
  16332. try {
  16333. postDigestQueue[postDigestQueuePosition++]();
  16334. } catch (e) {
  16335. $exceptionHandler(e);
  16336. }
  16337. }
  16338. postDigestQueue.length = postDigestQueuePosition = 0;
  16339. // Check for changes to browser url that happened during the $digest
  16340. // (for which no event is fired; e.g. via `history.pushState()`)
  16341. $browser.$$checkUrlChange();
  16342. },
  16343. /**
  16344. * @ngdoc event
  16345. * @name $rootScope.Scope#$destroy
  16346. * @eventType broadcast on scope being destroyed
  16347. *
  16348. * @description
  16349. * Broadcasted when a scope and its children are being destroyed.
  16350. *
  16351. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16352. * clean up DOM bindings before an element is removed from the DOM.
  16353. */
  16354. /**
  16355. * @ngdoc method
  16356. * @name $rootScope.Scope#$destroy
  16357. * @kind function
  16358. *
  16359. * @description
  16360. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  16361. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  16362. * propagate to the current scope and its children. Removal also implies that the current
  16363. * scope is eligible for garbage collection.
  16364. *
  16365. * The `$destroy()` is usually used by directives such as
  16366. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  16367. * unrolling of the loop.
  16368. *
  16369. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  16370. * Application code can register a `$destroy` event handler that will give it a chance to
  16371. * perform any necessary cleanup.
  16372. *
  16373. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16374. * clean up DOM bindings before an element is removed from the DOM.
  16375. */
  16376. $destroy: function() {
  16377. // We can't destroy a scope that has been already destroyed.
  16378. if (this.$$destroyed) return;
  16379. var parent = this.$parent;
  16380. this.$broadcast('$destroy');
  16381. this.$$destroyed = true;
  16382. if (this === $rootScope) {
  16383. //Remove handlers attached to window when $rootScope is removed
  16384. $browser.$$applicationDestroyed();
  16385. }
  16386. incrementWatchersCount(this, -this.$$watchersCount);
  16387. for (var eventName in this.$$listenerCount) {
  16388. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  16389. }
  16390. // sever all the references to parent scopes (after this cleanup, the current scope should
  16391. // not be retained by any of our references and should be eligible for garbage collection)
  16392. if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
  16393. if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
  16394. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  16395. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  16396. // Disable listeners, watchers and apply/digest methods
  16397. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  16398. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  16399. this.$$listeners = {};
  16400. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  16401. this.$$nextSibling = null;
  16402. cleanUpScope(this);
  16403. },
  16404. /**
  16405. * @ngdoc method
  16406. * @name $rootScope.Scope#$eval
  16407. * @kind function
  16408. *
  16409. * @description
  16410. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  16411. * the expression are propagated (uncaught). This is useful when evaluating Angular
  16412. * expressions.
  16413. *
  16414. * # Example
  16415. * ```js
  16416. var scope = ng.$rootScope.Scope();
  16417. scope.a = 1;
  16418. scope.b = 2;
  16419. expect(scope.$eval('a+b')).toEqual(3);
  16420. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  16421. * ```
  16422. *
  16423. * @param {(string|function())=} expression An angular expression to be executed.
  16424. *
  16425. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16426. * - `function(scope)`: execute the function with the current `scope` parameter.
  16427. *
  16428. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16429. * @returns {*} The result of evaluating the expression.
  16430. */
  16431. $eval: function(expr, locals) {
  16432. return $parse(expr)(this, locals);
  16433. },
  16434. /**
  16435. * @ngdoc method
  16436. * @name $rootScope.Scope#$evalAsync
  16437. * @kind function
  16438. *
  16439. * @description
  16440. * Executes the expression on the current scope at a later point in time.
  16441. *
  16442. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  16443. * that:
  16444. *
  16445. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  16446. * rendering).
  16447. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  16448. * `expression` execution.
  16449. *
  16450. * Any exceptions from the execution of the expression are forwarded to the
  16451. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16452. *
  16453. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  16454. * will be scheduled. However, it is encouraged to always call code that changes the model
  16455. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  16456. *
  16457. * @param {(string|function())=} expression An angular expression to be executed.
  16458. *
  16459. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16460. * - `function(scope)`: execute the function with the current `scope` parameter.
  16461. *
  16462. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16463. */
  16464. $evalAsync: function(expr, locals) {
  16465. // if we are outside of an $digest loop and this is the first time we are scheduling async
  16466. // task also schedule async auto-flush
  16467. if (!$rootScope.$$phase && !asyncQueue.length) {
  16468. $browser.defer(function() {
  16469. if (asyncQueue.length) {
  16470. $rootScope.$digest();
  16471. }
  16472. });
  16473. }
  16474. asyncQueue.push({scope: this, fn: $parse(expr), locals: locals});
  16475. },
  16476. $$postDigest: function(fn) {
  16477. postDigestQueue.push(fn);
  16478. },
  16479. /**
  16480. * @ngdoc method
  16481. * @name $rootScope.Scope#$apply
  16482. * @kind function
  16483. *
  16484. * @description
  16485. * `$apply()` is used to execute an expression in angular from outside of the angular
  16486. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  16487. * Because we are calling into the angular framework we need to perform proper scope life
  16488. * cycle of {@link ng.$exceptionHandler exception handling},
  16489. * {@link ng.$rootScope.Scope#$digest executing watches}.
  16490. *
  16491. * ## Life cycle
  16492. *
  16493. * # Pseudo-Code of `$apply()`
  16494. * ```js
  16495. function $apply(expr) {
  16496. try {
  16497. return $eval(expr);
  16498. } catch (e) {
  16499. $exceptionHandler(e);
  16500. } finally {
  16501. $root.$digest();
  16502. }
  16503. }
  16504. * ```
  16505. *
  16506. *
  16507. * Scope's `$apply()` method transitions through the following stages:
  16508. *
  16509. * 1. The {@link guide/expression expression} is executed using the
  16510. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  16511. * 2. Any exceptions from the execution of the expression are forwarded to the
  16512. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16513. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  16514. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  16515. *
  16516. *
  16517. * @param {(string|function())=} exp An angular expression to be executed.
  16518. *
  16519. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16520. * - `function(scope)`: execute the function with current `scope` parameter.
  16521. *
  16522. * @returns {*} The result of evaluating the expression.
  16523. */
  16524. $apply: function(expr) {
  16525. try {
  16526. beginPhase('$apply');
  16527. try {
  16528. return this.$eval(expr);
  16529. } finally {
  16530. clearPhase();
  16531. }
  16532. } catch (e) {
  16533. $exceptionHandler(e);
  16534. } finally {
  16535. try {
  16536. $rootScope.$digest();
  16537. } catch (e) {
  16538. $exceptionHandler(e);
  16539. // eslint-disable-next-line no-unsafe-finally
  16540. throw e;
  16541. }
  16542. }
  16543. },
  16544. /**
  16545. * @ngdoc method
  16546. * @name $rootScope.Scope#$applyAsync
  16547. * @kind function
  16548. *
  16549. * @description
  16550. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  16551. * varies across browsers, but is typically around ~10 milliseconds.
  16552. *
  16553. * This can be used to queue up multiple expressions which need to be evaluated in the same
  16554. * digest.
  16555. *
  16556. * @param {(string|function())=} exp An angular expression to be executed.
  16557. *
  16558. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16559. * - `function(scope)`: execute the function with current `scope` parameter.
  16560. */
  16561. $applyAsync: function(expr) {
  16562. var scope = this;
  16563. if (expr) {
  16564. applyAsyncQueue.push($applyAsyncExpression);
  16565. }
  16566. expr = $parse(expr);
  16567. scheduleApplyAsync();
  16568. function $applyAsyncExpression() {
  16569. scope.$eval(expr);
  16570. }
  16571. },
  16572. /**
  16573. * @ngdoc method
  16574. * @name $rootScope.Scope#$on
  16575. * @kind function
  16576. *
  16577. * @description
  16578. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  16579. * discussion of event life cycle.
  16580. *
  16581. * The event listener function format is: `function(event, args...)`. The `event` object
  16582. * passed into the listener has the following attributes:
  16583. *
  16584. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  16585. * `$broadcast`-ed.
  16586. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  16587. * event propagates through the scope hierarchy, this property is set to null.
  16588. * - `name` - `{string}`: name of the event.
  16589. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  16590. * further event propagation (available only for events that were `$emit`-ed).
  16591. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  16592. * to true.
  16593. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  16594. *
  16595. * @param {string} name Event name to listen on.
  16596. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  16597. * @returns {function()} Returns a deregistration function for this listener.
  16598. */
  16599. $on: function(name, listener) {
  16600. var namedListeners = this.$$listeners[name];
  16601. if (!namedListeners) {
  16602. this.$$listeners[name] = namedListeners = [];
  16603. }
  16604. namedListeners.push(listener);
  16605. var current = this;
  16606. do {
  16607. if (!current.$$listenerCount[name]) {
  16608. current.$$listenerCount[name] = 0;
  16609. }
  16610. current.$$listenerCount[name]++;
  16611. } while ((current = current.$parent));
  16612. var self = this;
  16613. return function() {
  16614. var indexOfListener = namedListeners.indexOf(listener);
  16615. if (indexOfListener !== -1) {
  16616. namedListeners[indexOfListener] = null;
  16617. decrementListenerCount(self, 1, name);
  16618. }
  16619. };
  16620. },
  16621. /**
  16622. * @ngdoc method
  16623. * @name $rootScope.Scope#$emit
  16624. * @kind function
  16625. *
  16626. * @description
  16627. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  16628. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16629. *
  16630. * The event life cycle starts at the scope on which `$emit` was called. All
  16631. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16632. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  16633. * registered listeners along the way. The event will stop propagating if one of the listeners
  16634. * cancels it.
  16635. *
  16636. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16637. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16638. *
  16639. * @param {string} name Event name to emit.
  16640. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16641. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  16642. */
  16643. $emit: function(name, args) {
  16644. var empty = [],
  16645. namedListeners,
  16646. scope = this,
  16647. stopPropagation = false,
  16648. event = {
  16649. name: name,
  16650. targetScope: scope,
  16651. stopPropagation: function() {stopPropagation = true;},
  16652. preventDefault: function() {
  16653. event.defaultPrevented = true;
  16654. },
  16655. defaultPrevented: false
  16656. },
  16657. listenerArgs = concat([event], arguments, 1),
  16658. i, length;
  16659. do {
  16660. namedListeners = scope.$$listeners[name] || empty;
  16661. event.currentScope = scope;
  16662. for (i = 0, length = namedListeners.length; i < length; i++) {
  16663. // if listeners were deregistered, defragment the array
  16664. if (!namedListeners[i]) {
  16665. namedListeners.splice(i, 1);
  16666. i--;
  16667. length--;
  16668. continue;
  16669. }
  16670. try {
  16671. //allow all listeners attached to the current scope to run
  16672. namedListeners[i].apply(null, listenerArgs);
  16673. } catch (e) {
  16674. $exceptionHandler(e);
  16675. }
  16676. }
  16677. //if any listener on the current scope stops propagation, prevent bubbling
  16678. if (stopPropagation) {
  16679. event.currentScope = null;
  16680. return event;
  16681. }
  16682. //traverse upwards
  16683. scope = scope.$parent;
  16684. } while (scope);
  16685. event.currentScope = null;
  16686. return event;
  16687. },
  16688. /**
  16689. * @ngdoc method
  16690. * @name $rootScope.Scope#$broadcast
  16691. * @kind function
  16692. *
  16693. * @description
  16694. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  16695. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16696. *
  16697. * The event life cycle starts at the scope on which `$broadcast` was called. All
  16698. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16699. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  16700. * scope and calls all registered listeners along the way. The event cannot be canceled.
  16701. *
  16702. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16703. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16704. *
  16705. * @param {string} name Event name to broadcast.
  16706. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16707. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  16708. */
  16709. $broadcast: function(name, args) {
  16710. var target = this,
  16711. current = target,
  16712. next = target,
  16713. event = {
  16714. name: name,
  16715. targetScope: target,
  16716. preventDefault: function() {
  16717. event.defaultPrevented = true;
  16718. },
  16719. defaultPrevented: false
  16720. };
  16721. if (!target.$$listenerCount[name]) return event;
  16722. var listenerArgs = concat([event], arguments, 1),
  16723. listeners, i, length;
  16724. //down while you can, then up and next sibling or up and next sibling until back at root
  16725. while ((current = next)) {
  16726. event.currentScope = current;
  16727. listeners = current.$$listeners[name] || [];
  16728. for (i = 0, length = listeners.length; i < length; i++) {
  16729. // if listeners were deregistered, defragment the array
  16730. if (!listeners[i]) {
  16731. listeners.splice(i, 1);
  16732. i--;
  16733. length--;
  16734. continue;
  16735. }
  16736. try {
  16737. listeners[i].apply(null, listenerArgs);
  16738. } catch (e) {
  16739. $exceptionHandler(e);
  16740. }
  16741. }
  16742. // Insanity Warning: scope depth-first traversal
  16743. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16744. // this piece should be kept in sync with the traversal in $digest
  16745. // (though it differs due to having the extra check for $$listenerCount)
  16746. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  16747. (current !== target && current.$$nextSibling)))) {
  16748. while (current !== target && !(next = current.$$nextSibling)) {
  16749. current = current.$parent;
  16750. }
  16751. }
  16752. }
  16753. event.currentScope = null;
  16754. return event;
  16755. }
  16756. };
  16757. var $rootScope = new Scope();
  16758. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  16759. var asyncQueue = $rootScope.$$asyncQueue = [];
  16760. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  16761. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  16762. var postDigestQueuePosition = 0;
  16763. return $rootScope;
  16764. function beginPhase(phase) {
  16765. if ($rootScope.$$phase) {
  16766. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  16767. }
  16768. $rootScope.$$phase = phase;
  16769. }
  16770. function clearPhase() {
  16771. $rootScope.$$phase = null;
  16772. }
  16773. function incrementWatchersCount(current, count) {
  16774. do {
  16775. current.$$watchersCount += count;
  16776. } while ((current = current.$parent));
  16777. }
  16778. function decrementListenerCount(current, count, name) {
  16779. do {
  16780. current.$$listenerCount[name] -= count;
  16781. if (current.$$listenerCount[name] === 0) {
  16782. delete current.$$listenerCount[name];
  16783. }
  16784. } while ((current = current.$parent));
  16785. }
  16786. /**
  16787. * function used as an initial value for watchers.
  16788. * because it's unique we can easily tell it apart from other values
  16789. */
  16790. function initWatchVal() {}
  16791. function flushApplyAsync() {
  16792. while (applyAsyncQueue.length) {
  16793. try {
  16794. applyAsyncQueue.shift()();
  16795. } catch (e) {
  16796. $exceptionHandler(e);
  16797. }
  16798. }
  16799. applyAsyncId = null;
  16800. }
  16801. function scheduleApplyAsync() {
  16802. if (applyAsyncId === null) {
  16803. applyAsyncId = $browser.defer(function() {
  16804. $rootScope.$apply(flushApplyAsync);
  16805. });
  16806. }
  16807. }
  16808. }];
  16809. }
  16810. /**
  16811. * @ngdoc service
  16812. * @name $rootElement
  16813. *
  16814. * @description
  16815. * The root element of Angular application. This is either the element where {@link
  16816. * ng.directive:ngApp ngApp} was declared or the element passed into
  16817. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  16818. * location where the application's {@link auto.$injector $injector} service gets
  16819. * published, and can be retrieved using `$rootElement.injector()`.
  16820. */
  16821. // the implementation is in angular.bootstrap
  16822. /**
  16823. * @this
  16824. * @description
  16825. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  16826. */
  16827. function $$SanitizeUriProvider() {
  16828. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  16829. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  16830. /**
  16831. * @description
  16832. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16833. * urls during a[href] sanitization.
  16834. *
  16835. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16836. *
  16837. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  16838. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  16839. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16840. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16841. *
  16842. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16843. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16844. * chaining otherwise.
  16845. */
  16846. this.aHrefSanitizationWhitelist = function(regexp) {
  16847. if (isDefined(regexp)) {
  16848. aHrefSanitizationWhitelist = regexp;
  16849. return this;
  16850. }
  16851. return aHrefSanitizationWhitelist;
  16852. };
  16853. /**
  16854. * @description
  16855. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16856. * urls during img[src] sanitization.
  16857. *
  16858. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16859. *
  16860. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  16861. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  16862. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16863. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16864. *
  16865. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16866. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16867. * chaining otherwise.
  16868. */
  16869. this.imgSrcSanitizationWhitelist = function(regexp) {
  16870. if (isDefined(regexp)) {
  16871. imgSrcSanitizationWhitelist = regexp;
  16872. return this;
  16873. }
  16874. return imgSrcSanitizationWhitelist;
  16875. };
  16876. this.$get = function() {
  16877. return function sanitizeUri(uri, isImage) {
  16878. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  16879. var normalizedVal;
  16880. normalizedVal = urlResolve(uri).href;
  16881. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  16882. return 'unsafe:' + normalizedVal;
  16883. }
  16884. return uri;
  16885. };
  16886. };
  16887. }
  16888. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  16889. * Any commits to this file should be reviewed with security in mind. *
  16890. * Changes to this file can potentially create security vulnerabilities. *
  16891. * An approval from 2 Core members with history of modifying *
  16892. * this file is required. *
  16893. * *
  16894. * Does the change somehow allow for arbitrary javascript to be executed? *
  16895. * Or allows for someone to change the prototype of built-in objects? *
  16896. * Or gives undesired access to variables likes document or window? *
  16897. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  16898. /* exported $SceProvider, $SceDelegateProvider */
  16899. var $sceMinErr = minErr('$sce');
  16900. var SCE_CONTEXTS = {
  16901. HTML: 'html',
  16902. CSS: 'css',
  16903. URL: 'url',
  16904. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  16905. // url. (e.g. ng-include, script src, templateUrl)
  16906. RESOURCE_URL: 'resourceUrl',
  16907. JS: 'js'
  16908. };
  16909. // Helper functions follow.
  16910. var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;
  16911. function snakeToCamel(name) {
  16912. return name
  16913. .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);
  16914. }
  16915. function adjustMatcher(matcher) {
  16916. if (matcher === 'self') {
  16917. return matcher;
  16918. } else if (isString(matcher)) {
  16919. // Strings match exactly except for 2 wildcards - '*' and '**'.
  16920. // '*' matches any character except those from the set ':/.?&'.
  16921. // '**' matches any character (like .* in a RegExp).
  16922. // More than 2 *'s raises an error as it's ill defined.
  16923. if (matcher.indexOf('***') > -1) {
  16924. throw $sceMinErr('iwcard',
  16925. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  16926. }
  16927. matcher = escapeForRegexp(matcher).
  16928. replace(/\\\*\\\*/g, '.*').
  16929. replace(/\\\*/g, '[^:/.?&;]*');
  16930. return new RegExp('^' + matcher + '$');
  16931. } else if (isRegExp(matcher)) {
  16932. // The only other type of matcher allowed is a Regexp.
  16933. // Match entire URL / disallow partial matches.
  16934. // Flags are reset (i.e. no global, ignoreCase or multiline)
  16935. return new RegExp('^' + matcher.source + '$');
  16936. } else {
  16937. throw $sceMinErr('imatcher',
  16938. 'Matchers may only be "self", string patterns or RegExp objects');
  16939. }
  16940. }
  16941. function adjustMatchers(matchers) {
  16942. var adjustedMatchers = [];
  16943. if (isDefined(matchers)) {
  16944. forEach(matchers, function(matcher) {
  16945. adjustedMatchers.push(adjustMatcher(matcher));
  16946. });
  16947. }
  16948. return adjustedMatchers;
  16949. }
  16950. /**
  16951. * @ngdoc service
  16952. * @name $sceDelegate
  16953. * @kind function
  16954. *
  16955. * @description
  16956. *
  16957. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  16958. * Contextual Escaping (SCE)} services to AngularJS.
  16959. *
  16960. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  16961. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  16962. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  16963. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  16964. * work because `$sce` delegates to `$sceDelegate` for these operations.
  16965. *
  16966. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  16967. *
  16968. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  16969. * can override it completely to change the behavior of `$sce`, the common case would
  16970. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  16971. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  16972. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  16973. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  16974. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16975. */
  16976. /**
  16977. * @ngdoc provider
  16978. * @name $sceDelegateProvider
  16979. * @this
  16980. *
  16981. * @description
  16982. *
  16983. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  16984. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  16985. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  16986. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  16987. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16988. *
  16989. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  16990. * Strict Contextual Escaping (SCE)}.
  16991. *
  16992. * **Example**: Consider the following case. <a name="example"></a>
  16993. *
  16994. * - your app is hosted at url `http://myapp.example.com/`
  16995. * - but some of your templates are hosted on other domains you control such as
  16996. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  16997. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  16998. *
  16999. * Here is what a secure configuration for this scenario might look like:
  17000. *
  17001. * ```
  17002. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  17003. * $sceDelegateProvider.resourceUrlWhitelist([
  17004. * // Allow same origin resource loads.
  17005. * 'self',
  17006. * // Allow loading from our assets domain. Notice the difference between * and **.
  17007. * 'http://srv*.assets.example.com/**'
  17008. * ]);
  17009. *
  17010. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  17011. * $sceDelegateProvider.resourceUrlBlacklist([
  17012. * 'http://myapp.example.com/clickThru**'
  17013. * ]);
  17014. * });
  17015. * ```
  17016. */
  17017. function $SceDelegateProvider() {
  17018. this.SCE_CONTEXTS = SCE_CONTEXTS;
  17019. // Resource URLs can also be trusted by policy.
  17020. var resourceUrlWhitelist = ['self'],
  17021. resourceUrlBlacklist = [];
  17022. /**
  17023. * @ngdoc method
  17024. * @name $sceDelegateProvider#resourceUrlWhitelist
  17025. * @kind function
  17026. *
  17027. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  17028. * provided. This must be an array or null. A snapshot of this array is used so further
  17029. * changes to the array are ignored.
  17030. *
  17031. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  17032. * allowed in this array.
  17033. *
  17034. * <div class="alert alert-warning">
  17035. * **Note:** an empty whitelist array will block all URLs!
  17036. * </div>
  17037. *
  17038. * @return {Array} the currently set whitelist array.
  17039. *
  17040. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  17041. * same origin resource requests.
  17042. *
  17043. * @description
  17044. * Sets/Gets the whitelist of trusted resource URLs.
  17045. */
  17046. this.resourceUrlWhitelist = function(value) {
  17047. if (arguments.length) {
  17048. resourceUrlWhitelist = adjustMatchers(value);
  17049. }
  17050. return resourceUrlWhitelist;
  17051. };
  17052. /**
  17053. * @ngdoc method
  17054. * @name $sceDelegateProvider#resourceUrlBlacklist
  17055. * @kind function
  17056. *
  17057. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  17058. * provided. This must be an array or null. A snapshot of this array is used so further
  17059. * changes to the array are ignored.
  17060. *
  17061. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  17062. * allowed in this array.
  17063. *
  17064. * The typical usage for the blacklist is to **block
  17065. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  17066. * these would otherwise be trusted but actually return content from the redirected domain.
  17067. *
  17068. * Finally, **the blacklist overrides the whitelist** and has the final say.
  17069. *
  17070. * @return {Array} the currently set blacklist array.
  17071. *
  17072. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  17073. * is no blacklist.)
  17074. *
  17075. * @description
  17076. * Sets/Gets the blacklist of trusted resource URLs.
  17077. */
  17078. this.resourceUrlBlacklist = function(value) {
  17079. if (arguments.length) {
  17080. resourceUrlBlacklist = adjustMatchers(value);
  17081. }
  17082. return resourceUrlBlacklist;
  17083. };
  17084. this.$get = ['$injector', function($injector) {
  17085. var htmlSanitizer = function htmlSanitizer(html) {
  17086. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17087. };
  17088. if ($injector.has('$sanitize')) {
  17089. htmlSanitizer = $injector.get('$sanitize');
  17090. }
  17091. function matchUrl(matcher, parsedUrl) {
  17092. if (matcher === 'self') {
  17093. return urlIsSameOrigin(parsedUrl);
  17094. } else {
  17095. // definitely a regex. See adjustMatchers()
  17096. return !!matcher.exec(parsedUrl.href);
  17097. }
  17098. }
  17099. function isResourceUrlAllowedByPolicy(url) {
  17100. var parsedUrl = urlResolve(url.toString());
  17101. var i, n, allowed = false;
  17102. // Ensure that at least one item from the whitelist allows this url.
  17103. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  17104. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  17105. allowed = true;
  17106. break;
  17107. }
  17108. }
  17109. if (allowed) {
  17110. // Ensure that no item from the blacklist blocked this url.
  17111. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  17112. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  17113. allowed = false;
  17114. break;
  17115. }
  17116. }
  17117. }
  17118. return allowed;
  17119. }
  17120. function generateHolderType(Base) {
  17121. var holderType = function TrustedValueHolderType(trustedValue) {
  17122. this.$$unwrapTrustedValue = function() {
  17123. return trustedValue;
  17124. };
  17125. };
  17126. if (Base) {
  17127. holderType.prototype = new Base();
  17128. }
  17129. holderType.prototype.valueOf = function sceValueOf() {
  17130. return this.$$unwrapTrustedValue();
  17131. };
  17132. holderType.prototype.toString = function sceToString() {
  17133. return this.$$unwrapTrustedValue().toString();
  17134. };
  17135. return holderType;
  17136. }
  17137. var trustedValueHolderBase = generateHolderType(),
  17138. byType = {};
  17139. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  17140. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  17141. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  17142. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  17143. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  17144. /**
  17145. * @ngdoc method
  17146. * @name $sceDelegate#trustAs
  17147. *
  17148. * @description
  17149. * Returns an object that is trusted by angular for use in specified strict
  17150. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  17151. * attribute interpolation, any dom event binding attribute interpolation
  17152. * such as for onclick, etc.) that uses the provided value.
  17153. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  17154. *
  17155. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  17156. * resourceUrl, html, js and css.
  17157. * @param {*} value The value that that should be considered trusted/safe.
  17158. * @returns {*} A value that can be used to stand in for the provided `value` in places
  17159. * where Angular expects a $sce.trustAs() return value.
  17160. */
  17161. function trustAs(type, trustedValue) {
  17162. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17163. if (!Constructor) {
  17164. throw $sceMinErr('icontext',
  17165. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  17166. type, trustedValue);
  17167. }
  17168. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  17169. return trustedValue;
  17170. }
  17171. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  17172. // mutable objects, we ensure here that the value passed in is actually a string.
  17173. if (typeof trustedValue !== 'string') {
  17174. throw $sceMinErr('itype',
  17175. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  17176. type);
  17177. }
  17178. return new Constructor(trustedValue);
  17179. }
  17180. /**
  17181. * @ngdoc method
  17182. * @name $sceDelegate#valueOf
  17183. *
  17184. * @description
  17185. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  17186. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  17187. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  17188. *
  17189. * If the passed parameter is not a value that had been returned by {@link
  17190. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  17191. *
  17192. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  17193. * call or anything else.
  17194. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  17195. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  17196. * `value` unchanged.
  17197. */
  17198. function valueOf(maybeTrusted) {
  17199. if (maybeTrusted instanceof trustedValueHolderBase) {
  17200. return maybeTrusted.$$unwrapTrustedValue();
  17201. } else {
  17202. return maybeTrusted;
  17203. }
  17204. }
  17205. /**
  17206. * @ngdoc method
  17207. * @name $sceDelegate#getTrusted
  17208. *
  17209. * @description
  17210. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  17211. * returns the originally supplied value if the queried context type is a supertype of the
  17212. * created type. If this condition isn't satisfied, throws an exception.
  17213. *
  17214. * <div class="alert alert-danger">
  17215. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  17216. * (XSS) vulnerability in your application.
  17217. * </div>
  17218. *
  17219. * @param {string} type The kind of context in which this value is to be used.
  17220. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  17221. * `$sceDelegate.trustAs`} call.
  17222. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  17223. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  17224. */
  17225. function getTrusted(type, maybeTrusted) {
  17226. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  17227. return maybeTrusted;
  17228. }
  17229. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17230. if (constructor && maybeTrusted instanceof constructor) {
  17231. return maybeTrusted.$$unwrapTrustedValue();
  17232. }
  17233. // If we get here, then we may only take one of two actions.
  17234. // 1. sanitize the value for the requested type, or
  17235. // 2. throw an exception.
  17236. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  17237. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  17238. return maybeTrusted;
  17239. } else {
  17240. throw $sceMinErr('insecurl',
  17241. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  17242. maybeTrusted.toString());
  17243. }
  17244. } else if (type === SCE_CONTEXTS.HTML) {
  17245. return htmlSanitizer(maybeTrusted);
  17246. }
  17247. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17248. }
  17249. return { trustAs: trustAs,
  17250. getTrusted: getTrusted,
  17251. valueOf: valueOf };
  17252. }];
  17253. }
  17254. /**
  17255. * @ngdoc provider
  17256. * @name $sceProvider
  17257. * @this
  17258. *
  17259. * @description
  17260. *
  17261. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  17262. * - enable/disable Strict Contextual Escaping (SCE) in a module
  17263. * - override the default implementation with a custom delegate
  17264. *
  17265. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  17266. */
  17267. /**
  17268. * @ngdoc service
  17269. * @name $sce
  17270. * @kind function
  17271. *
  17272. * @description
  17273. *
  17274. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  17275. *
  17276. * # Strict Contextual Escaping
  17277. *
  17278. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  17279. * contexts to result in a value that is marked as safe to use for that context. One example of
  17280. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  17281. * to these contexts as privileged or SCE contexts.
  17282. *
  17283. * As of version 1.2, Angular ships with SCE enabled by default.
  17284. *
  17285. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  17286. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  17287. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  17288. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  17289. * to the top of your HTML document.
  17290. *
  17291. * SCE assists in writing code in a way that (a) is secure by default and (b) makes auditing for
  17292. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  17293. *
  17294. * Here's an example of a binding in a privileged context:
  17295. *
  17296. * ```
  17297. * <input ng-model="userHtml" aria-label="User input">
  17298. * <div ng-bind-html="userHtml"></div>
  17299. * ```
  17300. *
  17301. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  17302. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  17303. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  17304. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  17305. * security vulnerabilities.)
  17306. *
  17307. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  17308. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  17309. *
  17310. * How would you ensure that every place that used these types of bindings was bound to a value that
  17311. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  17312. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  17313. * properties/fields and forgot to update the binding to the sanitized value?
  17314. *
  17315. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  17316. * determine that something explicitly says it's safe to use a value for binding in that
  17317. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  17318. * for those values that you can easily tell are safe - because they were received from your server,
  17319. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  17320. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  17321. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  17322. *
  17323. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  17324. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  17325. * obtain values that will be accepted by SCE / privileged contexts.
  17326. *
  17327. *
  17328. * ## How does it work?
  17329. *
  17330. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  17331. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  17332. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  17333. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  17334. *
  17335. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  17336. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  17337. * simplified):
  17338. *
  17339. * ```
  17340. * var ngBindHtmlDirective = ['$sce', function($sce) {
  17341. * return function(scope, element, attr) {
  17342. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  17343. * element.html(value || '');
  17344. * });
  17345. * };
  17346. * }];
  17347. * ```
  17348. *
  17349. * ## Impact on loading templates
  17350. *
  17351. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  17352. * `templateUrl`'s specified by {@link guide/directive directives}.
  17353. *
  17354. * By default, Angular only loads templates from the same domain and protocol as the application
  17355. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  17356. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  17357. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  17358. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  17359. *
  17360. * *Please note*:
  17361. * The browser's
  17362. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  17363. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  17364. * policy apply in addition to this and may further restrict whether the template is successfully
  17365. * loaded. This means that without the right CORS policy, loading templates from a different domain
  17366. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  17367. * browsers.
  17368. *
  17369. * ## This feels like too much overhead
  17370. *
  17371. * It's important to remember that SCE only applies to interpolation expressions.
  17372. *
  17373. * If your expressions are constant literals, they're automatically trusted and you don't need to
  17374. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  17375. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  17376. *
  17377. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  17378. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  17379. *
  17380. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  17381. * templates in `ng-include` from your application's domain without having to even know about SCE.
  17382. * It blocks loading templates from other domains or loading templates over http from an https
  17383. * served document. You can change these by setting your own custom {@link
  17384. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  17385. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  17386. *
  17387. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  17388. * application that's secure and can be audited to verify that with much more ease than bolting
  17389. * security onto an application later.
  17390. *
  17391. * <a name="contexts"></a>
  17392. * ## What trusted context types are supported?
  17393. *
  17394. * | Context | Notes |
  17395. * |---------------------|----------------|
  17396. * | `$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. |
  17397. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  17398. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
  17399. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG`, `VIDEO`, `AUDIO`, `SOURCE`, and `TRACK` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  17400. * | `$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. |
  17401. *
  17402. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  17403. *
  17404. * Each element in these arrays must be one of the following:
  17405. *
  17406. * - **'self'**
  17407. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  17408. * domain** as the application document using the **same protocol**.
  17409. * - **String** (except the special value `'self'`)
  17410. * - The string is matched against the full *normalized / absolute URL* of the resource
  17411. * being tested (substring matches are not good enough.)
  17412. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  17413. * match themselves.
  17414. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  17415. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  17416. * in a whitelist.
  17417. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  17418. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  17419. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  17420. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  17421. * http://foo.example.com/templates/**).
  17422. * - **RegExp** (*see caveat below*)
  17423. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  17424. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  17425. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  17426. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  17427. * small number of cases. A `.` character in the regex used when matching the scheme or a
  17428. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  17429. * is highly recommended to use the string patterns and only fall back to regular expressions
  17430. * as a last resort.
  17431. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  17432. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  17433. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  17434. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  17435. * - If you are generating your JavaScript from some other templating engine (not
  17436. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  17437. * remember to escape your regular expression (and be aware that you might need more than
  17438. * one level of escaping depending on your templating engine and the way you interpolated
  17439. * the value.) Do make use of your platform's escaping mechanism as it might be good
  17440. * enough before coding your own. E.g. Ruby has
  17441. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  17442. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  17443. * Javascript lacks a similar built in function for escaping. Take a look at Google
  17444. * Closure library's [goog.string.regExpEscape(s)](
  17445. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  17446. *
  17447. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  17448. *
  17449. * ## Show me an example using SCE.
  17450. *
  17451. * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
  17452. * <file name="index.html">
  17453. * <div ng-controller="AppController as myCtrl">
  17454. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  17455. * <b>User comments</b><br>
  17456. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  17457. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  17458. * exploit.
  17459. * <div class="well">
  17460. * <div ng-repeat="userComment in myCtrl.userComments">
  17461. * <b>{{userComment.name}}</b>:
  17462. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  17463. * <br>
  17464. * </div>
  17465. * </div>
  17466. * </div>
  17467. * </file>
  17468. *
  17469. * <file name="script.js">
  17470. * angular.module('mySceApp', ['ngSanitize'])
  17471. * .controller('AppController', ['$http', '$templateCache', '$sce',
  17472. * function AppController($http, $templateCache, $sce) {
  17473. * var self = this;
  17474. * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {
  17475. * self.userComments = response.data;
  17476. * });
  17477. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  17478. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17479. * 'sanitization.&quot;">Hover over this text.</span>');
  17480. * }]);
  17481. * </file>
  17482. *
  17483. * <file name="test_data.json">
  17484. * [
  17485. * { "name": "Alice",
  17486. * "htmlComment":
  17487. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  17488. * },
  17489. * { "name": "Bob",
  17490. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  17491. * }
  17492. * ]
  17493. * </file>
  17494. *
  17495. * <file name="protractor.js" type="protractor">
  17496. * describe('SCE doc demo', function() {
  17497. * it('should sanitize untrusted values', function() {
  17498. * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
  17499. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  17500. * });
  17501. *
  17502. * it('should NOT sanitize explicitly trusted values', function() {
  17503. * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
  17504. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17505. * 'sanitization.&quot;">Hover over this text.</span>');
  17506. * });
  17507. * });
  17508. * </file>
  17509. * </example>
  17510. *
  17511. *
  17512. *
  17513. * ## Can I disable SCE completely?
  17514. *
  17515. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  17516. * for little coding overhead. It will be much harder to take an SCE disabled application and
  17517. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  17518. * for cases where you have a lot of existing code that was written before SCE was introduced and
  17519. * you're migrating them a module at a time.
  17520. *
  17521. * That said, here's how you can completely disable SCE:
  17522. *
  17523. * ```
  17524. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  17525. * // Completely disable SCE. For demonstration purposes only!
  17526. * // Do not use in new projects.
  17527. * $sceProvider.enabled(false);
  17528. * });
  17529. * ```
  17530. *
  17531. */
  17532. function $SceProvider() {
  17533. var enabled = true;
  17534. /**
  17535. * @ngdoc method
  17536. * @name $sceProvider#enabled
  17537. * @kind function
  17538. *
  17539. * @param {boolean=} value If provided, then enables/disables SCE.
  17540. * @return {boolean} true if SCE is enabled, false otherwise.
  17541. *
  17542. * @description
  17543. * Enables/disables SCE and returns the current value.
  17544. */
  17545. this.enabled = function(value) {
  17546. if (arguments.length) {
  17547. enabled = !!value;
  17548. }
  17549. return enabled;
  17550. };
  17551. /* Design notes on the default implementation for SCE.
  17552. *
  17553. * The API contract for the SCE delegate
  17554. * -------------------------------------
  17555. * The SCE delegate object must provide the following 3 methods:
  17556. *
  17557. * - trustAs(contextEnum, value)
  17558. * This method is used to tell the SCE service that the provided value is OK to use in the
  17559. * contexts specified by contextEnum. It must return an object that will be accepted by
  17560. * getTrusted() for a compatible contextEnum and return this value.
  17561. *
  17562. * - valueOf(value)
  17563. * For values that were not produced by trustAs(), return them as is. For values that were
  17564. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  17565. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  17566. * such a value.
  17567. *
  17568. * - getTrusted(contextEnum, value)
  17569. * This function should return the a value that is safe to use in the context specified by
  17570. * contextEnum or throw and exception otherwise.
  17571. *
  17572. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  17573. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  17574. * instance, an implementation could maintain a registry of all trusted objects by context. In
  17575. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  17576. * return the same object passed in if it was found in the registry under a compatible context or
  17577. * throw an exception otherwise. An implementation might only wrap values some of the time based
  17578. * on some criteria. getTrusted() might return a value and not throw an exception for special
  17579. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  17580. *
  17581. *
  17582. * A note on the inheritance model for SCE contexts
  17583. * ------------------------------------------------
  17584. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  17585. * is purely an implementation details.
  17586. *
  17587. * The contract is simply this:
  17588. *
  17589. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  17590. * will also succeed.
  17591. *
  17592. * Inheritance happens to capture this in a natural way. In some future, we
  17593. * may not use inheritance anymore. That is OK because no code outside of
  17594. * sce.js and sceSpecs.js would need to be aware of this detail.
  17595. */
  17596. this.$get = ['$parse', '$sceDelegate', function(
  17597. $parse, $sceDelegate) {
  17598. // Support: IE 9-11 only
  17599. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  17600. // the "expression(javascript expression)" syntax which is insecure.
  17601. if (enabled && msie < 8) {
  17602. throw $sceMinErr('iequirks',
  17603. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  17604. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  17605. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  17606. }
  17607. var sce = shallowCopy(SCE_CONTEXTS);
  17608. /**
  17609. * @ngdoc method
  17610. * @name $sce#isEnabled
  17611. * @kind function
  17612. *
  17613. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  17614. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  17615. *
  17616. * @description
  17617. * Returns a boolean indicating if SCE is enabled.
  17618. */
  17619. sce.isEnabled = function() {
  17620. return enabled;
  17621. };
  17622. sce.trustAs = $sceDelegate.trustAs;
  17623. sce.getTrusted = $sceDelegate.getTrusted;
  17624. sce.valueOf = $sceDelegate.valueOf;
  17625. if (!enabled) {
  17626. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  17627. sce.valueOf = identity;
  17628. }
  17629. /**
  17630. * @ngdoc method
  17631. * @name $sce#parseAs
  17632. *
  17633. * @description
  17634. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  17635. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  17636. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  17637. * *result*)}
  17638. *
  17639. * @param {string} type The kind of SCE context in which this result will be used.
  17640. * @param {string} expression String expression to compile.
  17641. * @returns {function(context, locals)} a function which represents the compiled expression:
  17642. *
  17643. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17644. * are evaluated against (typically a scope object).
  17645. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17646. * `context`.
  17647. */
  17648. sce.parseAs = function sceParseAs(type, expr) {
  17649. var parsed = $parse(expr);
  17650. if (parsed.literal && parsed.constant) {
  17651. return parsed;
  17652. } else {
  17653. return $parse(expr, function(value) {
  17654. return sce.getTrusted(type, value);
  17655. });
  17656. }
  17657. };
  17658. /**
  17659. * @ngdoc method
  17660. * @name $sce#trustAs
  17661. *
  17662. * @description
  17663. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  17664. * returns an object that is trusted by angular for use in specified strict contextual
  17665. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  17666. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  17667. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  17668. * escaping.
  17669. *
  17670. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  17671. * resourceUrl, html, js and css.
  17672. * @param {*} value The value that that should be considered trusted/safe.
  17673. * @returns {*} A value that can be used to stand in for the provided `value` in places
  17674. * where Angular expects a $sce.trustAs() return value.
  17675. */
  17676. /**
  17677. * @ngdoc method
  17678. * @name $sce#trustAsHtml
  17679. *
  17680. * @description
  17681. * Shorthand method. `$sce.trustAsHtml(value)` →
  17682. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  17683. *
  17684. * @param {*} value The value to trustAs.
  17685. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  17686. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  17687. * only accept expressions that are either literal constants or are the
  17688. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17689. */
  17690. /**
  17691. * @ngdoc method
  17692. * @name $sce#trustAsUrl
  17693. *
  17694. * @description
  17695. * Shorthand method. `$sce.trustAsUrl(value)` →
  17696. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  17697. *
  17698. * @param {*} value The value to trustAs.
  17699. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  17700. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  17701. * only accept expressions that are either literal constants or are the
  17702. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17703. */
  17704. /**
  17705. * @ngdoc method
  17706. * @name $sce#trustAsResourceUrl
  17707. *
  17708. * @description
  17709. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  17710. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  17711. *
  17712. * @param {*} value The value to trustAs.
  17713. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  17714. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  17715. * only accept expressions that are either literal constants or are the return
  17716. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17717. */
  17718. /**
  17719. * @ngdoc method
  17720. * @name $sce#trustAsJs
  17721. *
  17722. * @description
  17723. * Shorthand method. `$sce.trustAsJs(value)` →
  17724. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  17725. *
  17726. * @param {*} value The value to trustAs.
  17727. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  17728. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  17729. * only accept expressions that are either literal constants or are the
  17730. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17731. */
  17732. /**
  17733. * @ngdoc method
  17734. * @name $sce#getTrusted
  17735. *
  17736. * @description
  17737. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  17738. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  17739. * originally supplied value if the queried context type is a supertype of the created type.
  17740. * If this condition isn't satisfied, throws an exception.
  17741. *
  17742. * @param {string} type The kind of context in which this value is to be used.
  17743. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  17744. * call.
  17745. * @returns {*} The value the was originally provided to
  17746. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  17747. * Otherwise, throws an exception.
  17748. */
  17749. /**
  17750. * @ngdoc method
  17751. * @name $sce#getTrustedHtml
  17752. *
  17753. * @description
  17754. * Shorthand method. `$sce.getTrustedHtml(value)` →
  17755. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  17756. *
  17757. * @param {*} value The value to pass to `$sce.getTrusted`.
  17758. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  17759. */
  17760. /**
  17761. * @ngdoc method
  17762. * @name $sce#getTrustedCss
  17763. *
  17764. * @description
  17765. * Shorthand method. `$sce.getTrustedCss(value)` →
  17766. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  17767. *
  17768. * @param {*} value The value to pass to `$sce.getTrusted`.
  17769. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  17770. */
  17771. /**
  17772. * @ngdoc method
  17773. * @name $sce#getTrustedUrl
  17774. *
  17775. * @description
  17776. * Shorthand method. `$sce.getTrustedUrl(value)` →
  17777. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  17778. *
  17779. * @param {*} value The value to pass to `$sce.getTrusted`.
  17780. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  17781. */
  17782. /**
  17783. * @ngdoc method
  17784. * @name $sce#getTrustedResourceUrl
  17785. *
  17786. * @description
  17787. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  17788. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  17789. *
  17790. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  17791. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  17792. */
  17793. /**
  17794. * @ngdoc method
  17795. * @name $sce#getTrustedJs
  17796. *
  17797. * @description
  17798. * Shorthand method. `$sce.getTrustedJs(value)` →
  17799. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  17800. *
  17801. * @param {*} value The value to pass to `$sce.getTrusted`.
  17802. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  17803. */
  17804. /**
  17805. * @ngdoc method
  17806. * @name $sce#parseAsHtml
  17807. *
  17808. * @description
  17809. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  17810. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  17811. *
  17812. * @param {string} expression String expression to compile.
  17813. * @returns {function(context, locals)} a function which represents the compiled expression:
  17814. *
  17815. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17816. * are evaluated against (typically a scope object).
  17817. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17818. * `context`.
  17819. */
  17820. /**
  17821. * @ngdoc method
  17822. * @name $sce#parseAsCss
  17823. *
  17824. * @description
  17825. * Shorthand method. `$sce.parseAsCss(value)` →
  17826. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  17827. *
  17828. * @param {string} expression String expression to compile.
  17829. * @returns {function(context, locals)} a function which represents the compiled expression:
  17830. *
  17831. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17832. * are evaluated against (typically a scope object).
  17833. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17834. * `context`.
  17835. */
  17836. /**
  17837. * @ngdoc method
  17838. * @name $sce#parseAsUrl
  17839. *
  17840. * @description
  17841. * Shorthand method. `$sce.parseAsUrl(value)` →
  17842. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  17843. *
  17844. * @param {string} expression String expression to compile.
  17845. * @returns {function(context, locals)} a function which represents the compiled expression:
  17846. *
  17847. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17848. * are evaluated against (typically a scope object).
  17849. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17850. * `context`.
  17851. */
  17852. /**
  17853. * @ngdoc method
  17854. * @name $sce#parseAsResourceUrl
  17855. *
  17856. * @description
  17857. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  17858. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  17859. *
  17860. * @param {string} expression String expression to compile.
  17861. * @returns {function(context, locals)} a function which represents the compiled expression:
  17862. *
  17863. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17864. * are evaluated against (typically a scope object).
  17865. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17866. * `context`.
  17867. */
  17868. /**
  17869. * @ngdoc method
  17870. * @name $sce#parseAsJs
  17871. *
  17872. * @description
  17873. * Shorthand method. `$sce.parseAsJs(value)` →
  17874. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  17875. *
  17876. * @param {string} expression String expression to compile.
  17877. * @returns {function(context, locals)} a function which represents the compiled expression:
  17878. *
  17879. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17880. * are evaluated against (typically a scope object).
  17881. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17882. * `context`.
  17883. */
  17884. // Shorthand delegations.
  17885. var parse = sce.parseAs,
  17886. getTrusted = sce.getTrusted,
  17887. trustAs = sce.trustAs;
  17888. forEach(SCE_CONTEXTS, function(enumValue, name) {
  17889. var lName = lowercase(name);
  17890. sce[snakeToCamel('parse_as_' + lName)] = function(expr) {
  17891. return parse(enumValue, expr);
  17892. };
  17893. sce[snakeToCamel('get_trusted_' + lName)] = function(value) {
  17894. return getTrusted(enumValue, value);
  17895. };
  17896. sce[snakeToCamel('trust_as_' + lName)] = function(value) {
  17897. return trustAs(enumValue, value);
  17898. };
  17899. });
  17900. return sce;
  17901. }];
  17902. }
  17903. /* exported $SnifferProvider */
  17904. /**
  17905. * !!! This is an undocumented "private" service !!!
  17906. *
  17907. * @name $sniffer
  17908. * @requires $window
  17909. * @requires $document
  17910. * @this
  17911. *
  17912. * @property {boolean} history Does the browser support html5 history api ?
  17913. * @property {boolean} transitions Does the browser support CSS transition events ?
  17914. * @property {boolean} animations Does the browser support CSS animation events ?
  17915. *
  17916. * @description
  17917. * This is very simple implementation of testing browser's features.
  17918. */
  17919. function $SnifferProvider() {
  17920. this.$get = ['$window', '$document', function($window, $document) {
  17921. var eventSupport = {},
  17922. // Chrome Packaged Apps are not allowed to access `history.pushState`.
  17923. // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
  17924. // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
  17925. // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
  17926. // (see https://developer.chrome.com/apps/manifest/sandbox).
  17927. // (NW.js apps have access to Chrome APIs, but do support `history`.)
  17928. isNw = $window.nw && $window.nw.process,
  17929. isChromePackagedApp =
  17930. !isNw &&
  17931. $window.chrome &&
  17932. ($window.chrome.app && $window.chrome.app.runtime ||
  17933. !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
  17934. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  17935. android =
  17936. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  17937. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  17938. document = $document[0] || {},
  17939. bodyStyle = document.body && document.body.style,
  17940. transitions = false,
  17941. animations = false;
  17942. if (bodyStyle) {
  17943. // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x
  17944. // Mentioned browsers need a -webkit- prefix for transitions & animations.
  17945. transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);
  17946. animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);
  17947. }
  17948. return {
  17949. // Android has history.pushState, but it does not update location correctly
  17950. // so let's not use the history API at all.
  17951. // http://code.google.com/p/android/issues/detail?id=17471
  17952. // https://github.com/angular/angular.js/issues/904
  17953. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  17954. // so let's not use the history API also
  17955. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  17956. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  17957. hasEvent: function(event) {
  17958. // Support: IE 9-11 only
  17959. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  17960. // it. In particular the event is not fired when backspace or delete key are pressed or
  17961. // when cut operation is performed.
  17962. // IE10+ implements 'input' event but it erroneously fires under various situations,
  17963. // e.g. when placeholder changes, or a form is focused.
  17964. if (event === 'input' && msie) return false;
  17965. if (isUndefined(eventSupport[event])) {
  17966. var divElm = document.createElement('div');
  17967. eventSupport[event] = 'on' + event in divElm;
  17968. }
  17969. return eventSupport[event];
  17970. },
  17971. csp: csp(),
  17972. transitions: transitions,
  17973. animations: animations,
  17974. android: android
  17975. };
  17976. }];
  17977. }
  17978. var $templateRequestMinErr = minErr('$compile');
  17979. /**
  17980. * @ngdoc provider
  17981. * @name $templateRequestProvider
  17982. * @this
  17983. *
  17984. * @description
  17985. * Used to configure the options passed to the {@link $http} service when making a template request.
  17986. *
  17987. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  17988. * requesting a template.
  17989. */
  17990. function $TemplateRequestProvider() {
  17991. var httpOptions;
  17992. /**
  17993. * @ngdoc method
  17994. * @name $templateRequestProvider#httpOptions
  17995. * @description
  17996. * The options to be passed to the {@link $http} service when making the request.
  17997. * You can use this to override options such as the "Accept" header for template requests.
  17998. *
  17999. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  18000. * options if not overridden here.
  18001. *
  18002. * @param {string=} value new value for the {@link $http} options.
  18003. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  18004. */
  18005. this.httpOptions = function(val) {
  18006. if (val) {
  18007. httpOptions = val;
  18008. return this;
  18009. }
  18010. return httpOptions;
  18011. };
  18012. /**
  18013. * @ngdoc service
  18014. * @name $templateRequest
  18015. *
  18016. * @description
  18017. * The `$templateRequest` service runs security checks then downloads the provided template using
  18018. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  18019. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  18020. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  18021. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  18022. * when `tpl` is of type string and `$templateCache` has the matching entry.
  18023. *
  18024. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  18025. * can configure this via {@link $templateRequestProvider#httpOptions}.
  18026. *
  18027. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  18028. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  18029. *
  18030. * @return {Promise} a promise for the HTTP response data of the given URL.
  18031. *
  18032. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  18033. */
  18034. this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',
  18035. function($exceptionHandler, $templateCache, $http, $q, $sce) {
  18036. function handleRequestFn(tpl, ignoreRequestError) {
  18037. handleRequestFn.totalPendingRequests++;
  18038. // We consider the template cache holds only trusted templates, so
  18039. // there's no need to go through whitelisting again for keys that already
  18040. // are included in there. This also makes Angular accept any script
  18041. // directive, no matter its name. However, we still need to unwrap trusted
  18042. // types.
  18043. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  18044. tpl = $sce.getTrustedResourceUrl(tpl);
  18045. }
  18046. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  18047. if (isArray(transformResponse)) {
  18048. transformResponse = transformResponse.filter(function(transformer) {
  18049. return transformer !== defaultHttpResponseTransform;
  18050. });
  18051. } else if (transformResponse === defaultHttpResponseTransform) {
  18052. transformResponse = null;
  18053. }
  18054. return $http.get(tpl, extend({
  18055. cache: $templateCache,
  18056. transformResponse: transformResponse
  18057. }, httpOptions))
  18058. .finally(function() {
  18059. handleRequestFn.totalPendingRequests--;
  18060. })
  18061. .then(function(response) {
  18062. $templateCache.put(tpl, response.data);
  18063. return response.data;
  18064. }, handleError);
  18065. function handleError(resp) {
  18066. if (!ignoreRequestError) {
  18067. resp = $templateRequestMinErr('tpload',
  18068. 'Failed to load template: {0} (HTTP status: {1} {2})',
  18069. tpl, resp.status, resp.statusText);
  18070. $exceptionHandler(resp);
  18071. }
  18072. return $q.reject(resp);
  18073. }
  18074. }
  18075. handleRequestFn.totalPendingRequests = 0;
  18076. return handleRequestFn;
  18077. }
  18078. ];
  18079. }
  18080. /** @this */
  18081. function $$TestabilityProvider() {
  18082. this.$get = ['$rootScope', '$browser', '$location',
  18083. function($rootScope, $browser, $location) {
  18084. /**
  18085. * @name $testability
  18086. *
  18087. * @description
  18088. * The private $$testability service provides a collection of methods for use when debugging
  18089. * or by automated test and debugging tools.
  18090. */
  18091. var testability = {};
  18092. /**
  18093. * @name $$testability#findBindings
  18094. *
  18095. * @description
  18096. * Returns an array of elements that are bound (via ng-bind or {{}})
  18097. * to expressions matching the input.
  18098. *
  18099. * @param {Element} element The element root to search from.
  18100. * @param {string} expression The binding expression to match.
  18101. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18102. * for the expression. Filters and whitespace are ignored.
  18103. */
  18104. testability.findBindings = function(element, expression, opt_exactMatch) {
  18105. var bindings = element.getElementsByClassName('ng-binding');
  18106. var matches = [];
  18107. forEach(bindings, function(binding) {
  18108. var dataBinding = angular.element(binding).data('$binding');
  18109. if (dataBinding) {
  18110. forEach(dataBinding, function(bindingName) {
  18111. if (opt_exactMatch) {
  18112. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  18113. if (matcher.test(bindingName)) {
  18114. matches.push(binding);
  18115. }
  18116. } else {
  18117. if (bindingName.indexOf(expression) !== -1) {
  18118. matches.push(binding);
  18119. }
  18120. }
  18121. });
  18122. }
  18123. });
  18124. return matches;
  18125. };
  18126. /**
  18127. * @name $$testability#findModels
  18128. *
  18129. * @description
  18130. * Returns an array of elements that are two-way found via ng-model to
  18131. * expressions matching the input.
  18132. *
  18133. * @param {Element} element The element root to search from.
  18134. * @param {string} expression The model expression to match.
  18135. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18136. * for the expression.
  18137. */
  18138. testability.findModels = function(element, expression, opt_exactMatch) {
  18139. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  18140. for (var p = 0; p < prefixes.length; ++p) {
  18141. var attributeEquals = opt_exactMatch ? '=' : '*=';
  18142. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  18143. var elements = element.querySelectorAll(selector);
  18144. if (elements.length) {
  18145. return elements;
  18146. }
  18147. }
  18148. };
  18149. /**
  18150. * @name $$testability#getLocation
  18151. *
  18152. * @description
  18153. * Shortcut for getting the location in a browser agnostic way. Returns
  18154. * the path, search, and hash. (e.g. /path?a=b#hash)
  18155. */
  18156. testability.getLocation = function() {
  18157. return $location.url();
  18158. };
  18159. /**
  18160. * @name $$testability#setLocation
  18161. *
  18162. * @description
  18163. * Shortcut for navigating to a location without doing a full page reload.
  18164. *
  18165. * @param {string} url The location url (path, search and hash,
  18166. * e.g. /path?a=b#hash) to go to.
  18167. */
  18168. testability.setLocation = function(url) {
  18169. if (url !== $location.url()) {
  18170. $location.url(url);
  18171. $rootScope.$digest();
  18172. }
  18173. };
  18174. /**
  18175. * @name $$testability#whenStable
  18176. *
  18177. * @description
  18178. * Calls the callback when $timeout and $http requests are completed.
  18179. *
  18180. * @param {function} callback
  18181. */
  18182. testability.whenStable = function(callback) {
  18183. $browser.notifyWhenNoOutstandingRequests(callback);
  18184. };
  18185. return testability;
  18186. }];
  18187. }
  18188. /** @this */
  18189. function $TimeoutProvider() {
  18190. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  18191. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  18192. var deferreds = {};
  18193. /**
  18194. * @ngdoc service
  18195. * @name $timeout
  18196. *
  18197. * @description
  18198. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  18199. * block and delegates any exceptions to
  18200. * {@link ng.$exceptionHandler $exceptionHandler} service.
  18201. *
  18202. * The return value of calling `$timeout` is a promise, which will be resolved when
  18203. * the delay has passed and the timeout function, if provided, is executed.
  18204. *
  18205. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  18206. *
  18207. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  18208. * synchronously flush the queue of deferred functions.
  18209. *
  18210. * If you only want a promise that will be resolved after some specified delay
  18211. * then you can call `$timeout` without the `fn` function.
  18212. *
  18213. * @param {function()=} fn A function, whose execution should be delayed.
  18214. * @param {number=} [delay=0] Delay in milliseconds.
  18215. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  18216. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  18217. * @param {...*=} Pass additional parameters to the executed function.
  18218. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  18219. * will be resolved with the return value of the `fn` function.
  18220. *
  18221. */
  18222. function timeout(fn, delay, invokeApply) {
  18223. if (!isFunction(fn)) {
  18224. invokeApply = delay;
  18225. delay = fn;
  18226. fn = noop;
  18227. }
  18228. var args = sliceArgs(arguments, 3),
  18229. skipApply = (isDefined(invokeApply) && !invokeApply),
  18230. deferred = (skipApply ? $$q : $q).defer(),
  18231. promise = deferred.promise,
  18232. timeoutId;
  18233. timeoutId = $browser.defer(function() {
  18234. try {
  18235. deferred.resolve(fn.apply(null, args));
  18236. } catch (e) {
  18237. deferred.reject(e);
  18238. $exceptionHandler(e);
  18239. } finally {
  18240. delete deferreds[promise.$$timeoutId];
  18241. }
  18242. if (!skipApply) $rootScope.$apply();
  18243. }, delay);
  18244. promise.$$timeoutId = timeoutId;
  18245. deferreds[timeoutId] = deferred;
  18246. return promise;
  18247. }
  18248. /**
  18249. * @ngdoc method
  18250. * @name $timeout#cancel
  18251. *
  18252. * @description
  18253. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  18254. * resolved with a rejection.
  18255. *
  18256. * @param {Promise=} promise Promise returned by the `$timeout` function.
  18257. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  18258. * canceled.
  18259. */
  18260. timeout.cancel = function(promise) {
  18261. if (promise && promise.$$timeoutId in deferreds) {
  18262. // Timeout cancels should not report an unhandled promise.
  18263. deferreds[promise.$$timeoutId].promise.catch(noop);
  18264. deferreds[promise.$$timeoutId].reject('canceled');
  18265. delete deferreds[promise.$$timeoutId];
  18266. return $browser.defer.cancel(promise.$$timeoutId);
  18267. }
  18268. return false;
  18269. };
  18270. return timeout;
  18271. }];
  18272. }
  18273. // NOTE: The usage of window and document instead of $window and $document here is
  18274. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  18275. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  18276. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  18277. // doesn't know about mocked locations and resolves URLs to the real document - which is
  18278. // exactly the behavior needed here. There is little value is mocking these out for this
  18279. // service.
  18280. var urlParsingNode = window.document.createElement('a');
  18281. var originUrl = urlResolve(window.location.href);
  18282. /**
  18283. *
  18284. * Implementation Notes for non-IE browsers
  18285. * ----------------------------------------
  18286. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  18287. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  18288. * URL will be resolved into an absolute URL in the context of the application document.
  18289. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  18290. * properties are all populated to reflect the normalized URL. This approach has wide
  18291. * compatibility - Safari 1+, Mozilla 1+ etc. See
  18292. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18293. *
  18294. * Implementation Notes for IE
  18295. * ---------------------------
  18296. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  18297. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  18298. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  18299. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  18300. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  18301. * properties such as protocol, hostname, port, etc.
  18302. *
  18303. * References:
  18304. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  18305. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18306. * http://url.spec.whatwg.org/#urlutils
  18307. * https://github.com/angular/angular.js/pull/2902
  18308. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  18309. *
  18310. * @kind function
  18311. * @param {string} url The URL to be parsed.
  18312. * @description Normalizes and parses a URL.
  18313. * @returns {object} Returns the normalized URL as a dictionary.
  18314. *
  18315. * | member name | Description |
  18316. * |---------------|----------------|
  18317. * | href | A normalized version of the provided URL if it was not an absolute URL |
  18318. * | protocol | The protocol including the trailing colon |
  18319. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  18320. * | search | The search params, minus the question mark |
  18321. * | hash | The hash string, minus the hash symbol
  18322. * | hostname | The hostname
  18323. * | port | The port, without ":"
  18324. * | pathname | The pathname, beginning with "/"
  18325. *
  18326. */
  18327. function urlResolve(url) {
  18328. var href = url;
  18329. // Support: IE 9-11 only
  18330. if (msie) {
  18331. // Normalize before parse. Refer Implementation Notes on why this is
  18332. // done in two steps on IE.
  18333. urlParsingNode.setAttribute('href', href);
  18334. href = urlParsingNode.href;
  18335. }
  18336. urlParsingNode.setAttribute('href', href);
  18337. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  18338. return {
  18339. href: urlParsingNode.href,
  18340. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  18341. host: urlParsingNode.host,
  18342. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  18343. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  18344. hostname: urlParsingNode.hostname,
  18345. port: urlParsingNode.port,
  18346. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  18347. ? urlParsingNode.pathname
  18348. : '/' + urlParsingNode.pathname
  18349. };
  18350. }
  18351. /**
  18352. * Parse a request URL and determine whether this is a same-origin request as the application document.
  18353. *
  18354. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  18355. * or a parsed URL object.
  18356. * @returns {boolean} Whether the request is for the same origin as the application document.
  18357. */
  18358. function urlIsSameOrigin(requestUrl) {
  18359. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  18360. return (parsed.protocol === originUrl.protocol &&
  18361. parsed.host === originUrl.host);
  18362. }
  18363. /**
  18364. * @ngdoc service
  18365. * @name $window
  18366. * @this
  18367. *
  18368. * @description
  18369. * A reference to the browser's `window` object. While `window`
  18370. * is globally available in JavaScript, it causes testability problems, because
  18371. * it is a global variable. In angular we always refer to it through the
  18372. * `$window` service, so it may be overridden, removed or mocked for testing.
  18373. *
  18374. * Expressions, like the one defined for the `ngClick` directive in the example
  18375. * below, are evaluated with respect to the current scope. Therefore, there is
  18376. * no risk of inadvertently coding in a dependency on a global value in such an
  18377. * expression.
  18378. *
  18379. * @example
  18380. <example module="windowExample" name="window-service">
  18381. <file name="index.html">
  18382. <script>
  18383. angular.module('windowExample', [])
  18384. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  18385. $scope.greeting = 'Hello, World!';
  18386. $scope.doGreeting = function(greeting) {
  18387. $window.alert(greeting);
  18388. };
  18389. }]);
  18390. </script>
  18391. <div ng-controller="ExampleController">
  18392. <input type="text" ng-model="greeting" aria-label="greeting" />
  18393. <button ng-click="doGreeting(greeting)">ALERT</button>
  18394. </div>
  18395. </file>
  18396. <file name="protractor.js" type="protractor">
  18397. it('should display the greeting in the input box', function() {
  18398. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  18399. // If we click the button it will block the test runner
  18400. // element(':button').click();
  18401. });
  18402. </file>
  18403. </example>
  18404. */
  18405. function $WindowProvider() {
  18406. this.$get = valueFn(window);
  18407. }
  18408. /**
  18409. * @name $$cookieReader
  18410. * @requires $document
  18411. *
  18412. * @description
  18413. * This is a private service for reading cookies used by $http and ngCookies
  18414. *
  18415. * @return {Object} a key/value map of the current cookies
  18416. */
  18417. function $$CookieReader($document) {
  18418. var rawDocument = $document[0] || {};
  18419. var lastCookies = {};
  18420. var lastCookieString = '';
  18421. function safeGetCookie(rawDocument) {
  18422. try {
  18423. return rawDocument.cookie || '';
  18424. } catch (e) {
  18425. return '';
  18426. }
  18427. }
  18428. function safeDecodeURIComponent(str) {
  18429. try {
  18430. return decodeURIComponent(str);
  18431. } catch (e) {
  18432. return str;
  18433. }
  18434. }
  18435. return function() {
  18436. var cookieArray, cookie, i, index, name;
  18437. var currentCookieString = safeGetCookie(rawDocument);
  18438. if (currentCookieString !== lastCookieString) {
  18439. lastCookieString = currentCookieString;
  18440. cookieArray = lastCookieString.split('; ');
  18441. lastCookies = {};
  18442. for (i = 0; i < cookieArray.length; i++) {
  18443. cookie = cookieArray[i];
  18444. index = cookie.indexOf('=');
  18445. if (index > 0) { //ignore nameless cookies
  18446. name = safeDecodeURIComponent(cookie.substring(0, index));
  18447. // the first value that is seen for a cookie is the most
  18448. // specific one. values for the same cookie name that
  18449. // follow are for less specific paths.
  18450. if (isUndefined(lastCookies[name])) {
  18451. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  18452. }
  18453. }
  18454. }
  18455. }
  18456. return lastCookies;
  18457. };
  18458. }
  18459. $$CookieReader.$inject = ['$document'];
  18460. /** @this */
  18461. function $$CookieReaderProvider() {
  18462. this.$get = $$CookieReader;
  18463. }
  18464. /* global currencyFilter: true,
  18465. dateFilter: true,
  18466. filterFilter: true,
  18467. jsonFilter: true,
  18468. limitToFilter: true,
  18469. lowercaseFilter: true,
  18470. numberFilter: true,
  18471. orderByFilter: true,
  18472. uppercaseFilter: true,
  18473. */
  18474. /**
  18475. * @ngdoc provider
  18476. * @name $filterProvider
  18477. * @description
  18478. *
  18479. * Filters are just functions which transform input to an output. However filters need to be
  18480. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  18481. * annotated with dependencies and is responsible for creating a filter function.
  18482. *
  18483. * <div class="alert alert-warning">
  18484. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18485. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18486. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18487. * (`myapp_subsection_filterx`).
  18488. * </div>
  18489. *
  18490. * ```js
  18491. * // Filter registration
  18492. * function MyModule($provide, $filterProvider) {
  18493. * // create a service to demonstrate injection (not always needed)
  18494. * $provide.value('greet', function(name){
  18495. * return 'Hello ' + name + '!';
  18496. * });
  18497. *
  18498. * // register a filter factory which uses the
  18499. * // greet service to demonstrate DI.
  18500. * $filterProvider.register('greet', function(greet){
  18501. * // return the filter function which uses the greet service
  18502. * // to generate salutation
  18503. * return function(text) {
  18504. * // filters need to be forgiving so check input validity
  18505. * return text && greet(text) || text;
  18506. * };
  18507. * });
  18508. * }
  18509. * ```
  18510. *
  18511. * The filter function is registered with the `$injector` under the filter name suffix with
  18512. * `Filter`.
  18513. *
  18514. * ```js
  18515. * it('should be the same instance', inject(
  18516. * function($filterProvider) {
  18517. * $filterProvider.register('reverse', function(){
  18518. * return ...;
  18519. * });
  18520. * },
  18521. * function($filter, reverseFilter) {
  18522. * expect($filter('reverse')).toBe(reverseFilter);
  18523. * });
  18524. * ```
  18525. *
  18526. *
  18527. * For more information about how angular filters work, and how to create your own filters, see
  18528. * {@link guide/filter Filters} in the Angular Developer Guide.
  18529. */
  18530. /**
  18531. * @ngdoc service
  18532. * @name $filter
  18533. * @kind function
  18534. * @description
  18535. * Filters are used for formatting data displayed to the user.
  18536. *
  18537. * They can be used in view templates, controllers or services.Angular comes
  18538. * with a collection of [built-in filters](api/ng/filter), but it is easy to
  18539. * define your own as well.
  18540. *
  18541. * The general syntax in templates is as follows:
  18542. *
  18543. * ```html
  18544. * {{ expression [| filter_name[:parameter_value] ... ] }}
  18545. * ```
  18546. *
  18547. * @param {String} name Name of the filter function to retrieve
  18548. * @return {Function} the filter function
  18549. * @example
  18550. <example name="$filter" module="filterExample">
  18551. <file name="index.html">
  18552. <div ng-controller="MainCtrl">
  18553. <h3>{{ originalText }}</h3>
  18554. <h3>{{ filteredText }}</h3>
  18555. </div>
  18556. </file>
  18557. <file name="script.js">
  18558. angular.module('filterExample', [])
  18559. .controller('MainCtrl', function($scope, $filter) {
  18560. $scope.originalText = 'hello';
  18561. $scope.filteredText = $filter('uppercase')($scope.originalText);
  18562. });
  18563. </file>
  18564. </example>
  18565. */
  18566. $FilterProvider.$inject = ['$provide'];
  18567. /** @this */
  18568. function $FilterProvider($provide) {
  18569. var suffix = 'Filter';
  18570. /**
  18571. * @ngdoc method
  18572. * @name $filterProvider#register
  18573. * @param {string|Object} name Name of the filter function, or an object map of filters where
  18574. * the keys are the filter names and the values are the filter factories.
  18575. *
  18576. * <div class="alert alert-warning">
  18577. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18578. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18579. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18580. * (`myapp_subsection_filterx`).
  18581. * </div>
  18582. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  18583. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  18584. * of the registered filter instances.
  18585. */
  18586. function register(name, factory) {
  18587. if (isObject(name)) {
  18588. var filters = {};
  18589. forEach(name, function(filter, key) {
  18590. filters[key] = register(key, filter);
  18591. });
  18592. return filters;
  18593. } else {
  18594. return $provide.factory(name + suffix, factory);
  18595. }
  18596. }
  18597. this.register = register;
  18598. this.$get = ['$injector', function($injector) {
  18599. return function(name) {
  18600. return $injector.get(name + suffix);
  18601. };
  18602. }];
  18603. ////////////////////////////////////////
  18604. /* global
  18605. currencyFilter: false,
  18606. dateFilter: false,
  18607. filterFilter: false,
  18608. jsonFilter: false,
  18609. limitToFilter: false,
  18610. lowercaseFilter: false,
  18611. numberFilter: false,
  18612. orderByFilter: false,
  18613. uppercaseFilter: false
  18614. */
  18615. register('currency', currencyFilter);
  18616. register('date', dateFilter);
  18617. register('filter', filterFilter);
  18618. register('json', jsonFilter);
  18619. register('limitTo', limitToFilter);
  18620. register('lowercase', lowercaseFilter);
  18621. register('number', numberFilter);
  18622. register('orderBy', orderByFilter);
  18623. register('uppercase', uppercaseFilter);
  18624. }
  18625. /**
  18626. * @ngdoc filter
  18627. * @name filter
  18628. * @kind function
  18629. *
  18630. * @description
  18631. * Selects a subset of items from `array` and returns it as a new array.
  18632. *
  18633. * @param {Array} array The source array.
  18634. * <div class="alert alert-info">
  18635. * **Note**: If the array contains objects that reference themselves, filtering is not possible.
  18636. * </div>
  18637. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  18638. * `array`.
  18639. *
  18640. * Can be one of:
  18641. *
  18642. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  18643. * objects with string properties in `array` that match this string will be returned. This also
  18644. * applies to nested object properties.
  18645. * The predicate can be negated by prefixing the string with `!`.
  18646. *
  18647. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  18648. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  18649. * which have property `name` containing "M" and property `phone` containing "1". A special
  18650. * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
  18651. * against any property of the object or its nested object properties. That's equivalent to the
  18652. * simple substring match with a `string` as described above. The special property name can be
  18653. * overwritten, using the `anyPropertyKey` parameter.
  18654. * The predicate can be negated by prefixing the string with `!`.
  18655. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  18656. * not containing "M".
  18657. *
  18658. * Note that a named property will match properties on the same level only, while the special
  18659. * `$` property will match properties on the same level or deeper. E.g. an array item like
  18660. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  18661. * **will** be matched by `{$: 'John'}`.
  18662. *
  18663. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  18664. * The function is called for each element of the array, with the element, its index, and
  18665. * the entire array itself as arguments.
  18666. *
  18667. * The final result is an array of those elements that the predicate returned true for.
  18668. *
  18669. * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in
  18670. * determining if the expected value (from the filter expression) and actual value (from
  18671. * the object in the array) should be considered a match.
  18672. *
  18673. * Can be one of:
  18674. *
  18675. * - `function(actual, expected)`:
  18676. * The function will be given the object value and the predicate value to compare and
  18677. * should return true if both values should be considered equal.
  18678. *
  18679. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  18680. * This is essentially strict comparison of expected and actual.
  18681. *
  18682. * - `false`: A short hand for a function which will look for a substring match in a case
  18683. * insensitive way. Primitive values are converted to strings. Objects are not compared against
  18684. * primitives, unless they have a custom `toString` method (e.g. `Date` objects).
  18685. *
  18686. *
  18687. * Defaults to `false`.
  18688. *
  18689. * @param {string} [anyPropertyKey] The special property name that matches against any property.
  18690. * By default `$`.
  18691. *
  18692. * @example
  18693. <example name="filter-filter">
  18694. <file name="index.html">
  18695. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  18696. {name:'Mary', phone:'800-BIG-MARY'},
  18697. {name:'Mike', phone:'555-4321'},
  18698. {name:'Adam', phone:'555-5678'},
  18699. {name:'Julie', phone:'555-8765'},
  18700. {name:'Juliette', phone:'555-5678'}]"></div>
  18701. <label>Search: <input ng-model="searchText"></label>
  18702. <table id="searchTextResults">
  18703. <tr><th>Name</th><th>Phone</th></tr>
  18704. <tr ng-repeat="friend in friends | filter:searchText">
  18705. <td>{{friend.name}}</td>
  18706. <td>{{friend.phone}}</td>
  18707. </tr>
  18708. </table>
  18709. <hr>
  18710. <label>Any: <input ng-model="search.$"></label> <br>
  18711. <label>Name only <input ng-model="search.name"></label><br>
  18712. <label>Phone only <input ng-model="search.phone"></label><br>
  18713. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  18714. <table id="searchObjResults">
  18715. <tr><th>Name</th><th>Phone</th></tr>
  18716. <tr ng-repeat="friendObj in friends | filter:search:strict">
  18717. <td>{{friendObj.name}}</td>
  18718. <td>{{friendObj.phone}}</td>
  18719. </tr>
  18720. </table>
  18721. </file>
  18722. <file name="protractor.js" type="protractor">
  18723. var expectFriendNames = function(expectedNames, key) {
  18724. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  18725. arr.forEach(function(wd, i) {
  18726. expect(wd.getText()).toMatch(expectedNames[i]);
  18727. });
  18728. });
  18729. };
  18730. it('should search across all fields when filtering with a string', function() {
  18731. var searchText = element(by.model('searchText'));
  18732. searchText.clear();
  18733. searchText.sendKeys('m');
  18734. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  18735. searchText.clear();
  18736. searchText.sendKeys('76');
  18737. expectFriendNames(['John', 'Julie'], 'friend');
  18738. });
  18739. it('should search in specific fields when filtering with a predicate object', function() {
  18740. var searchAny = element(by.model('search.$'));
  18741. searchAny.clear();
  18742. searchAny.sendKeys('i');
  18743. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  18744. });
  18745. it('should use a equal comparison when comparator is true', function() {
  18746. var searchName = element(by.model('search.name'));
  18747. var strict = element(by.model('strict'));
  18748. searchName.clear();
  18749. searchName.sendKeys('Julie');
  18750. strict.click();
  18751. expectFriendNames(['Julie'], 'friendObj');
  18752. });
  18753. </file>
  18754. </example>
  18755. */
  18756. function filterFilter() {
  18757. return function(array, expression, comparator, anyPropertyKey) {
  18758. if (!isArrayLike(array)) {
  18759. if (array == null) {
  18760. return array;
  18761. } else {
  18762. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  18763. }
  18764. }
  18765. anyPropertyKey = anyPropertyKey || '$';
  18766. var expressionType = getTypeForFilter(expression);
  18767. var predicateFn;
  18768. var matchAgainstAnyProp;
  18769. switch (expressionType) {
  18770. case 'function':
  18771. predicateFn = expression;
  18772. break;
  18773. case 'boolean':
  18774. case 'null':
  18775. case 'number':
  18776. case 'string':
  18777. matchAgainstAnyProp = true;
  18778. // falls through
  18779. case 'object':
  18780. predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18781. break;
  18782. default:
  18783. return array;
  18784. }
  18785. return Array.prototype.filter.call(array, predicateFn);
  18786. };
  18787. }
  18788. // Helper functions for `filterFilter`
  18789. function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
  18790. var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
  18791. var predicateFn;
  18792. if (comparator === true) {
  18793. comparator = equals;
  18794. } else if (!isFunction(comparator)) {
  18795. comparator = function(actual, expected) {
  18796. if (isUndefined(actual)) {
  18797. // No substring matching against `undefined`
  18798. return false;
  18799. }
  18800. if ((actual === null) || (expected === null)) {
  18801. // No substring matching against `null`; only match against `null`
  18802. return actual === expected;
  18803. }
  18804. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  18805. // Should not compare primitives against objects, unless they have custom `toString` method
  18806. return false;
  18807. }
  18808. actual = lowercase('' + actual);
  18809. expected = lowercase('' + expected);
  18810. return actual.indexOf(expected) !== -1;
  18811. };
  18812. }
  18813. predicateFn = function(item) {
  18814. if (shouldMatchPrimitives && !isObject(item)) {
  18815. return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
  18816. }
  18817. return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18818. };
  18819. return predicateFn;
  18820. }
  18821. function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
  18822. var actualType = getTypeForFilter(actual);
  18823. var expectedType = getTypeForFilter(expected);
  18824. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  18825. return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
  18826. } else if (isArray(actual)) {
  18827. // In case `actual` is an array, consider it a match
  18828. // if ANY of it's items matches `expected`
  18829. return actual.some(function(item) {
  18830. return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
  18831. });
  18832. }
  18833. switch (actualType) {
  18834. case 'object':
  18835. var key;
  18836. if (matchAgainstAnyProp) {
  18837. for (key in actual) {
  18838. // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined
  18839. // See: https://github.com/angular/angular.js/issues/15644
  18840. if (key.charAt && (key.charAt(0) !== '$') &&
  18841. deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
  18842. return true;
  18843. }
  18844. }
  18845. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
  18846. } else if (expectedType === 'object') {
  18847. for (key in expected) {
  18848. var expectedVal = expected[key];
  18849. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  18850. continue;
  18851. }
  18852. var matchAnyProperty = key === anyPropertyKey;
  18853. var actualVal = matchAnyProperty ? actual : actual[key];
  18854. if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
  18855. return false;
  18856. }
  18857. }
  18858. return true;
  18859. } else {
  18860. return comparator(actual, expected);
  18861. }
  18862. case 'function':
  18863. return false;
  18864. default:
  18865. return comparator(actual, expected);
  18866. }
  18867. }
  18868. // Used for easily differentiating between `null` and actual `object`
  18869. function getTypeForFilter(val) {
  18870. return (val === null) ? 'null' : typeof val;
  18871. }
  18872. var MAX_DIGITS = 22;
  18873. var DECIMAL_SEP = '.';
  18874. var ZERO_CHAR = '0';
  18875. /**
  18876. * @ngdoc filter
  18877. * @name currency
  18878. * @kind function
  18879. *
  18880. * @description
  18881. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  18882. * symbol for current locale is used.
  18883. *
  18884. * @param {number} amount Input to filter.
  18885. * @param {string=} symbol Currency symbol or identifier to be displayed.
  18886. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  18887. * @returns {string} Formatted number.
  18888. *
  18889. *
  18890. * @example
  18891. <example module="currencyExample" name="currency-filter">
  18892. <file name="index.html">
  18893. <script>
  18894. angular.module('currencyExample', [])
  18895. .controller('ExampleController', ['$scope', function($scope) {
  18896. $scope.amount = 1234.56;
  18897. }]);
  18898. </script>
  18899. <div ng-controller="ExampleController">
  18900. <input type="number" ng-model="amount" aria-label="amount"> <br>
  18901. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  18902. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
  18903. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  18904. </div>
  18905. </file>
  18906. <file name="protractor.js" type="protractor">
  18907. it('should init with 1234.56', function() {
  18908. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  18909. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  18910. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  18911. });
  18912. it('should update', function() {
  18913. if (browser.params.browser === 'safari') {
  18914. // Safari does not understand the minus key. See
  18915. // https://github.com/angular/protractor/issues/481
  18916. return;
  18917. }
  18918. element(by.model('amount')).clear();
  18919. element(by.model('amount')).sendKeys('-1234');
  18920. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  18921. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  18922. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  18923. });
  18924. </file>
  18925. </example>
  18926. */
  18927. currencyFilter.$inject = ['$locale'];
  18928. function currencyFilter($locale) {
  18929. var formats = $locale.NUMBER_FORMATS;
  18930. return function(amount, currencySymbol, fractionSize) {
  18931. if (isUndefined(currencySymbol)) {
  18932. currencySymbol = formats.CURRENCY_SYM;
  18933. }
  18934. if (isUndefined(fractionSize)) {
  18935. fractionSize = formats.PATTERNS[1].maxFrac;
  18936. }
  18937. // if null or undefined pass it through
  18938. return (amount == null)
  18939. ? amount
  18940. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  18941. replace(/\u00A4/g, currencySymbol);
  18942. };
  18943. }
  18944. /**
  18945. * @ngdoc filter
  18946. * @name number
  18947. * @kind function
  18948. *
  18949. * @description
  18950. * Formats a number as text.
  18951. *
  18952. * If the input is null or undefined, it will just be returned.
  18953. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  18954. * If the input is not a number an empty string is returned.
  18955. *
  18956. *
  18957. * @param {number|string} number Number to format.
  18958. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  18959. * If this is not provided then the fraction size is computed from the current locale's number
  18960. * formatting pattern. In the case of the default locale, it will be 3.
  18961. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  18962. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  18963. * include "," group separators after each third digit).
  18964. *
  18965. * @example
  18966. <example module="numberFilterExample" name="number-filter">
  18967. <file name="index.html">
  18968. <script>
  18969. angular.module('numberFilterExample', [])
  18970. .controller('ExampleController', ['$scope', function($scope) {
  18971. $scope.val = 1234.56789;
  18972. }]);
  18973. </script>
  18974. <div ng-controller="ExampleController">
  18975. <label>Enter number: <input ng-model='val'></label><br>
  18976. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  18977. No fractions: <span>{{val | number:0}}</span><br>
  18978. Negative number: <span>{{-val | number:4}}</span>
  18979. </div>
  18980. </file>
  18981. <file name="protractor.js" type="protractor">
  18982. it('should format numbers', function() {
  18983. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  18984. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  18985. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  18986. });
  18987. it('should update', function() {
  18988. element(by.model('val')).clear();
  18989. element(by.model('val')).sendKeys('3374.333');
  18990. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  18991. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  18992. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  18993. });
  18994. </file>
  18995. </example>
  18996. */
  18997. numberFilter.$inject = ['$locale'];
  18998. function numberFilter($locale) {
  18999. var formats = $locale.NUMBER_FORMATS;
  19000. return function(number, fractionSize) {
  19001. // if null or undefined pass it through
  19002. return (number == null)
  19003. ? number
  19004. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  19005. fractionSize);
  19006. };
  19007. }
  19008. /**
  19009. * Parse a number (as a string) into three components that can be used
  19010. * for formatting the number.
  19011. *
  19012. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  19013. *
  19014. * @param {string} numStr The number to parse
  19015. * @return {object} An object describing this number, containing the following keys:
  19016. * - d : an array of digits containing leading zeros as necessary
  19017. * - i : the number of the digits in `d` that are to the left of the decimal point
  19018. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  19019. *
  19020. */
  19021. function parse(numStr) {
  19022. var exponent = 0, digits, numberOfIntegerDigits;
  19023. var i, j, zeros;
  19024. // Decimal point?
  19025. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  19026. numStr = numStr.replace(DECIMAL_SEP, '');
  19027. }
  19028. // Exponential form?
  19029. if ((i = numStr.search(/e/i)) > 0) {
  19030. // Work out the exponent.
  19031. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  19032. numberOfIntegerDigits += +numStr.slice(i + 1);
  19033. numStr = numStr.substring(0, i);
  19034. } else if (numberOfIntegerDigits < 0) {
  19035. // There was no decimal point or exponent so it is an integer.
  19036. numberOfIntegerDigits = numStr.length;
  19037. }
  19038. // Count the number of leading zeros.
  19039. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
  19040. if (i === (zeros = numStr.length)) {
  19041. // The digits are all zero.
  19042. digits = [0];
  19043. numberOfIntegerDigits = 1;
  19044. } else {
  19045. // Count the number of trailing zeros
  19046. zeros--;
  19047. while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
  19048. // Trailing zeros are insignificant so ignore them
  19049. numberOfIntegerDigits -= i;
  19050. digits = [];
  19051. // Convert string to array of digits without leading/trailing zeros.
  19052. for (j = 0; i <= zeros; i++, j++) {
  19053. digits[j] = +numStr.charAt(i);
  19054. }
  19055. }
  19056. // If the number overflows the maximum allowed digits then use an exponent.
  19057. if (numberOfIntegerDigits > MAX_DIGITS) {
  19058. digits = digits.splice(0, MAX_DIGITS - 1);
  19059. exponent = numberOfIntegerDigits - 1;
  19060. numberOfIntegerDigits = 1;
  19061. }
  19062. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  19063. }
  19064. /**
  19065. * Round the parsed number to the specified number of decimal places
  19066. * This function changed the parsedNumber in-place
  19067. */
  19068. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  19069. var digits = parsedNumber.d;
  19070. var fractionLen = digits.length - parsedNumber.i;
  19071. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  19072. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  19073. // The index of the digit to where rounding is to occur
  19074. var roundAt = fractionSize + parsedNumber.i;
  19075. var digit = digits[roundAt];
  19076. if (roundAt > 0) {
  19077. // Drop fractional digits beyond `roundAt`
  19078. digits.splice(Math.max(parsedNumber.i, roundAt));
  19079. // Set non-fractional digits beyond `roundAt` to 0
  19080. for (var j = roundAt; j < digits.length; j++) {
  19081. digits[j] = 0;
  19082. }
  19083. } else {
  19084. // We rounded to zero so reset the parsedNumber
  19085. fractionLen = Math.max(0, fractionLen);
  19086. parsedNumber.i = 1;
  19087. digits.length = Math.max(1, roundAt = fractionSize + 1);
  19088. digits[0] = 0;
  19089. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  19090. }
  19091. if (digit >= 5) {
  19092. if (roundAt - 1 < 0) {
  19093. for (var k = 0; k > roundAt; k--) {
  19094. digits.unshift(0);
  19095. parsedNumber.i++;
  19096. }
  19097. digits.unshift(1);
  19098. parsedNumber.i++;
  19099. } else {
  19100. digits[roundAt - 1]++;
  19101. }
  19102. }
  19103. // Pad out with zeros to get the required fraction length
  19104. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  19105. // Do any carrying, e.g. a digit was rounded up to 10
  19106. var carry = digits.reduceRight(function(carry, d, i, digits) {
  19107. d = d + carry;
  19108. digits[i] = d % 10;
  19109. return Math.floor(d / 10);
  19110. }, 0);
  19111. if (carry) {
  19112. digits.unshift(carry);
  19113. parsedNumber.i++;
  19114. }
  19115. }
  19116. /**
  19117. * Format a number into a string
  19118. * @param {number} number The number to format
  19119. * @param {{
  19120. * minFrac, // the minimum number of digits required in the fraction part of the number
  19121. * maxFrac, // the maximum number of digits required in the fraction part of the number
  19122. * gSize, // number of digits in each group of separated digits
  19123. * lgSize, // number of digits in the last group of digits before the decimal separator
  19124. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  19125. * posPre, // the string to go in front of a positive number
  19126. * negSuf, // the string to go after a negative number (e.g. `)`)
  19127. * posSuf // the string to go after a positive number
  19128. * }} pattern
  19129. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  19130. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  19131. * @param {[type]} fractionSize The size of the fractional part of the number
  19132. * @return {string} The number formatted as a string
  19133. */
  19134. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  19135. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  19136. var isInfinity = !isFinite(number);
  19137. var isZero = false;
  19138. var numStr = Math.abs(number) + '',
  19139. formattedText = '',
  19140. parsedNumber;
  19141. if (isInfinity) {
  19142. formattedText = '\u221e';
  19143. } else {
  19144. parsedNumber = parse(numStr);
  19145. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  19146. var digits = parsedNumber.d;
  19147. var integerLen = parsedNumber.i;
  19148. var exponent = parsedNumber.e;
  19149. var decimals = [];
  19150. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  19151. // pad zeros for small numbers
  19152. while (integerLen < 0) {
  19153. digits.unshift(0);
  19154. integerLen++;
  19155. }
  19156. // extract decimals digits
  19157. if (integerLen > 0) {
  19158. decimals = digits.splice(integerLen, digits.length);
  19159. } else {
  19160. decimals = digits;
  19161. digits = [0];
  19162. }
  19163. // format the integer digits with grouping separators
  19164. var groups = [];
  19165. if (digits.length >= pattern.lgSize) {
  19166. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  19167. }
  19168. while (digits.length > pattern.gSize) {
  19169. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  19170. }
  19171. if (digits.length) {
  19172. groups.unshift(digits.join(''));
  19173. }
  19174. formattedText = groups.join(groupSep);
  19175. // append the decimal digits
  19176. if (decimals.length) {
  19177. formattedText += decimalSep + decimals.join('');
  19178. }
  19179. if (exponent) {
  19180. formattedText += 'e+' + exponent;
  19181. }
  19182. }
  19183. if (number < 0 && !isZero) {
  19184. return pattern.negPre + formattedText + pattern.negSuf;
  19185. } else {
  19186. return pattern.posPre + formattedText + pattern.posSuf;
  19187. }
  19188. }
  19189. function padNumber(num, digits, trim, negWrap) {
  19190. var neg = '';
  19191. if (num < 0 || (negWrap && num <= 0)) {
  19192. if (negWrap) {
  19193. num = -num + 1;
  19194. } else {
  19195. num = -num;
  19196. neg = '-';
  19197. }
  19198. }
  19199. num = '' + num;
  19200. while (num.length < digits) num = ZERO_CHAR + num;
  19201. if (trim) {
  19202. num = num.substr(num.length - digits);
  19203. }
  19204. return neg + num;
  19205. }
  19206. function dateGetter(name, size, offset, trim, negWrap) {
  19207. offset = offset || 0;
  19208. return function(date) {
  19209. var value = date['get' + name]();
  19210. if (offset > 0 || value > -offset) {
  19211. value += offset;
  19212. }
  19213. if (value === 0 && offset === -12) value = 12;
  19214. return padNumber(value, size, trim, negWrap);
  19215. };
  19216. }
  19217. function dateStrGetter(name, shortForm, standAlone) {
  19218. return function(date, formats) {
  19219. var value = date['get' + name]();
  19220. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  19221. var get = uppercase(propPrefix + name);
  19222. return formats[get][value];
  19223. };
  19224. }
  19225. function timeZoneGetter(date, formats, offset) {
  19226. var zone = -1 * offset;
  19227. var paddedZone = (zone >= 0) ? '+' : '';
  19228. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  19229. padNumber(Math.abs(zone % 60), 2);
  19230. return paddedZone;
  19231. }
  19232. function getFirstThursdayOfYear(year) {
  19233. // 0 = index of January
  19234. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  19235. // 4 = index of Thursday (+1 to account for 1st = 5)
  19236. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  19237. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  19238. }
  19239. function getThursdayThisWeek(datetime) {
  19240. return new Date(datetime.getFullYear(), datetime.getMonth(),
  19241. // 4 = index of Thursday
  19242. datetime.getDate() + (4 - datetime.getDay()));
  19243. }
  19244. function weekGetter(size) {
  19245. return function(date) {
  19246. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  19247. thisThurs = getThursdayThisWeek(date);
  19248. var diff = +thisThurs - +firstThurs,
  19249. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  19250. return padNumber(result, size);
  19251. };
  19252. }
  19253. function ampmGetter(date, formats) {
  19254. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  19255. }
  19256. function eraGetter(date, formats) {
  19257. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  19258. }
  19259. function longEraGetter(date, formats) {
  19260. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  19261. }
  19262. var DATE_FORMATS = {
  19263. yyyy: dateGetter('FullYear', 4, 0, false, true),
  19264. yy: dateGetter('FullYear', 2, 0, true, true),
  19265. y: dateGetter('FullYear', 1, 0, false, true),
  19266. MMMM: dateStrGetter('Month'),
  19267. MMM: dateStrGetter('Month', true),
  19268. MM: dateGetter('Month', 2, 1),
  19269. M: dateGetter('Month', 1, 1),
  19270. LLLL: dateStrGetter('Month', false, true),
  19271. dd: dateGetter('Date', 2),
  19272. d: dateGetter('Date', 1),
  19273. HH: dateGetter('Hours', 2),
  19274. H: dateGetter('Hours', 1),
  19275. hh: dateGetter('Hours', 2, -12),
  19276. h: dateGetter('Hours', 1, -12),
  19277. mm: dateGetter('Minutes', 2),
  19278. m: dateGetter('Minutes', 1),
  19279. ss: dateGetter('Seconds', 2),
  19280. s: dateGetter('Seconds', 1),
  19281. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  19282. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  19283. sss: dateGetter('Milliseconds', 3),
  19284. EEEE: dateStrGetter('Day'),
  19285. EEE: dateStrGetter('Day', true),
  19286. a: ampmGetter,
  19287. Z: timeZoneGetter,
  19288. ww: weekGetter(2),
  19289. w: weekGetter(1),
  19290. G: eraGetter,
  19291. GG: eraGetter,
  19292. GGG: eraGetter,
  19293. GGGG: longEraGetter
  19294. };
  19295. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  19296. NUMBER_STRING = /^-?\d+$/;
  19297. /**
  19298. * @ngdoc filter
  19299. * @name date
  19300. * @kind function
  19301. *
  19302. * @description
  19303. * Formats `date` to a string based on the requested `format`.
  19304. *
  19305. * `format` string can be composed of the following elements:
  19306. *
  19307. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  19308. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  19309. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  19310. * * `'MMMM'`: Month in year (January-December)
  19311. * * `'MMM'`: Month in year (Jan-Dec)
  19312. * * `'MM'`: Month in year, padded (01-12)
  19313. * * `'M'`: Month in year (1-12)
  19314. * * `'LLLL'`: Stand-alone month in year (January-December)
  19315. * * `'dd'`: Day in month, padded (01-31)
  19316. * * `'d'`: Day in month (1-31)
  19317. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  19318. * * `'EEE'`: Day in Week, (Sun-Sat)
  19319. * * `'HH'`: Hour in day, padded (00-23)
  19320. * * `'H'`: Hour in day (0-23)
  19321. * * `'hh'`: Hour in AM/PM, padded (01-12)
  19322. * * `'h'`: Hour in AM/PM, (1-12)
  19323. * * `'mm'`: Minute in hour, padded (00-59)
  19324. * * `'m'`: Minute in hour (0-59)
  19325. * * `'ss'`: Second in minute, padded (00-59)
  19326. * * `'s'`: Second in minute (0-59)
  19327. * * `'sss'`: Millisecond in second, padded (000-999)
  19328. * * `'a'`: AM/PM marker
  19329. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  19330. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  19331. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  19332. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  19333. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  19334. *
  19335. * `format` string can also be one of the following predefined
  19336. * {@link guide/i18n localizable formats}:
  19337. *
  19338. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  19339. * (e.g. Sep 3, 2010 12:05:08 PM)
  19340. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  19341. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  19342. * (e.g. Friday, September 3, 2010)
  19343. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  19344. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  19345. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  19346. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  19347. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  19348. *
  19349. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  19350. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  19351. * (e.g. `"h 'o''clock'"`).
  19352. *
  19353. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  19354. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  19355. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  19356. * specified in the string input, the time is considered to be in the local timezone.
  19357. * @param {string=} format Formatting rules (see Description). If not specified,
  19358. * `mediumDate` is used.
  19359. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  19360. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  19361. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  19362. * If not specified, the timezone of the browser will be used.
  19363. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  19364. *
  19365. * @example
  19366. <example name="filter-date">
  19367. <file name="index.html">
  19368. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  19369. <span>{{1288323623006 | date:'medium'}}</span><br>
  19370. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  19371. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  19372. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  19373. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  19374. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  19375. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  19376. </file>
  19377. <file name="protractor.js" type="protractor">
  19378. it('should format date', function() {
  19379. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  19380. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  19381. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  19382. toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
  19383. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  19384. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  19385. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  19386. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  19387. });
  19388. </file>
  19389. </example>
  19390. */
  19391. dateFilter.$inject = ['$locale'];
  19392. function dateFilter($locale) {
  19393. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  19394. // 1 2 3 4 5 6 7 8 9 10 11
  19395. function jsonStringToDate(string) {
  19396. var match;
  19397. if ((match = string.match(R_ISO8601_STR))) {
  19398. var date = new Date(0),
  19399. tzHour = 0,
  19400. tzMin = 0,
  19401. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  19402. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  19403. if (match[9]) {
  19404. tzHour = toInt(match[9] + match[10]);
  19405. tzMin = toInt(match[9] + match[11]);
  19406. }
  19407. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  19408. var h = toInt(match[4] || 0) - tzHour;
  19409. var m = toInt(match[5] || 0) - tzMin;
  19410. var s = toInt(match[6] || 0);
  19411. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  19412. timeSetter.call(date, h, m, s, ms);
  19413. return date;
  19414. }
  19415. return string;
  19416. }
  19417. return function(date, format, timezone) {
  19418. var text = '',
  19419. parts = [],
  19420. fn, match;
  19421. format = format || 'mediumDate';
  19422. format = $locale.DATETIME_FORMATS[format] || format;
  19423. if (isString(date)) {
  19424. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  19425. }
  19426. if (isNumber(date)) {
  19427. date = new Date(date);
  19428. }
  19429. if (!isDate(date) || !isFinite(date.getTime())) {
  19430. return date;
  19431. }
  19432. while (format) {
  19433. match = DATE_FORMATS_SPLIT.exec(format);
  19434. if (match) {
  19435. parts = concat(parts, match, 1);
  19436. format = parts.pop();
  19437. } else {
  19438. parts.push(format);
  19439. format = null;
  19440. }
  19441. }
  19442. var dateTimezoneOffset = date.getTimezoneOffset();
  19443. if (timezone) {
  19444. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  19445. date = convertTimezoneToLocal(date, timezone, true);
  19446. }
  19447. forEach(parts, function(value) {
  19448. fn = DATE_FORMATS[value];
  19449. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  19450. : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
  19451. });
  19452. return text;
  19453. };
  19454. }
  19455. /**
  19456. * @ngdoc filter
  19457. * @name json
  19458. * @kind function
  19459. *
  19460. * @description
  19461. * Allows you to convert a JavaScript object into JSON string.
  19462. *
  19463. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  19464. * the binding is automatically converted to JSON.
  19465. *
  19466. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  19467. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  19468. * @returns {string} JSON string.
  19469. *
  19470. *
  19471. * @example
  19472. <example name="filter-json">
  19473. <file name="index.html">
  19474. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  19475. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  19476. </file>
  19477. <file name="protractor.js" type="protractor">
  19478. it('should jsonify filtered objects', function() {
  19479. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
  19480. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
  19481. });
  19482. </file>
  19483. </example>
  19484. *
  19485. */
  19486. function jsonFilter() {
  19487. return function(object, spacing) {
  19488. if (isUndefined(spacing)) {
  19489. spacing = 2;
  19490. }
  19491. return toJson(object, spacing);
  19492. };
  19493. }
  19494. /**
  19495. * @ngdoc filter
  19496. * @name lowercase
  19497. * @kind function
  19498. * @description
  19499. * Converts string to lowercase.
  19500. * @see angular.lowercase
  19501. */
  19502. var lowercaseFilter = valueFn(lowercase);
  19503. /**
  19504. * @ngdoc filter
  19505. * @name uppercase
  19506. * @kind function
  19507. * @description
  19508. * Converts string to uppercase.
  19509. * @see angular.uppercase
  19510. */
  19511. var uppercaseFilter = valueFn(uppercase);
  19512. /**
  19513. * @ngdoc filter
  19514. * @name limitTo
  19515. * @kind function
  19516. *
  19517. * @description
  19518. * Creates a new array or string containing only a specified number of elements. The elements are
  19519. * taken from either the beginning or the end of the source array, string or number, as specified by
  19520. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  19521. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  19522. * it is converted to a string.
  19523. *
  19524. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  19525. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  19526. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  19527. * If the number is negative, `limit` number of items from the end of the source array/string
  19528. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  19529. * the input will be returned unchanged.
  19530. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  19531. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  19532. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  19533. * less than `limit` elements.
  19534. *
  19535. * @example
  19536. <example module="limitToExample" name="limit-to-filter">
  19537. <file name="index.html">
  19538. <script>
  19539. angular.module('limitToExample', [])
  19540. .controller('ExampleController', ['$scope', function($scope) {
  19541. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  19542. $scope.letters = "abcdefghi";
  19543. $scope.longNumber = 2345432342;
  19544. $scope.numLimit = 3;
  19545. $scope.letterLimit = 3;
  19546. $scope.longNumberLimit = 3;
  19547. }]);
  19548. </script>
  19549. <div ng-controller="ExampleController">
  19550. <label>
  19551. Limit {{numbers}} to:
  19552. <input type="number" step="1" ng-model="numLimit">
  19553. </label>
  19554. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  19555. <label>
  19556. Limit {{letters}} to:
  19557. <input type="number" step="1" ng-model="letterLimit">
  19558. </label>
  19559. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  19560. <label>
  19561. Limit {{longNumber}} to:
  19562. <input type="number" step="1" ng-model="longNumberLimit">
  19563. </label>
  19564. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  19565. </div>
  19566. </file>
  19567. <file name="protractor.js" type="protractor">
  19568. var numLimitInput = element(by.model('numLimit'));
  19569. var letterLimitInput = element(by.model('letterLimit'));
  19570. var longNumberLimitInput = element(by.model('longNumberLimit'));
  19571. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  19572. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  19573. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  19574. it('should limit the number array to first three items', function() {
  19575. expect(numLimitInput.getAttribute('value')).toBe('3');
  19576. expect(letterLimitInput.getAttribute('value')).toBe('3');
  19577. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  19578. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  19579. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  19580. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  19581. });
  19582. // There is a bug in safari and protractor that doesn't like the minus key
  19583. // it('should update the output when -3 is entered', function() {
  19584. // numLimitInput.clear();
  19585. // numLimitInput.sendKeys('-3');
  19586. // letterLimitInput.clear();
  19587. // letterLimitInput.sendKeys('-3');
  19588. // longNumberLimitInput.clear();
  19589. // longNumberLimitInput.sendKeys('-3');
  19590. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  19591. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  19592. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  19593. // });
  19594. it('should not exceed the maximum size of input array', function() {
  19595. numLimitInput.clear();
  19596. numLimitInput.sendKeys('100');
  19597. letterLimitInput.clear();
  19598. letterLimitInput.sendKeys('100');
  19599. longNumberLimitInput.clear();
  19600. longNumberLimitInput.sendKeys('100');
  19601. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  19602. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  19603. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  19604. });
  19605. </file>
  19606. </example>
  19607. */
  19608. function limitToFilter() {
  19609. return function(input, limit, begin) {
  19610. if (Math.abs(Number(limit)) === Infinity) {
  19611. limit = Number(limit);
  19612. } else {
  19613. limit = toInt(limit);
  19614. }
  19615. if (isNumberNaN(limit)) return input;
  19616. if (isNumber(input)) input = input.toString();
  19617. if (!isArrayLike(input)) return input;
  19618. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  19619. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  19620. if (limit >= 0) {
  19621. return sliceFn(input, begin, begin + limit);
  19622. } else {
  19623. if (begin === 0) {
  19624. return sliceFn(input, limit, input.length);
  19625. } else {
  19626. return sliceFn(input, Math.max(0, begin + limit), begin);
  19627. }
  19628. }
  19629. };
  19630. }
  19631. function sliceFn(input, begin, end) {
  19632. if (isString(input)) return input.slice(begin, end);
  19633. return slice.call(input, begin, end);
  19634. }
  19635. /**
  19636. * @ngdoc filter
  19637. * @name orderBy
  19638. * @kind function
  19639. *
  19640. * @description
  19641. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  19642. * function based on the values computed using the `expression` predicate.
  19643. *
  19644. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  19645. * `[{id: 'bar'}, {id: 'foo'}]`.
  19646. *
  19647. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  19648. * String, etc).
  19649. *
  19650. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  19651. * for the preceding one. The `expression` is evaluated against each item and the output is used
  19652. * for comparing with other items.
  19653. *
  19654. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  19655. * ascending order.
  19656. *
  19657. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  19658. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  19659. * strings alphabetically).
  19660. *
  19661. * ### Under the hood
  19662. *
  19663. * Ordering the specified `collection` happens in two phases:
  19664. *
  19665. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  19666. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  19667. * through a predicate that extracts the value of the `label` property, would be transformed to:
  19668. * ```
  19669. * {
  19670. * value: 'foo',
  19671. * type: 'string',
  19672. * index: ...
  19673. * }
  19674. * ```
  19675. * 2. The comparator function is used to sort the items, based on the derived values, types and
  19676. * indices.
  19677. *
  19678. * If you use a custom comparator, it will be called with pairs of objects of the form
  19679. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  19680. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  19681. * second, or `1` otherwise.
  19682. *
  19683. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  19684. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  19685. * dummy predicate that returns the item's index as `value`.
  19686. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  19687. *
  19688. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  19689. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  19690. * it to the comparator. The following rules govern the conversion:
  19691. *
  19692. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  19693. * used instead.<br />
  19694. * (If the object has a `valueOf()` method that returns another object, then the returned object
  19695. * will be used in subsequent steps.)
  19696. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  19697. * returns a primitive, its return value will be used instead.<br />
  19698. * (If the object has a `toString()` method that returns another object, then the returned object
  19699. * will be used in subsequent steps.)
  19700. * 3. No conversion; the object itself is used.
  19701. *
  19702. * ### The default comparator
  19703. *
  19704. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  19705. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  19706. * using their index in the original collection, and sorts values of different types by type.
  19707. *
  19708. * More specifically, it follows these steps to determine the relative order of items:
  19709. *
  19710. * 1. If the compared values are of different types, compare the types themselves alphabetically.
  19711. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  19712. * locale-insensitive way.
  19713. * 3. If both values are objects, compare their indices instead.
  19714. * 4. Otherwise, return:
  19715. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  19716. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  19717. * - `1`, otherwise.
  19718. *
  19719. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  19720. * saved as numbers and not strings.
  19721. * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e.
  19722. * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to
  19723. * other values.
  19724. *
  19725. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  19726. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  19727. * predicates) to be used by the comparator to determine the order of elements.
  19728. *
  19729. * Can be one of:
  19730. *
  19731. * - `Function`: A getter function. This function will be called with each item as argument and
  19732. * the return value will be used for sorting.
  19733. * - `string`: An Angular expression. This expression will be evaluated against each item and the
  19734. * result will be used for sorting. For example, use `'label'` to sort by a property called
  19735. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  19736. * property.<br />
  19737. * (The result of a constant expression is interpreted as a property name to be used for
  19738. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  19739. * property called `special name`.)<br />
  19740. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  19741. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  19742. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  19743. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  19744. * relative order of two items, the next predicate is used as a tie-breaker.
  19745. *
  19746. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  19747. *
  19748. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  19749. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  19750. * value pairs. If omitted, the built-in comparator will be used.
  19751. *
  19752. * @returns {Array} - The sorted array.
  19753. *
  19754. *
  19755. * @example
  19756. * ### Ordering a table with `ngRepeat`
  19757. *
  19758. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  19759. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  19760. * it defaults to the built-in comparator.
  19761. *
  19762. <example name="orderBy-static" module="orderByExample1">
  19763. <file name="index.html">
  19764. <div ng-controller="ExampleController">
  19765. <table class="friends">
  19766. <tr>
  19767. <th>Name</th>
  19768. <th>Phone Number</th>
  19769. <th>Age</th>
  19770. </tr>
  19771. <tr ng-repeat="friend in friends | orderBy:'-age'">
  19772. <td>{{friend.name}}</td>
  19773. <td>{{friend.phone}}</td>
  19774. <td>{{friend.age}}</td>
  19775. </tr>
  19776. </table>
  19777. </div>
  19778. </file>
  19779. <file name="script.js">
  19780. angular.module('orderByExample1', [])
  19781. .controller('ExampleController', ['$scope', function($scope) {
  19782. $scope.friends = [
  19783. {name: 'John', phone: '555-1212', age: 10},
  19784. {name: 'Mary', phone: '555-9876', age: 19},
  19785. {name: 'Mike', phone: '555-4321', age: 21},
  19786. {name: 'Adam', phone: '555-5678', age: 35},
  19787. {name: 'Julie', phone: '555-8765', age: 29}
  19788. ];
  19789. }]);
  19790. </file>
  19791. <file name="style.css">
  19792. .friends {
  19793. border-collapse: collapse;
  19794. }
  19795. .friends th {
  19796. border-bottom: 1px solid;
  19797. }
  19798. .friends td, .friends th {
  19799. border-left: 1px solid;
  19800. padding: 5px 10px;
  19801. }
  19802. .friends td:first-child, .friends th:first-child {
  19803. border-left: none;
  19804. }
  19805. </file>
  19806. <file name="protractor.js" type="protractor">
  19807. // Element locators
  19808. var names = element.all(by.repeater('friends').column('friend.name'));
  19809. it('should sort friends by age in reverse order', function() {
  19810. expect(names.get(0).getText()).toBe('Adam');
  19811. expect(names.get(1).getText()).toBe('Julie');
  19812. expect(names.get(2).getText()).toBe('Mike');
  19813. expect(names.get(3).getText()).toBe('Mary');
  19814. expect(names.get(4).getText()).toBe('John');
  19815. });
  19816. </file>
  19817. </example>
  19818. * <hr />
  19819. *
  19820. * @example
  19821. * ### Changing parameters dynamically
  19822. *
  19823. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  19824. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  19825. *
  19826. <example name="orderBy-dynamic" module="orderByExample2">
  19827. <file name="index.html">
  19828. <div ng-controller="ExampleController">
  19829. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19830. <hr/>
  19831. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  19832. <hr/>
  19833. <table class="friends">
  19834. <tr>
  19835. <th>
  19836. <button ng-click="sortBy('name')">Name</button>
  19837. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19838. </th>
  19839. <th>
  19840. <button ng-click="sortBy('phone')">Phone Number</button>
  19841. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19842. </th>
  19843. <th>
  19844. <button ng-click="sortBy('age')">Age</button>
  19845. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19846. </th>
  19847. </tr>
  19848. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  19849. <td>{{friend.name}}</td>
  19850. <td>{{friend.phone}}</td>
  19851. <td>{{friend.age}}</td>
  19852. </tr>
  19853. </table>
  19854. </div>
  19855. </file>
  19856. <file name="script.js">
  19857. angular.module('orderByExample2', [])
  19858. .controller('ExampleController', ['$scope', function($scope) {
  19859. var friends = [
  19860. {name: 'John', phone: '555-1212', age: 10},
  19861. {name: 'Mary', phone: '555-9876', age: 19},
  19862. {name: 'Mike', phone: '555-4321', age: 21},
  19863. {name: 'Adam', phone: '555-5678', age: 35},
  19864. {name: 'Julie', phone: '555-8765', age: 29}
  19865. ];
  19866. $scope.propertyName = 'age';
  19867. $scope.reverse = true;
  19868. $scope.friends = friends;
  19869. $scope.sortBy = function(propertyName) {
  19870. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  19871. $scope.propertyName = propertyName;
  19872. };
  19873. }]);
  19874. </file>
  19875. <file name="style.css">
  19876. .friends {
  19877. border-collapse: collapse;
  19878. }
  19879. .friends th {
  19880. border-bottom: 1px solid;
  19881. }
  19882. .friends td, .friends th {
  19883. border-left: 1px solid;
  19884. padding: 5px 10px;
  19885. }
  19886. .friends td:first-child, .friends th:first-child {
  19887. border-left: none;
  19888. }
  19889. .sortorder:after {
  19890. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19891. }
  19892. .sortorder.reverse:after {
  19893. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19894. }
  19895. </file>
  19896. <file name="protractor.js" type="protractor">
  19897. // Element locators
  19898. var unsortButton = element(by.partialButtonText('unsorted'));
  19899. var nameHeader = element(by.partialButtonText('Name'));
  19900. var phoneHeader = element(by.partialButtonText('Phone'));
  19901. var ageHeader = element(by.partialButtonText('Age'));
  19902. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19903. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19904. it('should sort friends by some property, when clicking on the column header', function() {
  19905. expect(firstName.getText()).toBe('Adam');
  19906. expect(lastName.getText()).toBe('John');
  19907. phoneHeader.click();
  19908. expect(firstName.getText()).toBe('John');
  19909. expect(lastName.getText()).toBe('Mary');
  19910. nameHeader.click();
  19911. expect(firstName.getText()).toBe('Adam');
  19912. expect(lastName.getText()).toBe('Mike');
  19913. ageHeader.click();
  19914. expect(firstName.getText()).toBe('John');
  19915. expect(lastName.getText()).toBe('Adam');
  19916. });
  19917. it('should sort friends in reverse order, when clicking on the same column', function() {
  19918. expect(firstName.getText()).toBe('Adam');
  19919. expect(lastName.getText()).toBe('John');
  19920. ageHeader.click();
  19921. expect(firstName.getText()).toBe('John');
  19922. expect(lastName.getText()).toBe('Adam');
  19923. ageHeader.click();
  19924. expect(firstName.getText()).toBe('Adam');
  19925. expect(lastName.getText()).toBe('John');
  19926. });
  19927. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19928. expect(firstName.getText()).toBe('Adam');
  19929. expect(lastName.getText()).toBe('John');
  19930. unsortButton.click();
  19931. expect(firstName.getText()).toBe('John');
  19932. expect(lastName.getText()).toBe('Julie');
  19933. });
  19934. </file>
  19935. </example>
  19936. * <hr />
  19937. *
  19938. * @example
  19939. * ### Using `orderBy` inside a controller
  19940. *
  19941. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  19942. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  19943. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  19944. *
  19945. <example name="orderBy-call-manually" module="orderByExample3">
  19946. <file name="index.html">
  19947. <div ng-controller="ExampleController">
  19948. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19949. <hr/>
  19950. <button ng-click="sortBy(null)">Set to unsorted</button>
  19951. <hr/>
  19952. <table class="friends">
  19953. <tr>
  19954. <th>
  19955. <button ng-click="sortBy('name')">Name</button>
  19956. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19957. </th>
  19958. <th>
  19959. <button ng-click="sortBy('phone')">Phone Number</button>
  19960. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19961. </th>
  19962. <th>
  19963. <button ng-click="sortBy('age')">Age</button>
  19964. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19965. </th>
  19966. </tr>
  19967. <tr ng-repeat="friend in friends">
  19968. <td>{{friend.name}}</td>
  19969. <td>{{friend.phone}}</td>
  19970. <td>{{friend.age}}</td>
  19971. </tr>
  19972. </table>
  19973. </div>
  19974. </file>
  19975. <file name="script.js">
  19976. angular.module('orderByExample3', [])
  19977. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  19978. var friends = [
  19979. {name: 'John', phone: '555-1212', age: 10},
  19980. {name: 'Mary', phone: '555-9876', age: 19},
  19981. {name: 'Mike', phone: '555-4321', age: 21},
  19982. {name: 'Adam', phone: '555-5678', age: 35},
  19983. {name: 'Julie', phone: '555-8765', age: 29}
  19984. ];
  19985. $scope.propertyName = 'age';
  19986. $scope.reverse = true;
  19987. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19988. $scope.sortBy = function(propertyName) {
  19989. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  19990. ? !$scope.reverse : false;
  19991. $scope.propertyName = propertyName;
  19992. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19993. };
  19994. }]);
  19995. </file>
  19996. <file name="style.css">
  19997. .friends {
  19998. border-collapse: collapse;
  19999. }
  20000. .friends th {
  20001. border-bottom: 1px solid;
  20002. }
  20003. .friends td, .friends th {
  20004. border-left: 1px solid;
  20005. padding: 5px 10px;
  20006. }
  20007. .friends td:first-child, .friends th:first-child {
  20008. border-left: none;
  20009. }
  20010. .sortorder:after {
  20011. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  20012. }
  20013. .sortorder.reverse:after {
  20014. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  20015. }
  20016. </file>
  20017. <file name="protractor.js" type="protractor">
  20018. // Element locators
  20019. var unsortButton = element(by.partialButtonText('unsorted'));
  20020. var nameHeader = element(by.partialButtonText('Name'));
  20021. var phoneHeader = element(by.partialButtonText('Phone'));
  20022. var ageHeader = element(by.partialButtonText('Age'));
  20023. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  20024. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  20025. it('should sort friends by some property, when clicking on the column header', function() {
  20026. expect(firstName.getText()).toBe('Adam');
  20027. expect(lastName.getText()).toBe('John');
  20028. phoneHeader.click();
  20029. expect(firstName.getText()).toBe('John');
  20030. expect(lastName.getText()).toBe('Mary');
  20031. nameHeader.click();
  20032. expect(firstName.getText()).toBe('Adam');
  20033. expect(lastName.getText()).toBe('Mike');
  20034. ageHeader.click();
  20035. expect(firstName.getText()).toBe('John');
  20036. expect(lastName.getText()).toBe('Adam');
  20037. });
  20038. it('should sort friends in reverse order, when clicking on the same column', function() {
  20039. expect(firstName.getText()).toBe('Adam');
  20040. expect(lastName.getText()).toBe('John');
  20041. ageHeader.click();
  20042. expect(firstName.getText()).toBe('John');
  20043. expect(lastName.getText()).toBe('Adam');
  20044. ageHeader.click();
  20045. expect(firstName.getText()).toBe('Adam');
  20046. expect(lastName.getText()).toBe('John');
  20047. });
  20048. it('should restore the original order, when clicking "Set to unsorted"', function() {
  20049. expect(firstName.getText()).toBe('Adam');
  20050. expect(lastName.getText()).toBe('John');
  20051. unsortButton.click();
  20052. expect(firstName.getText()).toBe('John');
  20053. expect(lastName.getText()).toBe('Julie');
  20054. });
  20055. </file>
  20056. </example>
  20057. * <hr />
  20058. *
  20059. * @example
  20060. * ### Using a custom comparator
  20061. *
  20062. * If you have very specific requirements about the way items are sorted, you can pass your own
  20063. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  20064. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  20065. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  20066. *
  20067. <example name="orderBy-custom-comparator" module="orderByExample4">
  20068. <file name="index.html">
  20069. <div ng-controller="ExampleController">
  20070. <div class="friends-container custom-comparator">
  20071. <h3>Locale-sensitive Comparator</h3>
  20072. <table class="friends">
  20073. <tr>
  20074. <th>Name</th>
  20075. <th>Favorite Letter</th>
  20076. </tr>
  20077. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  20078. <td>{{friend.name}}</td>
  20079. <td>{{friend.favoriteLetter}}</td>
  20080. </tr>
  20081. </table>
  20082. </div>
  20083. <div class="friends-container default-comparator">
  20084. <h3>Default Comparator</h3>
  20085. <table class="friends">
  20086. <tr>
  20087. <th>Name</th>
  20088. <th>Favorite Letter</th>
  20089. </tr>
  20090. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  20091. <td>{{friend.name}}</td>
  20092. <td>{{friend.favoriteLetter}}</td>
  20093. </tr>
  20094. </table>
  20095. </div>
  20096. </div>
  20097. </file>
  20098. <file name="script.js">
  20099. angular.module('orderByExample4', [])
  20100. .controller('ExampleController', ['$scope', function($scope) {
  20101. $scope.friends = [
  20102. {name: 'John', favoriteLetter: 'Ä'},
  20103. {name: 'Mary', favoriteLetter: 'Ü'},
  20104. {name: 'Mike', favoriteLetter: 'Ö'},
  20105. {name: 'Adam', favoriteLetter: 'H'},
  20106. {name: 'Julie', favoriteLetter: 'Z'}
  20107. ];
  20108. $scope.localeSensitiveComparator = function(v1, v2) {
  20109. // If we don't get strings, just compare by index
  20110. if (v1.type !== 'string' || v2.type !== 'string') {
  20111. return (v1.index < v2.index) ? -1 : 1;
  20112. }
  20113. // Compare strings alphabetically, taking locale into account
  20114. return v1.value.localeCompare(v2.value);
  20115. };
  20116. }]);
  20117. </file>
  20118. <file name="style.css">
  20119. .friends-container {
  20120. display: inline-block;
  20121. margin: 0 30px;
  20122. }
  20123. .friends {
  20124. border-collapse: collapse;
  20125. }
  20126. .friends th {
  20127. border-bottom: 1px solid;
  20128. }
  20129. .friends td, .friends th {
  20130. border-left: 1px solid;
  20131. padding: 5px 10px;
  20132. }
  20133. .friends td:first-child, .friends th:first-child {
  20134. border-left: none;
  20135. }
  20136. </file>
  20137. <file name="protractor.js" type="protractor">
  20138. // Element locators
  20139. var container = element(by.css('.custom-comparator'));
  20140. var names = container.all(by.repeater('friends').column('friend.name'));
  20141. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  20142. expect(names.get(0).getText()).toBe('John');
  20143. expect(names.get(1).getText()).toBe('Adam');
  20144. expect(names.get(2).getText()).toBe('Mike');
  20145. expect(names.get(3).getText()).toBe('Mary');
  20146. expect(names.get(4).getText()).toBe('Julie');
  20147. });
  20148. </file>
  20149. </example>
  20150. *
  20151. */
  20152. orderByFilter.$inject = ['$parse'];
  20153. function orderByFilter($parse) {
  20154. return function(array, sortPredicate, reverseOrder, compareFn) {
  20155. if (array == null) return array;
  20156. if (!isArrayLike(array)) {
  20157. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  20158. }
  20159. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  20160. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  20161. var predicates = processPredicates(sortPredicate);
  20162. var descending = reverseOrder ? -1 : 1;
  20163. // Define the `compare()` function. Use a default comparator if none is specified.
  20164. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  20165. // The next three lines are a version of a Swartzian Transform idiom from Perl
  20166. // (sometimes called the Decorate-Sort-Undecorate idiom)
  20167. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  20168. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  20169. compareValues.sort(doComparison);
  20170. array = compareValues.map(function(item) { return item.value; });
  20171. return array;
  20172. function getComparisonObject(value, index) {
  20173. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  20174. // This will be used to keep the sort stable when none of the input predicates can
  20175. // distinguish between two elements.
  20176. return {
  20177. value: value,
  20178. tieBreaker: {value: index, type: 'number', index: index},
  20179. predicateValues: predicates.map(function(predicate) {
  20180. return getPredicateValue(predicate.get(value), index);
  20181. })
  20182. };
  20183. }
  20184. function doComparison(v1, v2) {
  20185. for (var i = 0, ii = predicates.length; i < ii; i++) {
  20186. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  20187. if (result) {
  20188. return result * predicates[i].descending * descending;
  20189. }
  20190. }
  20191. return compare(v1.tieBreaker, v2.tieBreaker) * descending;
  20192. }
  20193. };
  20194. function processPredicates(sortPredicates) {
  20195. return sortPredicates.map(function(predicate) {
  20196. var descending = 1, get = identity;
  20197. if (isFunction(predicate)) {
  20198. get = predicate;
  20199. } else if (isString(predicate)) {
  20200. if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
  20201. descending = predicate.charAt(0) === '-' ? -1 : 1;
  20202. predicate = predicate.substring(1);
  20203. }
  20204. if (predicate !== '') {
  20205. get = $parse(predicate);
  20206. if (get.constant) {
  20207. var key = get();
  20208. get = function(value) { return value[key]; };
  20209. }
  20210. }
  20211. }
  20212. return {get: get, descending: descending};
  20213. });
  20214. }
  20215. function isPrimitive(value) {
  20216. switch (typeof value) {
  20217. case 'number': /* falls through */
  20218. case 'boolean': /* falls through */
  20219. case 'string':
  20220. return true;
  20221. default:
  20222. return false;
  20223. }
  20224. }
  20225. function objectValue(value) {
  20226. // If `valueOf` is a valid function use that
  20227. if (isFunction(value.valueOf)) {
  20228. value = value.valueOf();
  20229. if (isPrimitive(value)) return value;
  20230. }
  20231. // If `toString` is a valid function and not the one from `Object.prototype` use that
  20232. if (hasCustomToString(value)) {
  20233. value = value.toString();
  20234. if (isPrimitive(value)) return value;
  20235. }
  20236. return value;
  20237. }
  20238. function getPredicateValue(value, index) {
  20239. var type = typeof value;
  20240. if (value === null) {
  20241. type = 'string';
  20242. value = 'null';
  20243. } else if (type === 'object') {
  20244. value = objectValue(value);
  20245. }
  20246. return {value: value, type: type, index: index};
  20247. }
  20248. function defaultCompare(v1, v2) {
  20249. var result = 0;
  20250. var type1 = v1.type;
  20251. var type2 = v2.type;
  20252. if (type1 === type2) {
  20253. var value1 = v1.value;
  20254. var value2 = v2.value;
  20255. if (type1 === 'string') {
  20256. // Compare strings case-insensitively
  20257. value1 = value1.toLowerCase();
  20258. value2 = value2.toLowerCase();
  20259. } else if (type1 === 'object') {
  20260. // For basic objects, use the position of the object
  20261. // in the collection instead of the value
  20262. if (isObject(value1)) value1 = v1.index;
  20263. if (isObject(value2)) value2 = v2.index;
  20264. }
  20265. if (value1 !== value2) {
  20266. result = value1 < value2 ? -1 : 1;
  20267. }
  20268. } else {
  20269. result = type1 < type2 ? -1 : 1;
  20270. }
  20271. return result;
  20272. }
  20273. }
  20274. function ngDirective(directive) {
  20275. if (isFunction(directive)) {
  20276. directive = {
  20277. link: directive
  20278. };
  20279. }
  20280. directive.restrict = directive.restrict || 'AC';
  20281. return valueFn(directive);
  20282. }
  20283. /**
  20284. * @ngdoc directive
  20285. * @name a
  20286. * @restrict E
  20287. *
  20288. * @description
  20289. * Modifies the default behavior of the html a tag so that the default action is prevented when
  20290. * the href attribute is empty.
  20291. *
  20292. * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
  20293. */
  20294. var htmlAnchorDirective = valueFn({
  20295. restrict: 'E',
  20296. compile: function(element, attr) {
  20297. if (!attr.href && !attr.xlinkHref) {
  20298. return function(scope, element) {
  20299. // If the linked element is not an anchor tag anymore, do nothing
  20300. if (element[0].nodeName.toLowerCase() !== 'a') return;
  20301. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  20302. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  20303. 'xlink:href' : 'href';
  20304. element.on('click', function(event) {
  20305. // if we have no href url, then don't navigate anywhere.
  20306. if (!element.attr(href)) {
  20307. event.preventDefault();
  20308. }
  20309. });
  20310. };
  20311. }
  20312. }
  20313. });
  20314. /**
  20315. * @ngdoc directive
  20316. * @name ngHref
  20317. * @restrict A
  20318. * @priority 99
  20319. *
  20320. * @description
  20321. * Using Angular markup like `{{hash}}` in an href attribute will
  20322. * make the link go to the wrong URL if the user clicks it before
  20323. * Angular has a chance to replace the `{{hash}}` markup with its
  20324. * value. Until Angular replaces the markup the link will be broken
  20325. * and will most likely return a 404 error. The `ngHref` directive
  20326. * solves this problem.
  20327. *
  20328. * The wrong way to write it:
  20329. * ```html
  20330. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20331. * ```
  20332. *
  20333. * The correct way to write it:
  20334. * ```html
  20335. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20336. * ```
  20337. *
  20338. * @element A
  20339. * @param {template} ngHref any string which can contain `{{}}` markup.
  20340. *
  20341. * @example
  20342. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  20343. * in links and their different behaviors:
  20344. <example name="ng-href">
  20345. <file name="index.html">
  20346. <input ng-model="value" /><br />
  20347. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  20348. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  20349. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  20350. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  20351. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  20352. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  20353. </file>
  20354. <file name="protractor.js" type="protractor">
  20355. it('should execute ng-click but not reload when href without value', function() {
  20356. element(by.id('link-1')).click();
  20357. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  20358. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  20359. });
  20360. it('should execute ng-click but not reload when href empty string', function() {
  20361. element(by.id('link-2')).click();
  20362. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  20363. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  20364. });
  20365. it('should execute ng-click and change url when ng-href specified', function() {
  20366. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  20367. element(by.id('link-3')).click();
  20368. // At this point, we navigate away from an Angular page, so we need
  20369. // to use browser.driver to get the base webdriver.
  20370. browser.wait(function() {
  20371. return browser.driver.getCurrentUrl().then(function(url) {
  20372. return url.match(/\/123$/);
  20373. });
  20374. }, 5000, 'page should navigate to /123');
  20375. });
  20376. it('should execute ng-click but not reload when href empty string and name specified', function() {
  20377. element(by.id('link-4')).click();
  20378. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  20379. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  20380. });
  20381. it('should execute ng-click but not reload when no href but name specified', function() {
  20382. element(by.id('link-5')).click();
  20383. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  20384. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  20385. });
  20386. it('should only change url when only ng-href', function() {
  20387. element(by.model('value')).clear();
  20388. element(by.model('value')).sendKeys('6');
  20389. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  20390. element(by.id('link-6')).click();
  20391. // At this point, we navigate away from an Angular page, so we need
  20392. // to use browser.driver to get the base webdriver.
  20393. browser.wait(function() {
  20394. return browser.driver.getCurrentUrl().then(function(url) {
  20395. return url.match(/\/6$/);
  20396. });
  20397. }, 5000, 'page should navigate to /6');
  20398. });
  20399. </file>
  20400. </example>
  20401. */
  20402. /**
  20403. * @ngdoc directive
  20404. * @name ngSrc
  20405. * @restrict A
  20406. * @priority 99
  20407. *
  20408. * @description
  20409. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  20410. * work right: The browser will fetch from the URL with the literal
  20411. * text `{{hash}}` until Angular replaces the expression inside
  20412. * `{{hash}}`. The `ngSrc` directive solves this problem.
  20413. *
  20414. * The buggy way to write it:
  20415. * ```html
  20416. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  20417. * ```
  20418. *
  20419. * The correct way to write it:
  20420. * ```html
  20421. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  20422. * ```
  20423. *
  20424. * @element IMG
  20425. * @param {template} ngSrc any string which can contain `{{}}` markup.
  20426. */
  20427. /**
  20428. * @ngdoc directive
  20429. * @name ngSrcset
  20430. * @restrict A
  20431. * @priority 99
  20432. *
  20433. * @description
  20434. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  20435. * work right: The browser will fetch from the URL with the literal
  20436. * text `{{hash}}` until Angular replaces the expression inside
  20437. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  20438. *
  20439. * The buggy way to write it:
  20440. * ```html
  20441. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  20442. * ```
  20443. *
  20444. * The correct way to write it:
  20445. * ```html
  20446. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  20447. * ```
  20448. *
  20449. * @element IMG
  20450. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  20451. */
  20452. /**
  20453. * @ngdoc directive
  20454. * @name ngDisabled
  20455. * @restrict A
  20456. * @priority 100
  20457. *
  20458. * @description
  20459. *
  20460. * This directive sets the `disabled` attribute on the element (typically a form control,
  20461. * e.g. `input`, `button`, `select` etc.) if the
  20462. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  20463. *
  20464. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  20465. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20466. *
  20467. * @example
  20468. <example name="ng-disabled">
  20469. <file name="index.html">
  20470. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  20471. <button ng-model="button" ng-disabled="checked">Button</button>
  20472. </file>
  20473. <file name="protractor.js" type="protractor">
  20474. it('should toggle button', function() {
  20475. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  20476. element(by.model('checked')).click();
  20477. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  20478. });
  20479. </file>
  20480. </example>
  20481. *
  20482. * @element INPUT
  20483. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  20484. * then the `disabled` attribute will be set on the element
  20485. */
  20486. /**
  20487. * @ngdoc directive
  20488. * @name ngChecked
  20489. * @restrict A
  20490. * @priority 100
  20491. *
  20492. * @description
  20493. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  20494. *
  20495. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  20496. * as this can lead to unexpected behavior.
  20497. *
  20498. * A special directive is necessary because we cannot use interpolation inside the `checked`
  20499. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20500. *
  20501. * @example
  20502. <example name="ng-checked">
  20503. <file name="index.html">
  20504. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  20505. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  20506. </file>
  20507. <file name="protractor.js" type="protractor">
  20508. it('should check both checkBoxes', function() {
  20509. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  20510. element(by.model('master')).click();
  20511. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  20512. });
  20513. </file>
  20514. </example>
  20515. *
  20516. * @element INPUT
  20517. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  20518. * then the `checked` attribute will be set on the element
  20519. */
  20520. /**
  20521. * @ngdoc directive
  20522. * @name ngReadonly
  20523. * @restrict A
  20524. * @priority 100
  20525. *
  20526. * @description
  20527. *
  20528. * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  20529. * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
  20530. * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
  20531. *
  20532. * A special directive is necessary because we cannot use interpolation inside the `readonly`
  20533. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20534. *
  20535. * @example
  20536. <example name="ng-readonly">
  20537. <file name="index.html">
  20538. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  20539. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  20540. </file>
  20541. <file name="protractor.js" type="protractor">
  20542. it('should toggle readonly attr', function() {
  20543. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  20544. element(by.model('checked')).click();
  20545. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  20546. });
  20547. </file>
  20548. </example>
  20549. *
  20550. * @element INPUT
  20551. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  20552. * then special attribute "readonly" will be set on the element
  20553. */
  20554. /**
  20555. * @ngdoc directive
  20556. * @name ngSelected
  20557. * @restrict A
  20558. * @priority 100
  20559. *
  20560. * @description
  20561. *
  20562. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  20563. *
  20564. * A special directive is necessary because we cannot use interpolation inside the `selected`
  20565. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20566. *
  20567. * <div class="alert alert-warning">
  20568. * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
  20569. * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
  20570. * should not use `ngSelected` on the options, as `ngModel` will set the select value and
  20571. * selected options.
  20572. * </div>
  20573. *
  20574. * @example
  20575. <example name="ng-selected">
  20576. <file name="index.html">
  20577. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  20578. <select aria-label="ngSelected demo">
  20579. <option>Hello!</option>
  20580. <option id="greet" ng-selected="selected">Greetings!</option>
  20581. </select>
  20582. </file>
  20583. <file name="protractor.js" type="protractor">
  20584. it('should select Greetings!', function() {
  20585. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  20586. element(by.model('selected')).click();
  20587. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  20588. });
  20589. </file>
  20590. </example>
  20591. *
  20592. * @element OPTION
  20593. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  20594. * then special attribute "selected" will be set on the element
  20595. */
  20596. /**
  20597. * @ngdoc directive
  20598. * @name ngOpen
  20599. * @restrict A
  20600. * @priority 100
  20601. *
  20602. * @description
  20603. *
  20604. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  20605. *
  20606. * A special directive is necessary because we cannot use interpolation inside the `open`
  20607. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20608. *
  20609. * ## A note about browser compatibility
  20610. *
  20611. * Edge, Firefox, and Internet Explorer do not support the `details` element, it is
  20612. * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
  20613. *
  20614. * @example
  20615. <example name="ng-open">
  20616. <file name="index.html">
  20617. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  20618. <details id="details" ng-open="open">
  20619. <summary>Show/Hide me</summary>
  20620. </details>
  20621. </file>
  20622. <file name="protractor.js" type="protractor">
  20623. it('should toggle open', function() {
  20624. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  20625. element(by.model('open')).click();
  20626. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  20627. });
  20628. </file>
  20629. </example>
  20630. *
  20631. * @element DETAILS
  20632. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  20633. * then special attribute "open" will be set on the element
  20634. */
  20635. var ngAttributeAliasDirectives = {};
  20636. // boolean attrs are evaluated
  20637. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  20638. // binding to multiple is not supported
  20639. if (propName === 'multiple') return;
  20640. function defaultLinkFn(scope, element, attr) {
  20641. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  20642. attr.$set(attrName, !!value);
  20643. });
  20644. }
  20645. var normalized = directiveNormalize('ng-' + attrName);
  20646. var linkFn = defaultLinkFn;
  20647. if (propName === 'checked') {
  20648. linkFn = function(scope, element, attr) {
  20649. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  20650. if (attr.ngModel !== attr[normalized]) {
  20651. defaultLinkFn(scope, element, attr);
  20652. }
  20653. };
  20654. }
  20655. ngAttributeAliasDirectives[normalized] = function() {
  20656. return {
  20657. restrict: 'A',
  20658. priority: 100,
  20659. link: linkFn
  20660. };
  20661. };
  20662. });
  20663. // aliased input attrs are evaluated
  20664. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  20665. ngAttributeAliasDirectives[ngAttr] = function() {
  20666. return {
  20667. priority: 100,
  20668. link: function(scope, element, attr) {
  20669. //special case ngPattern when a literal regular expression value
  20670. //is used as the expression (this way we don't have to watch anything).
  20671. if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
  20672. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  20673. if (match) {
  20674. attr.$set('ngPattern', new RegExp(match[1], match[2]));
  20675. return;
  20676. }
  20677. }
  20678. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  20679. attr.$set(ngAttr, value);
  20680. });
  20681. }
  20682. };
  20683. };
  20684. });
  20685. // ng-src, ng-srcset, ng-href are interpolated
  20686. forEach(['src', 'srcset', 'href'], function(attrName) {
  20687. var normalized = directiveNormalize('ng-' + attrName);
  20688. ngAttributeAliasDirectives[normalized] = function() {
  20689. return {
  20690. priority: 99, // it needs to run after the attributes are interpolated
  20691. link: function(scope, element, attr) {
  20692. var propName = attrName,
  20693. name = attrName;
  20694. if (attrName === 'href' &&
  20695. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  20696. name = 'xlinkHref';
  20697. attr.$attr[name] = 'xlink:href';
  20698. propName = null;
  20699. }
  20700. attr.$observe(normalized, function(value) {
  20701. if (!value) {
  20702. if (attrName === 'href') {
  20703. attr.$set(name, null);
  20704. }
  20705. return;
  20706. }
  20707. attr.$set(name, value);
  20708. // Support: IE 9-11 only
  20709. // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  20710. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  20711. // to set the property as well to achieve the desired effect.
  20712. // We use attr[attrName] value since $set can sanitize the url.
  20713. if (msie && propName) element.prop(propName, attr[name]);
  20714. });
  20715. }
  20716. };
  20717. };
  20718. });
  20719. /* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS
  20720. */
  20721. var nullFormCtrl = {
  20722. $addControl: noop,
  20723. $$renameControl: nullFormRenameControl,
  20724. $removeControl: noop,
  20725. $setValidity: noop,
  20726. $setDirty: noop,
  20727. $setPristine: noop,
  20728. $setSubmitted: noop
  20729. },
  20730. PENDING_CLASS = 'ng-pending',
  20731. SUBMITTED_CLASS = 'ng-submitted';
  20732. function nullFormRenameControl(control, name) {
  20733. control.$name = name;
  20734. }
  20735. /**
  20736. * @ngdoc type
  20737. * @name form.FormController
  20738. *
  20739. * @property {boolean} $pristine True if user has not interacted with the form yet.
  20740. * @property {boolean} $dirty True if user has already interacted with the form.
  20741. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  20742. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  20743. * @property {boolean} $pending True if at least one containing control or form is pending.
  20744. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  20745. *
  20746. * @property {Object} $error Is an object hash, containing references to controls or
  20747. * forms with failing validators, where:
  20748. *
  20749. * - keys are validation tokens (error names),
  20750. * - values are arrays of controls or forms that have a failing validator for given error name.
  20751. *
  20752. * Built-in validation tokens:
  20753. *
  20754. * - `email`
  20755. * - `max`
  20756. * - `maxlength`
  20757. * - `min`
  20758. * - `minlength`
  20759. * - `number`
  20760. * - `pattern`
  20761. * - `required`
  20762. * - `url`
  20763. * - `date`
  20764. * - `datetimelocal`
  20765. * - `time`
  20766. * - `week`
  20767. * - `month`
  20768. *
  20769. * @description
  20770. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  20771. * such as being valid/invalid or dirty/pristine.
  20772. *
  20773. * Each {@link ng.directive:form form} directive creates an instance
  20774. * of `FormController`.
  20775. *
  20776. */
  20777. //asks for $scope to fool the BC controller module
  20778. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  20779. function FormController($element, $attrs, $scope, $animate, $interpolate) {
  20780. this.$$controls = [];
  20781. // init state
  20782. this.$error = {};
  20783. this.$$success = {};
  20784. this.$pending = undefined;
  20785. this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);
  20786. this.$dirty = false;
  20787. this.$pristine = true;
  20788. this.$valid = true;
  20789. this.$invalid = false;
  20790. this.$submitted = false;
  20791. this.$$parentForm = nullFormCtrl;
  20792. this.$$element = $element;
  20793. this.$$animate = $animate;
  20794. setupValidity(this);
  20795. }
  20796. FormController.prototype = {
  20797. /**
  20798. * @ngdoc method
  20799. * @name form.FormController#$rollbackViewValue
  20800. *
  20801. * @description
  20802. * Rollback all form controls pending updates to the `$modelValue`.
  20803. *
  20804. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20805. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  20806. * a form that uses `ng-model-options` to pend updates.
  20807. */
  20808. $rollbackViewValue: function() {
  20809. forEach(this.$$controls, function(control) {
  20810. control.$rollbackViewValue();
  20811. });
  20812. },
  20813. /**
  20814. * @ngdoc method
  20815. * @name form.FormController#$commitViewValue
  20816. *
  20817. * @description
  20818. * Commit all form controls pending updates to the `$modelValue`.
  20819. *
  20820. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20821. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  20822. * usually handles calling this in response to input events.
  20823. */
  20824. $commitViewValue: function() {
  20825. forEach(this.$$controls, function(control) {
  20826. control.$commitViewValue();
  20827. });
  20828. },
  20829. /**
  20830. * @ngdoc method
  20831. * @name form.FormController#$addControl
  20832. * @param {object} control control object, either a {@link form.FormController} or an
  20833. * {@link ngModel.NgModelController}
  20834. *
  20835. * @description
  20836. * Register a control with the form. Input elements using ngModelController do this automatically
  20837. * when they are linked.
  20838. *
  20839. * Note that the current state of the control will not be reflected on the new parent form. This
  20840. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  20841. * state.
  20842. *
  20843. * However, if the method is used programmatically, for example by adding dynamically created controls,
  20844. * or controls that have been previously removed without destroying their corresponding DOM element,
  20845. * it's the developers responsibility to make sure the current state propagates to the parent form.
  20846. *
  20847. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  20848. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  20849. */
  20850. $addControl: function(control) {
  20851. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  20852. // and not added to the scope. Now we throw an error.
  20853. assertNotHasOwnProperty(control.$name, 'input');
  20854. this.$$controls.push(control);
  20855. if (control.$name) {
  20856. this[control.$name] = control;
  20857. }
  20858. control.$$parentForm = this;
  20859. },
  20860. // Private API: rename a form control
  20861. $$renameControl: function(control, newName) {
  20862. var oldName = control.$name;
  20863. if (this[oldName] === control) {
  20864. delete this[oldName];
  20865. }
  20866. this[newName] = control;
  20867. control.$name = newName;
  20868. },
  20869. /**
  20870. * @ngdoc method
  20871. * @name form.FormController#$removeControl
  20872. * @param {object} control control object, either a {@link form.FormController} or an
  20873. * {@link ngModel.NgModelController}
  20874. *
  20875. * @description
  20876. * Deregister a control from the form.
  20877. *
  20878. * Input elements using ngModelController do this automatically when they are destroyed.
  20879. *
  20880. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  20881. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  20882. * different from case to case. For example, removing the only `$dirty` control from a form may or
  20883. * may not mean that the form is still `$dirty`.
  20884. */
  20885. $removeControl: function(control) {
  20886. if (control.$name && this[control.$name] === control) {
  20887. delete this[control.$name];
  20888. }
  20889. forEach(this.$pending, function(value, name) {
  20890. // eslint-disable-next-line no-invalid-this
  20891. this.$setValidity(name, null, control);
  20892. }, this);
  20893. forEach(this.$error, function(value, name) {
  20894. // eslint-disable-next-line no-invalid-this
  20895. this.$setValidity(name, null, control);
  20896. }, this);
  20897. forEach(this.$$success, function(value, name) {
  20898. // eslint-disable-next-line no-invalid-this
  20899. this.$setValidity(name, null, control);
  20900. }, this);
  20901. arrayRemove(this.$$controls, control);
  20902. control.$$parentForm = nullFormCtrl;
  20903. },
  20904. /**
  20905. * @ngdoc method
  20906. * @name form.FormController#$setDirty
  20907. *
  20908. * @description
  20909. * Sets the form to a dirty state.
  20910. *
  20911. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  20912. * state (ng-dirty class). This method will also propagate to parent forms.
  20913. */
  20914. $setDirty: function() {
  20915. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  20916. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  20917. this.$dirty = true;
  20918. this.$pristine = false;
  20919. this.$$parentForm.$setDirty();
  20920. },
  20921. /**
  20922. * @ngdoc method
  20923. * @name form.FormController#$setPristine
  20924. *
  20925. * @description
  20926. * Sets the form to its pristine state.
  20927. *
  20928. * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
  20929. * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
  20930. * state to false.
  20931. *
  20932. * This method will also propagate to all the controls contained in this form.
  20933. *
  20934. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  20935. * saving or resetting it.
  20936. */
  20937. $setPristine: function() {
  20938. this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  20939. this.$dirty = false;
  20940. this.$pristine = true;
  20941. this.$submitted = false;
  20942. forEach(this.$$controls, function(control) {
  20943. control.$setPristine();
  20944. });
  20945. },
  20946. /**
  20947. * @ngdoc method
  20948. * @name form.FormController#$setUntouched
  20949. *
  20950. * @description
  20951. * Sets the form to its untouched state.
  20952. *
  20953. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  20954. * untouched state (ng-untouched class).
  20955. *
  20956. * Setting a form controls back to their untouched state is often useful when setting the form
  20957. * back to its pristine state.
  20958. */
  20959. $setUntouched: function() {
  20960. forEach(this.$$controls, function(control) {
  20961. control.$setUntouched();
  20962. });
  20963. },
  20964. /**
  20965. * @ngdoc method
  20966. * @name form.FormController#$setSubmitted
  20967. *
  20968. * @description
  20969. * Sets the form to its submitted state.
  20970. */
  20971. $setSubmitted: function() {
  20972. this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);
  20973. this.$submitted = true;
  20974. this.$$parentForm.$setSubmitted();
  20975. }
  20976. };
  20977. /**
  20978. * @ngdoc method
  20979. * @name form.FormController#$setValidity
  20980. *
  20981. * @description
  20982. * Sets the validity of a form control.
  20983. *
  20984. * This method will also propagate to parent forms.
  20985. */
  20986. addSetValidityMethod({
  20987. clazz: FormController,
  20988. set: function(object, property, controller) {
  20989. var list = object[property];
  20990. if (!list) {
  20991. object[property] = [controller];
  20992. } else {
  20993. var index = list.indexOf(controller);
  20994. if (index === -1) {
  20995. list.push(controller);
  20996. }
  20997. }
  20998. },
  20999. unset: function(object, property, controller) {
  21000. var list = object[property];
  21001. if (!list) {
  21002. return;
  21003. }
  21004. arrayRemove(list, controller);
  21005. if (list.length === 0) {
  21006. delete object[property];
  21007. }
  21008. }
  21009. });
  21010. /**
  21011. * @ngdoc directive
  21012. * @name ngForm
  21013. * @restrict EAC
  21014. *
  21015. * @description
  21016. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  21017. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  21018. * sub-group of controls needs to be determined.
  21019. *
  21020. * Note: the purpose of `ngForm` is to group controls,
  21021. * but not to be a replacement for the `<form>` tag with all of its capabilities
  21022. * (e.g. posting to the server, ...).
  21023. *
  21024. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  21025. * related scope, under this name.
  21026. *
  21027. */
  21028. /**
  21029. * @ngdoc directive
  21030. * @name form
  21031. * @restrict E
  21032. *
  21033. * @description
  21034. * Directive that instantiates
  21035. * {@link form.FormController FormController}.
  21036. *
  21037. * If the `name` attribute is specified, the form controller is published onto the current scope under
  21038. * this name.
  21039. *
  21040. * # Alias: {@link ng.directive:ngForm `ngForm`}
  21041. *
  21042. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  21043. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  21044. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  21045. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  21046. * of controls needs to be determined.
  21047. *
  21048. * # CSS classes
  21049. * - `ng-valid` is set if the form is valid.
  21050. * - `ng-invalid` is set if the form is invalid.
  21051. * - `ng-pending` is set if the form is pending.
  21052. * - `ng-pristine` is set if the form is pristine.
  21053. * - `ng-dirty` is set if the form is dirty.
  21054. * - `ng-submitted` is set if the form was submitted.
  21055. *
  21056. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  21057. *
  21058. *
  21059. * # Submitting a form and preventing the default action
  21060. *
  21061. * Since the role of forms in client-side Angular applications is different than in classical
  21062. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  21063. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  21064. * to handle the form submission in an application-specific way.
  21065. *
  21066. * For this reason, Angular prevents the default action (form submission to the server) unless the
  21067. * `<form>` element has an `action` attribute specified.
  21068. *
  21069. * You can use one of the following two ways to specify what javascript method should be called when
  21070. * a form is submitted:
  21071. *
  21072. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  21073. * - {@link ng.directive:ngClick ngClick} directive on the first
  21074. * button or input field of type submit (input[type=submit])
  21075. *
  21076. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  21077. * or {@link ng.directive:ngClick ngClick} directives.
  21078. * This is because of the following form submission rules in the HTML specification:
  21079. *
  21080. * - If a form has only one input field then hitting enter in this field triggers form submit
  21081. * (`ngSubmit`)
  21082. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  21083. * doesn't trigger submit
  21084. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  21085. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  21086. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  21087. *
  21088. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  21089. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  21090. * to have access to the updated model.
  21091. *
  21092. * ## Animation Hooks
  21093. *
  21094. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  21095. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  21096. * other validations that are performed within the form. Animations in ngForm are similar to how
  21097. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  21098. * as JS animations.
  21099. *
  21100. * The following example shows a simple way to utilize CSS transitions to style a form element
  21101. * that has been rendered as invalid after it has been validated:
  21102. *
  21103. * <pre>
  21104. * //be sure to include ngAnimate as a module to hook into more
  21105. * //advanced animations
  21106. * .my-form {
  21107. * transition:0.5s linear all;
  21108. * background: white;
  21109. * }
  21110. * .my-form.ng-invalid {
  21111. * background: red;
  21112. * color:white;
  21113. * }
  21114. * </pre>
  21115. *
  21116. * @example
  21117. <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  21118. <file name="index.html">
  21119. <script>
  21120. angular.module('formExample', [])
  21121. .controller('FormController', ['$scope', function($scope) {
  21122. $scope.userType = 'guest';
  21123. }]);
  21124. </script>
  21125. <style>
  21126. .my-form {
  21127. transition:all linear 0.5s;
  21128. background: transparent;
  21129. }
  21130. .my-form.ng-invalid {
  21131. background: red;
  21132. }
  21133. </style>
  21134. <form name="myForm" ng-controller="FormController" class="my-form">
  21135. userType: <input name="input" ng-model="userType" required>
  21136. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  21137. <code>userType = {{userType}}</code><br>
  21138. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  21139. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  21140. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  21141. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  21142. </form>
  21143. </file>
  21144. <file name="protractor.js" type="protractor">
  21145. it('should initialize to model', function() {
  21146. var userType = element(by.binding('userType'));
  21147. var valid = element(by.binding('myForm.input.$valid'));
  21148. expect(userType.getText()).toContain('guest');
  21149. expect(valid.getText()).toContain('true');
  21150. });
  21151. it('should be invalid if empty', function() {
  21152. var userType = element(by.binding('userType'));
  21153. var valid = element(by.binding('myForm.input.$valid'));
  21154. var userInput = element(by.model('userType'));
  21155. userInput.clear();
  21156. userInput.sendKeys('');
  21157. expect(userType.getText()).toEqual('userType =');
  21158. expect(valid.getText()).toContain('false');
  21159. });
  21160. </file>
  21161. </example>
  21162. *
  21163. * @param {string=} name Name of the form. If specified, the form controller will be published into
  21164. * related scope, under this name.
  21165. */
  21166. var formDirectiveFactory = function(isNgForm) {
  21167. return ['$timeout', '$parse', function($timeout, $parse) {
  21168. var formDirective = {
  21169. name: 'form',
  21170. restrict: isNgForm ? 'EAC' : 'E',
  21171. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  21172. controller: FormController,
  21173. compile: function ngFormCompile(formElement, attr) {
  21174. // Setup initial state of the control
  21175. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  21176. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  21177. return {
  21178. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  21179. var controller = ctrls[0];
  21180. // if `action` attr is not present on the form, prevent the default action (submission)
  21181. if (!('action' in attr)) {
  21182. // we can't use jq events because if a form is destroyed during submission the default
  21183. // action is not prevented. see #1238
  21184. //
  21185. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  21186. // page reload if the form was destroyed by submission of the form via a click handler
  21187. // on a button in the form. Looks like an IE9 specific bug.
  21188. var handleFormSubmission = function(event) {
  21189. scope.$apply(function() {
  21190. controller.$commitViewValue();
  21191. controller.$setSubmitted();
  21192. });
  21193. event.preventDefault();
  21194. };
  21195. formElement[0].addEventListener('submit', handleFormSubmission);
  21196. // unregister the preventDefault listener so that we don't not leak memory but in a
  21197. // way that will achieve the prevention of the default action.
  21198. formElement.on('$destroy', function() {
  21199. $timeout(function() {
  21200. formElement[0].removeEventListener('submit', handleFormSubmission);
  21201. }, 0, false);
  21202. });
  21203. }
  21204. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  21205. parentFormCtrl.$addControl(controller);
  21206. var setter = nameAttr ? getSetter(controller.$name) : noop;
  21207. if (nameAttr) {
  21208. setter(scope, controller);
  21209. attr.$observe(nameAttr, function(newValue) {
  21210. if (controller.$name === newValue) return;
  21211. setter(scope, undefined);
  21212. controller.$$parentForm.$$renameControl(controller, newValue);
  21213. setter = getSetter(controller.$name);
  21214. setter(scope, controller);
  21215. });
  21216. }
  21217. formElement.on('$destroy', function() {
  21218. controller.$$parentForm.$removeControl(controller);
  21219. setter(scope, undefined);
  21220. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  21221. });
  21222. }
  21223. };
  21224. }
  21225. };
  21226. return formDirective;
  21227. function getSetter(expression) {
  21228. if (expression === '') {
  21229. //create an assignable expression, so forms with an empty name can be renamed later
  21230. return $parse('this[""]').assign;
  21231. }
  21232. return $parse(expression).assign || noop;
  21233. }
  21234. }];
  21235. };
  21236. var formDirective = formDirectiveFactory();
  21237. var ngFormDirective = formDirectiveFactory(true);
  21238. // helper methods
  21239. function setupValidity(instance) {
  21240. instance.$$classCache = {};
  21241. instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));
  21242. }
  21243. function addSetValidityMethod(context) {
  21244. var clazz = context.clazz,
  21245. set = context.set,
  21246. unset = context.unset;
  21247. clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {
  21248. if (isUndefined(state)) {
  21249. createAndSet(this, '$pending', validationErrorKey, controller);
  21250. } else {
  21251. unsetAndCleanup(this, '$pending', validationErrorKey, controller);
  21252. }
  21253. if (!isBoolean(state)) {
  21254. unset(this.$error, validationErrorKey, controller);
  21255. unset(this.$$success, validationErrorKey, controller);
  21256. } else {
  21257. if (state) {
  21258. unset(this.$error, validationErrorKey, controller);
  21259. set(this.$$success, validationErrorKey, controller);
  21260. } else {
  21261. set(this.$error, validationErrorKey, controller);
  21262. unset(this.$$success, validationErrorKey, controller);
  21263. }
  21264. }
  21265. if (this.$pending) {
  21266. cachedToggleClass(this, PENDING_CLASS, true);
  21267. this.$valid = this.$invalid = undefined;
  21268. toggleValidationCss(this, '', null);
  21269. } else {
  21270. cachedToggleClass(this, PENDING_CLASS, false);
  21271. this.$valid = isObjectEmpty(this.$error);
  21272. this.$invalid = !this.$valid;
  21273. toggleValidationCss(this, '', this.$valid);
  21274. }
  21275. // re-read the state as the set/unset methods could have
  21276. // combined state in this.$error[validationError] (used for forms),
  21277. // where setting/unsetting only increments/decrements the value,
  21278. // and does not replace it.
  21279. var combinedState;
  21280. if (this.$pending && this.$pending[validationErrorKey]) {
  21281. combinedState = undefined;
  21282. } else if (this.$error[validationErrorKey]) {
  21283. combinedState = false;
  21284. } else if (this.$$success[validationErrorKey]) {
  21285. combinedState = true;
  21286. } else {
  21287. combinedState = null;
  21288. }
  21289. toggleValidationCss(this, validationErrorKey, combinedState);
  21290. this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);
  21291. };
  21292. function createAndSet(ctrl, name, value, controller) {
  21293. if (!ctrl[name]) {
  21294. ctrl[name] = {};
  21295. }
  21296. set(ctrl[name], value, controller);
  21297. }
  21298. function unsetAndCleanup(ctrl, name, value, controller) {
  21299. if (ctrl[name]) {
  21300. unset(ctrl[name], value, controller);
  21301. }
  21302. if (isObjectEmpty(ctrl[name])) {
  21303. ctrl[name] = undefined;
  21304. }
  21305. }
  21306. function cachedToggleClass(ctrl, className, switchValue) {
  21307. if (switchValue && !ctrl.$$classCache[className]) {
  21308. ctrl.$$animate.addClass(ctrl.$$element, className);
  21309. ctrl.$$classCache[className] = true;
  21310. } else if (!switchValue && ctrl.$$classCache[className]) {
  21311. ctrl.$$animate.removeClass(ctrl.$$element, className);
  21312. ctrl.$$classCache[className] = false;
  21313. }
  21314. }
  21315. function toggleValidationCss(ctrl, validationErrorKey, isValid) {
  21316. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  21317. cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);
  21318. cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);
  21319. }
  21320. }
  21321. function isObjectEmpty(obj) {
  21322. if (obj) {
  21323. for (var prop in obj) {
  21324. if (obj.hasOwnProperty(prop)) {
  21325. return false;
  21326. }
  21327. }
  21328. }
  21329. return true;
  21330. }
  21331. /* global
  21332. VALID_CLASS: false,
  21333. INVALID_CLASS: false,
  21334. PRISTINE_CLASS: false,
  21335. DIRTY_CLASS: false,
  21336. ngModelMinErr: false
  21337. */
  21338. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  21339. 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)$/;
  21340. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  21341. // Note: We are being more lenient, because browsers are too.
  21342. // 1. Scheme
  21343. // 2. Slashes
  21344. // 3. Username
  21345. // 4. Password
  21346. // 5. Hostname
  21347. // 6. Port
  21348. // 7. Path
  21349. // 8. Query
  21350. // 9. Fragment
  21351. // 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
  21352. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  21353. // eslint-disable-next-line max-len
  21354. 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])?)*$/;
  21355. var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  21356. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  21357. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21358. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  21359. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  21360. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21361. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  21362. var PARTIAL_VALIDATION_TYPES = createMap();
  21363. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  21364. PARTIAL_VALIDATION_TYPES[type] = true;
  21365. });
  21366. var inputType = {
  21367. /**
  21368. * @ngdoc input
  21369. * @name input[text]
  21370. *
  21371. * @description
  21372. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  21373. *
  21374. *
  21375. * @param {string} ngModel Assignable angular expression to data-bind to.
  21376. * @param {string=} name Property name of the form under which the control is published.
  21377. * @param {string=} required Adds `required` validation error key if the value is not entered.
  21378. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21379. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21380. * `required` when you want to data-bind to the `required` attribute.
  21381. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21382. * minlength.
  21383. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21384. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21385. * any length.
  21386. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21387. * that contains the regular expression body that will be converted to a regular expression
  21388. * as in the ngPattern directive.
  21389. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21390. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21391. * If the expression evaluates to a RegExp object, then this is used directly.
  21392. * If the expression evaluates to a string, then it will be converted to a RegExp
  21393. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21394. * `new RegExp('^abc$')`.<br />
  21395. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21396. * start at the index of the last search's match, thus not taking the whole input value into
  21397. * account.
  21398. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21399. * interaction with the input element.
  21400. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21401. * This parameter is ignored for input[type=password] controls, which will never trim the
  21402. * input.
  21403. *
  21404. * @example
  21405. <example name="text-input-directive" module="textInputExample">
  21406. <file name="index.html">
  21407. <script>
  21408. angular.module('textInputExample', [])
  21409. .controller('ExampleController', ['$scope', function($scope) {
  21410. $scope.example = {
  21411. text: 'guest',
  21412. word: /^\s*\w*\s*$/
  21413. };
  21414. }]);
  21415. </script>
  21416. <form name="myForm" ng-controller="ExampleController">
  21417. <label>Single word:
  21418. <input type="text" name="input" ng-model="example.text"
  21419. ng-pattern="example.word" required ng-trim="false">
  21420. </label>
  21421. <div role="alert">
  21422. <span class="error" ng-show="myForm.input.$error.required">
  21423. Required!</span>
  21424. <span class="error" ng-show="myForm.input.$error.pattern">
  21425. Single word only!</span>
  21426. </div>
  21427. <code>text = {{example.text}}</code><br/>
  21428. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  21429. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  21430. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  21431. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  21432. </form>
  21433. </file>
  21434. <file name="protractor.js" type="protractor">
  21435. var text = element(by.binding('example.text'));
  21436. var valid = element(by.binding('myForm.input.$valid'));
  21437. var input = element(by.model('example.text'));
  21438. it('should initialize to model', function() {
  21439. expect(text.getText()).toContain('guest');
  21440. expect(valid.getText()).toContain('true');
  21441. });
  21442. it('should be invalid if empty', function() {
  21443. input.clear();
  21444. input.sendKeys('');
  21445. expect(text.getText()).toEqual('text =');
  21446. expect(valid.getText()).toContain('false');
  21447. });
  21448. it('should be invalid if multi word', function() {
  21449. input.clear();
  21450. input.sendKeys('hello world');
  21451. expect(valid.getText()).toContain('false');
  21452. });
  21453. </file>
  21454. </example>
  21455. */
  21456. 'text': textInputType,
  21457. /**
  21458. * @ngdoc input
  21459. * @name input[date]
  21460. *
  21461. * @description
  21462. * Input with date validation and transformation. In browsers that do not yet support
  21463. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  21464. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  21465. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  21466. * expected input format via a placeholder or label.
  21467. *
  21468. * The model must always be a Date object, otherwise Angular will throw an error.
  21469. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21470. *
  21471. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21472. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21473. *
  21474. * @param {string} ngModel Assignable angular expression to data-bind to.
  21475. * @param {string=} name Property name of the form under which the control is published.
  21476. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  21477. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21478. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  21479. * constraint validation.
  21480. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  21481. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21482. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  21483. * constraint validation.
  21484. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  21485. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21486. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  21487. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21488. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21489. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21490. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21491. * `required` when you want to data-bind to the `required` attribute.
  21492. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21493. * interaction with the input element.
  21494. *
  21495. * @example
  21496. <example name="date-input-directive" module="dateInputExample">
  21497. <file name="index.html">
  21498. <script>
  21499. angular.module('dateInputExample', [])
  21500. .controller('DateController', ['$scope', function($scope) {
  21501. $scope.example = {
  21502. value: new Date(2013, 9, 22)
  21503. };
  21504. }]);
  21505. </script>
  21506. <form name="myForm" ng-controller="DateController as dateCtrl">
  21507. <label for="exampleInput">Pick a date in 2013:</label>
  21508. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  21509. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  21510. <div role="alert">
  21511. <span class="error" ng-show="myForm.input.$error.required">
  21512. Required!</span>
  21513. <span class="error" ng-show="myForm.input.$error.date">
  21514. Not a valid date!</span>
  21515. </div>
  21516. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  21517. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21518. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21519. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21520. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21521. </form>
  21522. </file>
  21523. <file name="protractor.js" type="protractor">
  21524. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  21525. var valid = element(by.binding('myForm.input.$valid'));
  21526. // currently protractor/webdriver does not support
  21527. // sending keys to all known HTML5 input controls
  21528. // for various browsers (see https://github.com/angular/protractor/issues/562).
  21529. function setInput(val) {
  21530. // set the value of the element and force validation.
  21531. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21532. "ipt.value = '" + val + "';" +
  21533. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21534. browser.executeScript(scr);
  21535. }
  21536. it('should initialize to model', function() {
  21537. expect(value.getText()).toContain('2013-10-22');
  21538. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21539. });
  21540. it('should be invalid if empty', function() {
  21541. setInput('');
  21542. expect(value.getText()).toEqual('value =');
  21543. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21544. });
  21545. it('should be invalid if over max', function() {
  21546. setInput('2015-01-01');
  21547. expect(value.getText()).toContain('');
  21548. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21549. });
  21550. </file>
  21551. </example>
  21552. */
  21553. 'date': createDateInputType('date', DATE_REGEXP,
  21554. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  21555. 'yyyy-MM-dd'),
  21556. /**
  21557. * @ngdoc input
  21558. * @name input[datetime-local]
  21559. *
  21560. * @description
  21561. * Input with datetime validation and transformation. In browsers that do not yet support
  21562. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21563. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  21564. *
  21565. * The model must always be a Date object, otherwise Angular will throw an error.
  21566. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21567. *
  21568. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21569. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21570. *
  21571. * @param {string} ngModel Assignable angular expression to data-bind to.
  21572. * @param {string=} name Property name of the form under which the control is published.
  21573. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21574. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21575. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21576. * Note that `min` will also add native HTML5 constraint validation.
  21577. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21578. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21579. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21580. * Note that `max` will also add native HTML5 constraint validation.
  21581. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  21582. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21583. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  21584. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21585. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21586. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21587. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21588. * `required` when you want to data-bind to the `required` attribute.
  21589. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21590. * interaction with the input element.
  21591. *
  21592. * @example
  21593. <example name="datetimelocal-input-directive" module="dateExample">
  21594. <file name="index.html">
  21595. <script>
  21596. angular.module('dateExample', [])
  21597. .controller('DateController', ['$scope', function($scope) {
  21598. $scope.example = {
  21599. value: new Date(2010, 11, 28, 14, 57)
  21600. };
  21601. }]);
  21602. </script>
  21603. <form name="myForm" ng-controller="DateController as dateCtrl">
  21604. <label for="exampleInput">Pick a date between in 2013:</label>
  21605. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  21606. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  21607. <div role="alert">
  21608. <span class="error" ng-show="myForm.input.$error.required">
  21609. Required!</span>
  21610. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  21611. Not a valid date!</span>
  21612. </div>
  21613. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  21614. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21615. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21616. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21617. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21618. </form>
  21619. </file>
  21620. <file name="protractor.js" type="protractor">
  21621. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  21622. var valid = element(by.binding('myForm.input.$valid'));
  21623. // currently protractor/webdriver does not support
  21624. // sending keys to all known HTML5 input controls
  21625. // for various browsers (https://github.com/angular/protractor/issues/562).
  21626. function setInput(val) {
  21627. // set the value of the element and force validation.
  21628. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21629. "ipt.value = '" + val + "';" +
  21630. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21631. browser.executeScript(scr);
  21632. }
  21633. it('should initialize to model', function() {
  21634. expect(value.getText()).toContain('2010-12-28T14:57:00');
  21635. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21636. });
  21637. it('should be invalid if empty', function() {
  21638. setInput('');
  21639. expect(value.getText()).toEqual('value =');
  21640. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21641. });
  21642. it('should be invalid if over max', function() {
  21643. setInput('2015-01-01T23:59:00');
  21644. expect(value.getText()).toContain('');
  21645. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21646. });
  21647. </file>
  21648. </example>
  21649. */
  21650. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  21651. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  21652. 'yyyy-MM-ddTHH:mm:ss.sss'),
  21653. /**
  21654. * @ngdoc input
  21655. * @name input[time]
  21656. *
  21657. * @description
  21658. * Input with time validation and transformation. In browsers that do not yet support
  21659. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21660. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  21661. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  21662. *
  21663. * The model must always be a Date object, otherwise Angular will throw an error.
  21664. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21665. *
  21666. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21667. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21668. *
  21669. * @param {string} ngModel Assignable angular expression to data-bind to.
  21670. * @param {string=} name Property name of the form under which the control is published.
  21671. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21672. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21673. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  21674. * native HTML5 constraint validation.
  21675. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21676. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21677. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  21678. * native HTML5 constraint validation.
  21679. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  21680. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21681. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  21682. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21683. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21684. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21685. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21686. * `required` when you want to data-bind to the `required` attribute.
  21687. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21688. * interaction with the input element.
  21689. *
  21690. * @example
  21691. <example name="time-input-directive" module="timeExample">
  21692. <file name="index.html">
  21693. <script>
  21694. angular.module('timeExample', [])
  21695. .controller('DateController', ['$scope', function($scope) {
  21696. $scope.example = {
  21697. value: new Date(1970, 0, 1, 14, 57, 0)
  21698. };
  21699. }]);
  21700. </script>
  21701. <form name="myForm" ng-controller="DateController as dateCtrl">
  21702. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  21703. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  21704. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  21705. <div role="alert">
  21706. <span class="error" ng-show="myForm.input.$error.required">
  21707. Required!</span>
  21708. <span class="error" ng-show="myForm.input.$error.time">
  21709. Not a valid date!</span>
  21710. </div>
  21711. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  21712. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21713. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21714. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21715. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21716. </form>
  21717. </file>
  21718. <file name="protractor.js" type="protractor">
  21719. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  21720. var valid = element(by.binding('myForm.input.$valid'));
  21721. // currently protractor/webdriver does not support
  21722. // sending keys to all known HTML5 input controls
  21723. // for various browsers (https://github.com/angular/protractor/issues/562).
  21724. function setInput(val) {
  21725. // set the value of the element and force validation.
  21726. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21727. "ipt.value = '" + val + "';" +
  21728. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21729. browser.executeScript(scr);
  21730. }
  21731. it('should initialize to model', function() {
  21732. expect(value.getText()).toContain('14:57:00');
  21733. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21734. });
  21735. it('should be invalid if empty', function() {
  21736. setInput('');
  21737. expect(value.getText()).toEqual('value =');
  21738. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21739. });
  21740. it('should be invalid if over max', function() {
  21741. setInput('23:59:00');
  21742. expect(value.getText()).toContain('');
  21743. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21744. });
  21745. </file>
  21746. </example>
  21747. */
  21748. 'time': createDateInputType('time', TIME_REGEXP,
  21749. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  21750. 'HH:mm:ss.sss'),
  21751. /**
  21752. * @ngdoc input
  21753. * @name input[week]
  21754. *
  21755. * @description
  21756. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  21757. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21758. * week format (yyyy-W##), for example: `2013-W02`.
  21759. *
  21760. * The model must always be a Date object, otherwise Angular will throw an error.
  21761. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21762. *
  21763. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21764. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21765. *
  21766. * @param {string} ngModel Assignable angular expression to data-bind to.
  21767. * @param {string=} name Property name of the form under which the control is published.
  21768. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21769. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21770. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  21771. * native HTML5 constraint validation.
  21772. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21773. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21774. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  21775. * native HTML5 constraint validation.
  21776. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21777. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21778. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21779. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21780. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21781. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21782. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21783. * `required` when you want to data-bind to the `required` attribute.
  21784. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21785. * interaction with the input element.
  21786. *
  21787. * @example
  21788. <example name="week-input-directive" module="weekExample">
  21789. <file name="index.html">
  21790. <script>
  21791. angular.module('weekExample', [])
  21792. .controller('DateController', ['$scope', function($scope) {
  21793. $scope.example = {
  21794. value: new Date(2013, 0, 3)
  21795. };
  21796. }]);
  21797. </script>
  21798. <form name="myForm" ng-controller="DateController as dateCtrl">
  21799. <label>Pick a date between in 2013:
  21800. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  21801. placeholder="YYYY-W##" min="2012-W32"
  21802. max="2013-W52" required />
  21803. </label>
  21804. <div role="alert">
  21805. <span class="error" ng-show="myForm.input.$error.required">
  21806. Required!</span>
  21807. <span class="error" ng-show="myForm.input.$error.week">
  21808. Not a valid date!</span>
  21809. </div>
  21810. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  21811. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21812. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21813. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21814. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21815. </form>
  21816. </file>
  21817. <file name="protractor.js" type="protractor">
  21818. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  21819. var valid = element(by.binding('myForm.input.$valid'));
  21820. // currently protractor/webdriver does not support
  21821. // sending keys to all known HTML5 input controls
  21822. // for various browsers (https://github.com/angular/protractor/issues/562).
  21823. function setInput(val) {
  21824. // set the value of the element and force validation.
  21825. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21826. "ipt.value = '" + val + "';" +
  21827. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21828. browser.executeScript(scr);
  21829. }
  21830. it('should initialize to model', function() {
  21831. expect(value.getText()).toContain('2013-W01');
  21832. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21833. });
  21834. it('should be invalid if empty', function() {
  21835. setInput('');
  21836. expect(value.getText()).toEqual('value =');
  21837. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21838. });
  21839. it('should be invalid if over max', function() {
  21840. setInput('2015-W01');
  21841. expect(value.getText()).toContain('');
  21842. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21843. });
  21844. </file>
  21845. </example>
  21846. */
  21847. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  21848. /**
  21849. * @ngdoc input
  21850. * @name input[month]
  21851. *
  21852. * @description
  21853. * Input with month validation and transformation. In browsers that do not yet support
  21854. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21855. * month format (yyyy-MM), for example: `2009-01`.
  21856. *
  21857. * The model must always be a Date object, otherwise Angular will throw an error.
  21858. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21859. * If the model is not set to the first of the month, the next view to model update will set it
  21860. * to the first of the month.
  21861. *
  21862. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21863. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21864. *
  21865. * @param {string} ngModel Assignable angular expression to data-bind to.
  21866. * @param {string=} name Property name of the form under which the control is published.
  21867. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21868. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21869. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  21870. * native HTML5 constraint validation.
  21871. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21872. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21873. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  21874. * native HTML5 constraint validation.
  21875. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21876. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21877. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21878. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21879. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21880. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21881. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21882. * `required` when you want to data-bind to the `required` attribute.
  21883. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21884. * interaction with the input element.
  21885. *
  21886. * @example
  21887. <example name="month-input-directive" module="monthExample">
  21888. <file name="index.html">
  21889. <script>
  21890. angular.module('monthExample', [])
  21891. .controller('DateController', ['$scope', function($scope) {
  21892. $scope.example = {
  21893. value: new Date(2013, 9, 1)
  21894. };
  21895. }]);
  21896. </script>
  21897. <form name="myForm" ng-controller="DateController as dateCtrl">
  21898. <label for="exampleInput">Pick a month in 2013:</label>
  21899. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  21900. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  21901. <div role="alert">
  21902. <span class="error" ng-show="myForm.input.$error.required">
  21903. Required!</span>
  21904. <span class="error" ng-show="myForm.input.$error.month">
  21905. Not a valid month!</span>
  21906. </div>
  21907. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  21908. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21909. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21910. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21911. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21912. </form>
  21913. </file>
  21914. <file name="protractor.js" type="protractor">
  21915. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  21916. var valid = element(by.binding('myForm.input.$valid'));
  21917. // currently protractor/webdriver does not support
  21918. // sending keys to all known HTML5 input controls
  21919. // for various browsers (https://github.com/angular/protractor/issues/562).
  21920. function setInput(val) {
  21921. // set the value of the element and force validation.
  21922. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21923. "ipt.value = '" + val + "';" +
  21924. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21925. browser.executeScript(scr);
  21926. }
  21927. it('should initialize to model', function() {
  21928. expect(value.getText()).toContain('2013-10');
  21929. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21930. });
  21931. it('should be invalid if empty', function() {
  21932. setInput('');
  21933. expect(value.getText()).toEqual('value =');
  21934. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21935. });
  21936. it('should be invalid if over max', function() {
  21937. setInput('2015-01');
  21938. expect(value.getText()).toContain('');
  21939. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21940. });
  21941. </file>
  21942. </example>
  21943. */
  21944. 'month': createDateInputType('month', MONTH_REGEXP,
  21945. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  21946. 'yyyy-MM'),
  21947. /**
  21948. * @ngdoc input
  21949. * @name input[number]
  21950. *
  21951. * @description
  21952. * Text input with number validation and transformation. Sets the `number` validation
  21953. * error if not a valid number.
  21954. *
  21955. * <div class="alert alert-warning">
  21956. * The model must always be of type `number` otherwise Angular will throw an error.
  21957. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  21958. * error docs for more information and an example of how to convert your model if necessary.
  21959. * </div>
  21960. *
  21961. * ## Issues with HTML5 constraint validation
  21962. *
  21963. * In browsers that follow the
  21964. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  21965. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  21966. * If a non-number is entered in the input, the browser will report the value as an empty string,
  21967. * which means the view / model values in `ngModel` and subsequently the scope value
  21968. * will also be an empty string.
  21969. *
  21970. *
  21971. * @param {string} ngModel Assignable angular expression to data-bind to.
  21972. * @param {string=} name Property name of the form under which the control is published.
  21973. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21974. * Can be interpolated.
  21975. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21976. * Can be interpolated.
  21977. * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
  21978. * but does not trigger HTML5 native validation. Takes an expression.
  21979. * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
  21980. * but does not trigger HTML5 native validation. Takes an expression.
  21981. * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
  21982. * Can be interpolated.
  21983. * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,
  21984. * but does not trigger HTML5 native validation. Takes an expression.
  21985. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21986. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21987. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21988. * `required` when you want to data-bind to the `required` attribute.
  21989. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21990. * minlength.
  21991. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21992. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21993. * any length.
  21994. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21995. * that contains the regular expression body that will be converted to a regular expression
  21996. * as in the ngPattern directive.
  21997. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21998. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21999. * If the expression evaluates to a RegExp object, then this is used directly.
  22000. * If the expression evaluates to a string, then it will be converted to a RegExp
  22001. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22002. * `new RegExp('^abc$')`.<br />
  22003. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22004. * start at the index of the last search's match, thus not taking the whole input value into
  22005. * account.
  22006. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22007. * interaction with the input element.
  22008. *
  22009. * @example
  22010. <example name="number-input-directive" module="numberExample">
  22011. <file name="index.html">
  22012. <script>
  22013. angular.module('numberExample', [])
  22014. .controller('ExampleController', ['$scope', function($scope) {
  22015. $scope.example = {
  22016. value: 12
  22017. };
  22018. }]);
  22019. </script>
  22020. <form name="myForm" ng-controller="ExampleController">
  22021. <label>Number:
  22022. <input type="number" name="input" ng-model="example.value"
  22023. min="0" max="99" required>
  22024. </label>
  22025. <div role="alert">
  22026. <span class="error" ng-show="myForm.input.$error.required">
  22027. Required!</span>
  22028. <span class="error" ng-show="myForm.input.$error.number">
  22029. Not valid number!</span>
  22030. </div>
  22031. <tt>value = {{example.value}}</tt><br/>
  22032. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22033. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22034. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22035. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22036. </form>
  22037. </file>
  22038. <file name="protractor.js" type="protractor">
  22039. var value = element(by.binding('example.value'));
  22040. var valid = element(by.binding('myForm.input.$valid'));
  22041. var input = element(by.model('example.value'));
  22042. it('should initialize to model', function() {
  22043. expect(value.getText()).toContain('12');
  22044. expect(valid.getText()).toContain('true');
  22045. });
  22046. it('should be invalid if empty', function() {
  22047. input.clear();
  22048. input.sendKeys('');
  22049. expect(value.getText()).toEqual('value =');
  22050. expect(valid.getText()).toContain('false');
  22051. });
  22052. it('should be invalid if over max', function() {
  22053. input.clear();
  22054. input.sendKeys('123');
  22055. expect(value.getText()).toEqual('value =');
  22056. expect(valid.getText()).toContain('false');
  22057. });
  22058. </file>
  22059. </example>
  22060. */
  22061. 'number': numberInputType,
  22062. /**
  22063. * @ngdoc input
  22064. * @name input[url]
  22065. *
  22066. * @description
  22067. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  22068. * valid URL.
  22069. *
  22070. * <div class="alert alert-warning">
  22071. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  22072. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  22073. * the built-in validators (see the {@link guide/forms Forms guide})
  22074. * </div>
  22075. *
  22076. * @param {string} ngModel Assignable angular expression to data-bind to.
  22077. * @param {string=} name Property name of the form under which the control is published.
  22078. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22079. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22080. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22081. * `required` when you want to data-bind to the `required` attribute.
  22082. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22083. * minlength.
  22084. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22085. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22086. * any length.
  22087. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22088. * that contains the regular expression body that will be converted to a regular expression
  22089. * as in the ngPattern directive.
  22090. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22091. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22092. * If the expression evaluates to a RegExp object, then this is used directly.
  22093. * If the expression evaluates to a string, then it will be converted to a RegExp
  22094. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22095. * `new RegExp('^abc$')`.<br />
  22096. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22097. * start at the index of the last search's match, thus not taking the whole input value into
  22098. * account.
  22099. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22100. * interaction with the input element.
  22101. *
  22102. * @example
  22103. <example name="url-input-directive" module="urlExample">
  22104. <file name="index.html">
  22105. <script>
  22106. angular.module('urlExample', [])
  22107. .controller('ExampleController', ['$scope', function($scope) {
  22108. $scope.url = {
  22109. text: 'http://google.com'
  22110. };
  22111. }]);
  22112. </script>
  22113. <form name="myForm" ng-controller="ExampleController">
  22114. <label>URL:
  22115. <input type="url" name="input" ng-model="url.text" required>
  22116. <label>
  22117. <div role="alert">
  22118. <span class="error" ng-show="myForm.input.$error.required">
  22119. Required!</span>
  22120. <span class="error" ng-show="myForm.input.$error.url">
  22121. Not valid url!</span>
  22122. </div>
  22123. <tt>text = {{url.text}}</tt><br/>
  22124. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22125. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22126. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22127. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22128. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  22129. </form>
  22130. </file>
  22131. <file name="protractor.js" type="protractor">
  22132. var text = element(by.binding('url.text'));
  22133. var valid = element(by.binding('myForm.input.$valid'));
  22134. var input = element(by.model('url.text'));
  22135. it('should initialize to model', function() {
  22136. expect(text.getText()).toContain('http://google.com');
  22137. expect(valid.getText()).toContain('true');
  22138. });
  22139. it('should be invalid if empty', function() {
  22140. input.clear();
  22141. input.sendKeys('');
  22142. expect(text.getText()).toEqual('text =');
  22143. expect(valid.getText()).toContain('false');
  22144. });
  22145. it('should be invalid if not url', function() {
  22146. input.clear();
  22147. input.sendKeys('box');
  22148. expect(valid.getText()).toContain('false');
  22149. });
  22150. </file>
  22151. </example>
  22152. */
  22153. 'url': urlInputType,
  22154. /**
  22155. * @ngdoc input
  22156. * @name input[email]
  22157. *
  22158. * @description
  22159. * Text input with email validation. Sets the `email` validation error key if not a valid email
  22160. * address.
  22161. *
  22162. * <div class="alert alert-warning">
  22163. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  22164. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  22165. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  22166. * </div>
  22167. *
  22168. * @param {string} ngModel Assignable angular expression to data-bind to.
  22169. * @param {string=} name Property name of the form under which the control is published.
  22170. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22171. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22172. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22173. * `required` when you want to data-bind to the `required` attribute.
  22174. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22175. * minlength.
  22176. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22177. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22178. * any length.
  22179. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22180. * that contains the regular expression body that will be converted to a regular expression
  22181. * as in the ngPattern directive.
  22182. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22183. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22184. * If the expression evaluates to a RegExp object, then this is used directly.
  22185. * If the expression evaluates to a string, then it will be converted to a RegExp
  22186. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22187. * `new RegExp('^abc$')`.<br />
  22188. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22189. * start at the index of the last search's match, thus not taking the whole input value into
  22190. * account.
  22191. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22192. * interaction with the input element.
  22193. *
  22194. * @example
  22195. <example name="email-input-directive" module="emailExample">
  22196. <file name="index.html">
  22197. <script>
  22198. angular.module('emailExample', [])
  22199. .controller('ExampleController', ['$scope', function($scope) {
  22200. $scope.email = {
  22201. text: 'me@example.com'
  22202. };
  22203. }]);
  22204. </script>
  22205. <form name="myForm" ng-controller="ExampleController">
  22206. <label>Email:
  22207. <input type="email" name="input" ng-model="email.text" required>
  22208. </label>
  22209. <div role="alert">
  22210. <span class="error" ng-show="myForm.input.$error.required">
  22211. Required!</span>
  22212. <span class="error" ng-show="myForm.input.$error.email">
  22213. Not valid email!</span>
  22214. </div>
  22215. <tt>text = {{email.text}}</tt><br/>
  22216. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22217. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22218. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22219. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22220. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  22221. </form>
  22222. </file>
  22223. <file name="protractor.js" type="protractor">
  22224. var text = element(by.binding('email.text'));
  22225. var valid = element(by.binding('myForm.input.$valid'));
  22226. var input = element(by.model('email.text'));
  22227. it('should initialize to model', function() {
  22228. expect(text.getText()).toContain('me@example.com');
  22229. expect(valid.getText()).toContain('true');
  22230. });
  22231. it('should be invalid if empty', function() {
  22232. input.clear();
  22233. input.sendKeys('');
  22234. expect(text.getText()).toEqual('text =');
  22235. expect(valid.getText()).toContain('false');
  22236. });
  22237. it('should be invalid if not email', function() {
  22238. input.clear();
  22239. input.sendKeys('xxx');
  22240. expect(valid.getText()).toContain('false');
  22241. });
  22242. </file>
  22243. </example>
  22244. */
  22245. 'email': emailInputType,
  22246. /**
  22247. * @ngdoc input
  22248. * @name input[radio]
  22249. *
  22250. * @description
  22251. * HTML radio button.
  22252. *
  22253. * @param {string} ngModel Assignable angular expression to data-bind to.
  22254. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  22255. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  22256. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  22257. * @param {string=} name Property name of the form under which the control is published.
  22258. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22259. * interaction with the input element.
  22260. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  22261. * is selected. Should be used instead of the `value` attribute if you need
  22262. * a non-string `ngModel` (`boolean`, `array`, ...).
  22263. *
  22264. * @example
  22265. <example name="radio-input-directive" module="radioExample">
  22266. <file name="index.html">
  22267. <script>
  22268. angular.module('radioExample', [])
  22269. .controller('ExampleController', ['$scope', function($scope) {
  22270. $scope.color = {
  22271. name: 'blue'
  22272. };
  22273. $scope.specialValue = {
  22274. "id": "12345",
  22275. "value": "green"
  22276. };
  22277. }]);
  22278. </script>
  22279. <form name="myForm" ng-controller="ExampleController">
  22280. <label>
  22281. <input type="radio" ng-model="color.name" value="red">
  22282. Red
  22283. </label><br/>
  22284. <label>
  22285. <input type="radio" ng-model="color.name" ng-value="specialValue">
  22286. Green
  22287. </label><br/>
  22288. <label>
  22289. <input type="radio" ng-model="color.name" value="blue">
  22290. Blue
  22291. </label><br/>
  22292. <tt>color = {{color.name | json}}</tt><br/>
  22293. </form>
  22294. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  22295. </file>
  22296. <file name="protractor.js" type="protractor">
  22297. it('should change state', function() {
  22298. var inputs = element.all(by.model('color.name'));
  22299. var color = element(by.binding('color.name'));
  22300. expect(color.getText()).toContain('blue');
  22301. inputs.get(0).click();
  22302. expect(color.getText()).toContain('red');
  22303. inputs.get(1).click();
  22304. expect(color.getText()).toContain('green');
  22305. });
  22306. </file>
  22307. </example>
  22308. */
  22309. 'radio': radioInputType,
  22310. /**
  22311. * @ngdoc input
  22312. * @name input[range]
  22313. *
  22314. * @description
  22315. * Native range input with validation and transformation.
  22316. *
  22317. * The model for the range input must always be a `Number`.
  22318. *
  22319. * IE9 and other browsers that do not support the `range` type fall back
  22320. * to a text input without any default values for `min`, `max` and `step`. Model binding,
  22321. * validation and number parsing are nevertheless supported.
  22322. *
  22323. * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
  22324. * in a way that never allows the input to hold an invalid value. That means:
  22325. * - any non-numerical value is set to `(max + min) / 2`.
  22326. * - any numerical value that is less than the current min val, or greater than the current max val
  22327. * is set to the min / max val respectively.
  22328. * - additionally, the current `step` is respected, so the nearest value that satisfies a step
  22329. * is used.
  22330. *
  22331. * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
  22332. * for more info.
  22333. *
  22334. * This has the following consequences for Angular:
  22335. *
  22336. * Since the element value should always reflect the current model value, a range input
  22337. * will set the bound ngModel expression to the value that the browser has set for the
  22338. * input element. For example, in the following input `<input type="range" ng-model="model.value">`,
  22339. * if the application sets `model.value = null`, the browser will set the input to `'50'`.
  22340. * Angular will then set the model to `50`, to prevent input and model value being out of sync.
  22341. *
  22342. * That means the model for range will immediately be set to `50` after `ngModel` has been
  22343. * initialized. It also means a range input can never have the required error.
  22344. *
  22345. * This does not only affect changes to the model value, but also to the values of the `min`,
  22346. * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
  22347. * the input value, Angular will also update the model value.
  22348. *
  22349. * Automatic value adjustment also means that a range input element can never have the `required`,
  22350. * `min`, or `max` errors.
  22351. *
  22352. * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
  22353. * when the step value changes dynamically - they do not adjust the element value correctly, but
  22354. * instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step`
  22355. * error on the input, and set the model to `undefined`.
  22356. *
  22357. * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
  22358. * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
  22359. * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
  22360. *
  22361. * @param {string} ngModel Assignable angular expression to data-bind to.
  22362. * @param {string=} name Property name of the form under which the control is published.
  22363. * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
  22364. * than `min`. Can be interpolated.
  22365. * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
  22366. * Can be interpolated.
  22367. * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
  22368. * Can be interpolated.
  22369. * @param {string=} ngChange Angular expression to be executed when the ngModel value changes due
  22370. * to user interaction with the input element.
  22371. * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
  22372. * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
  22373. * Checkout {@link ng.directive:ngChecked ngChecked} for usage.
  22374. *
  22375. * @example
  22376. <example name="range-input-directive" module="rangeExample">
  22377. <file name="index.html">
  22378. <script>
  22379. angular.module('rangeExample', [])
  22380. .controller('ExampleController', ['$scope', function($scope) {
  22381. $scope.value = 75;
  22382. $scope.min = 10;
  22383. $scope.max = 90;
  22384. }]);
  22385. </script>
  22386. <form name="myForm" ng-controller="ExampleController">
  22387. Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
  22388. <hr>
  22389. Model as number: <input type="number" ng-model="value"><br>
  22390. Min: <input type="number" ng-model="min"><br>
  22391. Max: <input type="number" ng-model="max"><br>
  22392. value = <code>{{value}}</code><br/>
  22393. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22394. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22395. </form>
  22396. </file>
  22397. </example>
  22398. * ## Range Input with ngMin & ngMax attributes
  22399. * @example
  22400. <example name="range-input-directive-ng" module="rangeExample">
  22401. <file name="index.html">
  22402. <script>
  22403. angular.module('rangeExample', [])
  22404. .controller('ExampleController', ['$scope', function($scope) {
  22405. $scope.value = 75;
  22406. $scope.min = 10;
  22407. $scope.max = 90;
  22408. }]);
  22409. </script>
  22410. <form name="myForm" ng-controller="ExampleController">
  22411. Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
  22412. <hr>
  22413. Model as number: <input type="number" ng-model="value"><br>
  22414. Min: <input type="number" ng-model="min"><br>
  22415. Max: <input type="number" ng-model="max"><br>
  22416. value = <code>{{value}}</code><br/>
  22417. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22418. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22419. </form>
  22420. </file>
  22421. </example>
  22422. */
  22423. 'range': rangeInputType,
  22424. /**
  22425. * @ngdoc input
  22426. * @name input[checkbox]
  22427. *
  22428. * @description
  22429. * HTML checkbox.
  22430. *
  22431. * @param {string} ngModel Assignable angular expression to data-bind to.
  22432. * @param {string=} name Property name of the form under which the control is published.
  22433. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  22434. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  22435. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22436. * interaction with the input element.
  22437. *
  22438. * @example
  22439. <example name="checkbox-input-directive" module="checkboxExample">
  22440. <file name="index.html">
  22441. <script>
  22442. angular.module('checkboxExample', [])
  22443. .controller('ExampleController', ['$scope', function($scope) {
  22444. $scope.checkboxModel = {
  22445. value1 : true,
  22446. value2 : 'YES'
  22447. };
  22448. }]);
  22449. </script>
  22450. <form name="myForm" ng-controller="ExampleController">
  22451. <label>Value1:
  22452. <input type="checkbox" ng-model="checkboxModel.value1">
  22453. </label><br/>
  22454. <label>Value2:
  22455. <input type="checkbox" ng-model="checkboxModel.value2"
  22456. ng-true-value="'YES'" ng-false-value="'NO'">
  22457. </label><br/>
  22458. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  22459. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  22460. </form>
  22461. </file>
  22462. <file name="protractor.js" type="protractor">
  22463. it('should change state', function() {
  22464. var value1 = element(by.binding('checkboxModel.value1'));
  22465. var value2 = element(by.binding('checkboxModel.value2'));
  22466. expect(value1.getText()).toContain('true');
  22467. expect(value2.getText()).toContain('YES');
  22468. element(by.model('checkboxModel.value1')).click();
  22469. element(by.model('checkboxModel.value2')).click();
  22470. expect(value1.getText()).toContain('false');
  22471. expect(value2.getText()).toContain('NO');
  22472. });
  22473. </file>
  22474. </example>
  22475. */
  22476. 'checkbox': checkboxInputType,
  22477. 'hidden': noop,
  22478. 'button': noop,
  22479. 'submit': noop,
  22480. 'reset': noop,
  22481. 'file': noop
  22482. };
  22483. function stringBasedInputType(ctrl) {
  22484. ctrl.$formatters.push(function(value) {
  22485. return ctrl.$isEmpty(value) ? value : value.toString();
  22486. });
  22487. }
  22488. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22489. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22490. stringBasedInputType(ctrl);
  22491. }
  22492. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22493. var type = lowercase(element[0].type);
  22494. // In composition mode, users are still inputting intermediate text buffer,
  22495. // hold the listener until composition is done.
  22496. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  22497. if (!$sniffer.android) {
  22498. var composing = false;
  22499. element.on('compositionstart', function() {
  22500. composing = true;
  22501. });
  22502. element.on('compositionend', function() {
  22503. composing = false;
  22504. listener();
  22505. });
  22506. }
  22507. var timeout;
  22508. var listener = function(ev) {
  22509. if (timeout) {
  22510. $browser.defer.cancel(timeout);
  22511. timeout = null;
  22512. }
  22513. if (composing) return;
  22514. var value = element.val(),
  22515. event = ev && ev.type;
  22516. // By default we will trim the value
  22517. // If the attribute ng-trim exists we will avoid trimming
  22518. // If input type is 'password', the value is never trimmed
  22519. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  22520. value = trim(value);
  22521. }
  22522. // If a control is suffering from bad input (due to native validators), browsers discard its
  22523. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  22524. // control's value is the same empty value twice in a row.
  22525. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  22526. ctrl.$setViewValue(value, event);
  22527. }
  22528. };
  22529. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  22530. // input event on backspace, delete or cut
  22531. if ($sniffer.hasEvent('input')) {
  22532. element.on('input', listener);
  22533. } else {
  22534. var deferListener = function(ev, input, origValue) {
  22535. if (!timeout) {
  22536. timeout = $browser.defer(function() {
  22537. timeout = null;
  22538. if (!input || input.value !== origValue) {
  22539. listener(ev);
  22540. }
  22541. });
  22542. }
  22543. };
  22544. element.on('keydown', /** @this */ function(event) {
  22545. var key = event.keyCode;
  22546. // ignore
  22547. // command modifiers arrows
  22548. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  22549. deferListener(event, this, this.value);
  22550. });
  22551. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  22552. if ($sniffer.hasEvent('paste')) {
  22553. element.on('paste cut', deferListener);
  22554. }
  22555. }
  22556. // if user paste into input using mouse on older browser
  22557. // or form autocomplete on newer browser, we need "change" event to catch it
  22558. element.on('change', listener);
  22559. // Some native input types (date-family) have the ability to change validity without
  22560. // firing any input/change events.
  22561. // For these event types, when native validators are present and the browser supports the type,
  22562. // check for validity changes on various DOM events.
  22563. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  22564. element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
  22565. if (!timeout) {
  22566. var validity = this[VALIDITY_STATE_PROPERTY];
  22567. var origBadInput = validity.badInput;
  22568. var origTypeMismatch = validity.typeMismatch;
  22569. timeout = $browser.defer(function() {
  22570. timeout = null;
  22571. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  22572. listener(ev);
  22573. }
  22574. });
  22575. }
  22576. });
  22577. }
  22578. ctrl.$render = function() {
  22579. // Workaround for Firefox validation #12102.
  22580. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  22581. if (element.val() !== value) {
  22582. element.val(value);
  22583. }
  22584. };
  22585. }
  22586. function weekParser(isoWeek, existingDate) {
  22587. if (isDate(isoWeek)) {
  22588. return isoWeek;
  22589. }
  22590. if (isString(isoWeek)) {
  22591. WEEK_REGEXP.lastIndex = 0;
  22592. var parts = WEEK_REGEXP.exec(isoWeek);
  22593. if (parts) {
  22594. var year = +parts[1],
  22595. week = +parts[2],
  22596. hours = 0,
  22597. minutes = 0,
  22598. seconds = 0,
  22599. milliseconds = 0,
  22600. firstThurs = getFirstThursdayOfYear(year),
  22601. addDays = (week - 1) * 7;
  22602. if (existingDate) {
  22603. hours = existingDate.getHours();
  22604. minutes = existingDate.getMinutes();
  22605. seconds = existingDate.getSeconds();
  22606. milliseconds = existingDate.getMilliseconds();
  22607. }
  22608. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  22609. }
  22610. }
  22611. return NaN;
  22612. }
  22613. function createDateParser(regexp, mapping) {
  22614. return function(iso, date) {
  22615. var parts, map;
  22616. if (isDate(iso)) {
  22617. return iso;
  22618. }
  22619. if (isString(iso)) {
  22620. // When a date is JSON'ified to wraps itself inside of an extra
  22621. // set of double quotes. This makes the date parsing code unable
  22622. // to match the date string and parse it as a date.
  22623. if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
  22624. iso = iso.substring(1, iso.length - 1);
  22625. }
  22626. if (ISO_DATE_REGEXP.test(iso)) {
  22627. return new Date(iso);
  22628. }
  22629. regexp.lastIndex = 0;
  22630. parts = regexp.exec(iso);
  22631. if (parts) {
  22632. parts.shift();
  22633. if (date) {
  22634. map = {
  22635. yyyy: date.getFullYear(),
  22636. MM: date.getMonth() + 1,
  22637. dd: date.getDate(),
  22638. HH: date.getHours(),
  22639. mm: date.getMinutes(),
  22640. ss: date.getSeconds(),
  22641. sss: date.getMilliseconds() / 1000
  22642. };
  22643. } else {
  22644. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  22645. }
  22646. forEach(parts, function(part, index) {
  22647. if (index < mapping.length) {
  22648. map[mapping[index]] = +part;
  22649. }
  22650. });
  22651. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  22652. }
  22653. }
  22654. return NaN;
  22655. };
  22656. }
  22657. function createDateInputType(type, regexp, parseDate, format) {
  22658. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  22659. badInputChecker(scope, element, attr, ctrl);
  22660. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22661. var timezone = ctrl && ctrl.$options.getOption('timezone');
  22662. var previousDate;
  22663. ctrl.$$parserName = type;
  22664. ctrl.$parsers.push(function(value) {
  22665. if (ctrl.$isEmpty(value)) return null;
  22666. if (regexp.test(value)) {
  22667. // Note: We cannot read ctrl.$modelValue, as there might be a different
  22668. // parser/formatter in the processing chain so that the model
  22669. // contains some different data format!
  22670. var parsedDate = parseDate(value, previousDate);
  22671. if (timezone) {
  22672. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  22673. }
  22674. return parsedDate;
  22675. }
  22676. return undefined;
  22677. });
  22678. ctrl.$formatters.push(function(value) {
  22679. if (value && !isDate(value)) {
  22680. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  22681. }
  22682. if (isValidDate(value)) {
  22683. previousDate = value;
  22684. if (previousDate && timezone) {
  22685. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  22686. }
  22687. return $filter('date')(value, format, timezone);
  22688. } else {
  22689. previousDate = null;
  22690. return '';
  22691. }
  22692. });
  22693. if (isDefined(attr.min) || attr.ngMin) {
  22694. var minVal;
  22695. ctrl.$validators.min = function(value) {
  22696. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  22697. };
  22698. attr.$observe('min', function(val) {
  22699. minVal = parseObservedDateValue(val);
  22700. ctrl.$validate();
  22701. });
  22702. }
  22703. if (isDefined(attr.max) || attr.ngMax) {
  22704. var maxVal;
  22705. ctrl.$validators.max = function(value) {
  22706. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  22707. };
  22708. attr.$observe('max', function(val) {
  22709. maxVal = parseObservedDateValue(val);
  22710. ctrl.$validate();
  22711. });
  22712. }
  22713. function isValidDate(value) {
  22714. // Invalid Date: getTime() returns NaN
  22715. return value && !(value.getTime && value.getTime() !== value.getTime());
  22716. }
  22717. function parseObservedDateValue(val) {
  22718. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  22719. }
  22720. };
  22721. }
  22722. function badInputChecker(scope, element, attr, ctrl) {
  22723. var node = element[0];
  22724. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  22725. if (nativeValidation) {
  22726. ctrl.$parsers.push(function(value) {
  22727. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  22728. return validity.badInput || validity.typeMismatch ? undefined : value;
  22729. });
  22730. }
  22731. }
  22732. function numberFormatterParser(ctrl) {
  22733. ctrl.$$parserName = 'number';
  22734. ctrl.$parsers.push(function(value) {
  22735. if (ctrl.$isEmpty(value)) return null;
  22736. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  22737. return undefined;
  22738. });
  22739. ctrl.$formatters.push(function(value) {
  22740. if (!ctrl.$isEmpty(value)) {
  22741. if (!isNumber(value)) {
  22742. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  22743. }
  22744. value = value.toString();
  22745. }
  22746. return value;
  22747. });
  22748. }
  22749. function parseNumberAttrVal(val) {
  22750. if (isDefined(val) && !isNumber(val)) {
  22751. val = parseFloat(val);
  22752. }
  22753. return !isNumberNaN(val) ? val : undefined;
  22754. }
  22755. function isNumberInteger(num) {
  22756. // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
  22757. // (minus the assumption that `num` is a number)
  22758. // eslint-disable-next-line no-bitwise
  22759. return (num | 0) === num;
  22760. }
  22761. function countDecimals(num) {
  22762. var numString = num.toString();
  22763. var decimalSymbolIndex = numString.indexOf('.');
  22764. if (decimalSymbolIndex === -1) {
  22765. if (-1 < num && num < 1) {
  22766. // It may be in the exponential notation format (`1e-X`)
  22767. var match = /e-(\d+)$/.exec(numString);
  22768. if (match) {
  22769. return Number(match[1]);
  22770. }
  22771. }
  22772. return 0;
  22773. }
  22774. return numString.length - decimalSymbolIndex - 1;
  22775. }
  22776. function isValidForStep(viewValue, stepBase, step) {
  22777. // At this point `stepBase` and `step` are expected to be non-NaN values
  22778. // and `viewValue` is expected to be a valid stringified number.
  22779. var value = Number(viewValue);
  22780. var isNonIntegerValue = !isNumberInteger(value);
  22781. var isNonIntegerStepBase = !isNumberInteger(stepBase);
  22782. var isNonIntegerStep = !isNumberInteger(step);
  22783. // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
  22784. // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
  22785. if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) {
  22786. var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0;
  22787. var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0;
  22788. var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0;
  22789. var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals);
  22790. var multiplier = Math.pow(10, decimalCount);
  22791. value = value * multiplier;
  22792. stepBase = stepBase * multiplier;
  22793. step = step * multiplier;
  22794. if (isNonIntegerValue) value = Math.round(value);
  22795. if (isNonIntegerStepBase) stepBase = Math.round(stepBase);
  22796. if (isNonIntegerStep) step = Math.round(step);
  22797. }
  22798. return (value - stepBase) % step === 0;
  22799. }
  22800. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22801. badInputChecker(scope, element, attr, ctrl);
  22802. numberFormatterParser(ctrl);
  22803. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22804. var minVal;
  22805. var maxVal;
  22806. if (isDefined(attr.min) || attr.ngMin) {
  22807. ctrl.$validators.min = function(value) {
  22808. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  22809. };
  22810. attr.$observe('min', function(val) {
  22811. minVal = parseNumberAttrVal(val);
  22812. // TODO(matsko): implement validateLater to reduce number of validations
  22813. ctrl.$validate();
  22814. });
  22815. }
  22816. if (isDefined(attr.max) || attr.ngMax) {
  22817. ctrl.$validators.max = function(value) {
  22818. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  22819. };
  22820. attr.$observe('max', function(val) {
  22821. maxVal = parseNumberAttrVal(val);
  22822. // TODO(matsko): implement validateLater to reduce number of validations
  22823. ctrl.$validate();
  22824. });
  22825. }
  22826. if (isDefined(attr.step) || attr.ngStep) {
  22827. var stepVal;
  22828. ctrl.$validators.step = function(modelValue, viewValue) {
  22829. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  22830. isValidForStep(viewValue, minVal || 0, stepVal);
  22831. };
  22832. attr.$observe('step', function(val) {
  22833. stepVal = parseNumberAttrVal(val);
  22834. // TODO(matsko): implement validateLater to reduce number of validations
  22835. ctrl.$validate();
  22836. });
  22837. }
  22838. }
  22839. function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22840. badInputChecker(scope, element, attr, ctrl);
  22841. numberFormatterParser(ctrl);
  22842. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22843. var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
  22844. minVal = supportsRange ? 0 : undefined,
  22845. maxVal = supportsRange ? 100 : undefined,
  22846. stepVal = supportsRange ? 1 : undefined,
  22847. validity = element[0].validity,
  22848. hasMinAttr = isDefined(attr.min),
  22849. hasMaxAttr = isDefined(attr.max),
  22850. hasStepAttr = isDefined(attr.step);
  22851. var originalRender = ctrl.$render;
  22852. ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
  22853. //Browsers that implement range will set these values automatically, but reading the adjusted values after
  22854. //$render would cause the min / max validators to be applied with the wrong value
  22855. function rangeRender() {
  22856. originalRender();
  22857. ctrl.$setViewValue(element.val());
  22858. } :
  22859. originalRender;
  22860. if (hasMinAttr) {
  22861. ctrl.$validators.min = supportsRange ?
  22862. // Since all browsers set the input to a valid value, we don't need to check validity
  22863. function noopMinValidator() { return true; } :
  22864. // non-support browsers validate the min val
  22865. function minValidator(modelValue, viewValue) {
  22866. return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
  22867. };
  22868. setInitialValueAndObserver('min', minChange);
  22869. }
  22870. if (hasMaxAttr) {
  22871. ctrl.$validators.max = supportsRange ?
  22872. // Since all browsers set the input to a valid value, we don't need to check validity
  22873. function noopMaxValidator() { return true; } :
  22874. // non-support browsers validate the max val
  22875. function maxValidator(modelValue, viewValue) {
  22876. return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
  22877. };
  22878. setInitialValueAndObserver('max', maxChange);
  22879. }
  22880. if (hasStepAttr) {
  22881. ctrl.$validators.step = supportsRange ?
  22882. function nativeStepValidator() {
  22883. // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
  22884. // input element value to a valid value). It's possible that other browsers set the stepMismatch
  22885. // validity error instead, so we can at least report an error in that case.
  22886. return !validity.stepMismatch;
  22887. } :
  22888. // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
  22889. function stepValidator(modelValue, viewValue) {
  22890. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  22891. isValidForStep(viewValue, minVal || 0, stepVal);
  22892. };
  22893. setInitialValueAndObserver('step', stepChange);
  22894. }
  22895. function setInitialValueAndObserver(htmlAttrName, changeFn) {
  22896. // interpolated attributes set the attribute value only after a digest, but we need the
  22897. // attribute value when the input is first rendered, so that the browser can adjust the
  22898. // input value based on the min/max value
  22899. element.attr(htmlAttrName, attr[htmlAttrName]);
  22900. attr.$observe(htmlAttrName, changeFn);
  22901. }
  22902. function minChange(val) {
  22903. minVal = parseNumberAttrVal(val);
  22904. // ignore changes before model is initialized
  22905. if (isNumberNaN(ctrl.$modelValue)) {
  22906. return;
  22907. }
  22908. if (supportsRange) {
  22909. var elVal = element.val();
  22910. // IE11 doesn't set the el val correctly if the minVal is greater than the element value
  22911. if (minVal > elVal) {
  22912. elVal = minVal;
  22913. element.val(elVal);
  22914. }
  22915. ctrl.$setViewValue(elVal);
  22916. } else {
  22917. // TODO(matsko): implement validateLater to reduce number of validations
  22918. ctrl.$validate();
  22919. }
  22920. }
  22921. function maxChange(val) {
  22922. maxVal = parseNumberAttrVal(val);
  22923. // ignore changes before model is initialized
  22924. if (isNumberNaN(ctrl.$modelValue)) {
  22925. return;
  22926. }
  22927. if (supportsRange) {
  22928. var elVal = element.val();
  22929. // IE11 doesn't set the el val correctly if the maxVal is less than the element value
  22930. if (maxVal < elVal) {
  22931. element.val(maxVal);
  22932. // IE11 and Chrome don't set the value to the minVal when max < min
  22933. elVal = maxVal < minVal ? minVal : maxVal;
  22934. }
  22935. ctrl.$setViewValue(elVal);
  22936. } else {
  22937. // TODO(matsko): implement validateLater to reduce number of validations
  22938. ctrl.$validate();
  22939. }
  22940. }
  22941. function stepChange(val) {
  22942. stepVal = parseNumberAttrVal(val);
  22943. // ignore changes before model is initialized
  22944. if (isNumberNaN(ctrl.$modelValue)) {
  22945. return;
  22946. }
  22947. // Some browsers don't adjust the input value correctly, but set the stepMismatch error
  22948. if (supportsRange && ctrl.$viewValue !== element.val()) {
  22949. ctrl.$setViewValue(element.val());
  22950. } else {
  22951. // TODO(matsko): implement validateLater to reduce number of validations
  22952. ctrl.$validate();
  22953. }
  22954. }
  22955. }
  22956. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22957. // Note: no badInputChecker here by purpose as `url` is only a validation
  22958. // in browsers, i.e. we can always read out input.value even if it is not valid!
  22959. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22960. stringBasedInputType(ctrl);
  22961. ctrl.$$parserName = 'url';
  22962. ctrl.$validators.url = function(modelValue, viewValue) {
  22963. var value = modelValue || viewValue;
  22964. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  22965. };
  22966. }
  22967. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22968. // Note: no badInputChecker here by purpose as `url` is only a validation
  22969. // in browsers, i.e. we can always read out input.value even if it is not valid!
  22970. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22971. stringBasedInputType(ctrl);
  22972. ctrl.$$parserName = 'email';
  22973. ctrl.$validators.email = function(modelValue, viewValue) {
  22974. var value = modelValue || viewValue;
  22975. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  22976. };
  22977. }
  22978. function radioInputType(scope, element, attr, ctrl) {
  22979. var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
  22980. // make the name unique, if not defined
  22981. if (isUndefined(attr.name)) {
  22982. element.attr('name', nextUid());
  22983. }
  22984. var listener = function(ev) {
  22985. var value;
  22986. if (element[0].checked) {
  22987. value = attr.value;
  22988. if (doTrim) {
  22989. value = trim(value);
  22990. }
  22991. ctrl.$setViewValue(value, ev && ev.type);
  22992. }
  22993. };
  22994. element.on('click', listener);
  22995. ctrl.$render = function() {
  22996. var value = attr.value;
  22997. if (doTrim) {
  22998. value = trim(value);
  22999. }
  23000. element[0].checked = (value === ctrl.$viewValue);
  23001. };
  23002. attr.$observe('value', ctrl.$render);
  23003. }
  23004. function parseConstantExpr($parse, context, name, expression, fallback) {
  23005. var parseFn;
  23006. if (isDefined(expression)) {
  23007. parseFn = $parse(expression);
  23008. if (!parseFn.constant) {
  23009. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  23010. '`{1}`.', name, expression);
  23011. }
  23012. return parseFn(context);
  23013. }
  23014. return fallback;
  23015. }
  23016. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  23017. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  23018. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  23019. var listener = function(ev) {
  23020. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  23021. };
  23022. element.on('click', listener);
  23023. ctrl.$render = function() {
  23024. element[0].checked = ctrl.$viewValue;
  23025. };
  23026. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  23027. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  23028. // it to a boolean.
  23029. ctrl.$isEmpty = function(value) {
  23030. return value === false;
  23031. };
  23032. ctrl.$formatters.push(function(value) {
  23033. return equals(value, trueValue);
  23034. });
  23035. ctrl.$parsers.push(function(value) {
  23036. return value ? trueValue : falseValue;
  23037. });
  23038. }
  23039. /**
  23040. * @ngdoc directive
  23041. * @name textarea
  23042. * @restrict E
  23043. *
  23044. * @description
  23045. * HTML textarea element control with angular data-binding. The data-binding and validation
  23046. * properties of this element are exactly the same as those of the
  23047. * {@link ng.directive:input input element}.
  23048. *
  23049. * @param {string} ngModel Assignable angular expression to data-bind to.
  23050. * @param {string=} name Property name of the form under which the control is published.
  23051. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23052. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23053. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23054. * `required` when you want to data-bind to the `required` attribute.
  23055. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23056. * minlength.
  23057. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23058. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  23059. * length.
  23060. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23061. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  23062. * If the expression evaluates to a RegExp object, then this is used directly.
  23063. * If the expression evaluates to a string, then it will be converted to a RegExp
  23064. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23065. * `new RegExp('^abc$')`.<br />
  23066. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23067. * start at the index of the last search's match, thus not taking the whole input value into
  23068. * account.
  23069. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  23070. * interaction with the input element.
  23071. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  23072. *
  23073. * @knownIssue
  23074. *
  23075. * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
  23076. * insert the placeholder value as the textarea's content. If the placeholder value contains
  23077. * interpolation (`{{ ... }}`), an error will be logged in the console when Angular tries to update
  23078. * the value of the by-then-removed text node. This doesn't affect the functionality of the
  23079. * textarea, but can be undesirable.
  23080. *
  23081. * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
  23082. * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
  23083. * find more details on `ngAttr` in the
  23084. * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
  23085. * Developer Guide.
  23086. */
  23087. /**
  23088. * @ngdoc directive
  23089. * @name input
  23090. * @restrict E
  23091. *
  23092. * @description
  23093. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  23094. * input state control, and validation.
  23095. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  23096. *
  23097. * <div class="alert alert-warning">
  23098. * **Note:** Not every feature offered is available for all input types.
  23099. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  23100. * </div>
  23101. *
  23102. * @param {string} ngModel Assignable angular expression to data-bind to.
  23103. * @param {string=} name Property name of the form under which the control is published.
  23104. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23105. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  23106. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23107. * minlength.
  23108. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23109. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  23110. * length.
  23111. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23112. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  23113. * If the expression evaluates to a RegExp object, then this is used directly.
  23114. * If the expression evaluates to a string, then it will be converted to a RegExp
  23115. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23116. * `new RegExp('^abc$')`.<br />
  23117. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23118. * start at the index of the last search's match, thus not taking the whole input value into
  23119. * account.
  23120. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  23121. * interaction with the input element.
  23122. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  23123. * This parameter is ignored for input[type=password] controls, which will never trim the
  23124. * input.
  23125. *
  23126. * @example
  23127. <example name="input-directive" module="inputExample">
  23128. <file name="index.html">
  23129. <script>
  23130. angular.module('inputExample', [])
  23131. .controller('ExampleController', ['$scope', function($scope) {
  23132. $scope.user = {name: 'guest', last: 'visitor'};
  23133. }]);
  23134. </script>
  23135. <div ng-controller="ExampleController">
  23136. <form name="myForm">
  23137. <label>
  23138. User name:
  23139. <input type="text" name="userName" ng-model="user.name" required>
  23140. </label>
  23141. <div role="alert">
  23142. <span class="error" ng-show="myForm.userName.$error.required">
  23143. Required!</span>
  23144. </div>
  23145. <label>
  23146. Last name:
  23147. <input type="text" name="lastName" ng-model="user.last"
  23148. ng-minlength="3" ng-maxlength="10">
  23149. </label>
  23150. <div role="alert">
  23151. <span class="error" ng-show="myForm.lastName.$error.minlength">
  23152. Too short!</span>
  23153. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  23154. Too long!</span>
  23155. </div>
  23156. </form>
  23157. <hr>
  23158. <tt>user = {{user}}</tt><br/>
  23159. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  23160. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  23161. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  23162. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  23163. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23164. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23165. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  23166. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  23167. </div>
  23168. </file>
  23169. <file name="protractor.js" type="protractor">
  23170. var user = element(by.exactBinding('user'));
  23171. var userNameValid = element(by.binding('myForm.userName.$valid'));
  23172. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  23173. var lastNameError = element(by.binding('myForm.lastName.$error'));
  23174. var formValid = element(by.binding('myForm.$valid'));
  23175. var userNameInput = element(by.model('user.name'));
  23176. var userLastInput = element(by.model('user.last'));
  23177. it('should initialize to model', function() {
  23178. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  23179. expect(userNameValid.getText()).toContain('true');
  23180. expect(formValid.getText()).toContain('true');
  23181. });
  23182. it('should be invalid if empty when required', function() {
  23183. userNameInput.clear();
  23184. userNameInput.sendKeys('');
  23185. expect(user.getText()).toContain('{"last":"visitor"}');
  23186. expect(userNameValid.getText()).toContain('false');
  23187. expect(formValid.getText()).toContain('false');
  23188. });
  23189. it('should be valid if empty when min length is set', function() {
  23190. userLastInput.clear();
  23191. userLastInput.sendKeys('');
  23192. expect(user.getText()).toContain('{"name":"guest","last":""}');
  23193. expect(lastNameValid.getText()).toContain('true');
  23194. expect(formValid.getText()).toContain('true');
  23195. });
  23196. it('should be invalid if less than required min length', function() {
  23197. userLastInput.clear();
  23198. userLastInput.sendKeys('xx');
  23199. expect(user.getText()).toContain('{"name":"guest"}');
  23200. expect(lastNameValid.getText()).toContain('false');
  23201. expect(lastNameError.getText()).toContain('minlength');
  23202. expect(formValid.getText()).toContain('false');
  23203. });
  23204. it('should be invalid if longer than max length', function() {
  23205. userLastInput.clear();
  23206. userLastInput.sendKeys('some ridiculously long name');
  23207. expect(user.getText()).toContain('{"name":"guest"}');
  23208. expect(lastNameValid.getText()).toContain('false');
  23209. expect(lastNameError.getText()).toContain('maxlength');
  23210. expect(formValid.getText()).toContain('false');
  23211. });
  23212. </file>
  23213. </example>
  23214. */
  23215. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  23216. function($browser, $sniffer, $filter, $parse) {
  23217. return {
  23218. restrict: 'E',
  23219. require: ['?ngModel'],
  23220. link: {
  23221. pre: function(scope, element, attr, ctrls) {
  23222. if (ctrls[0]) {
  23223. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  23224. $browser, $filter, $parse);
  23225. }
  23226. }
  23227. }
  23228. };
  23229. }];
  23230. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  23231. /**
  23232. * @ngdoc directive
  23233. * @name ngValue
  23234. *
  23235. * @description
  23236. * Binds the given expression to the value of the element.
  23237. *
  23238. * It is mainly used on {@link input[radio] `input[radio]`} and option elements,
  23239. * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
  23240. * {@link select `select`} parent element) is set to the bound value. It is especially useful
  23241. * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
  23242. *
  23243. * It can also be used to achieve one-way binding of a given expression to an input element
  23244. * such as an `input[text]` or a `textarea`, when that element does not use ngModel.
  23245. *
  23246. * @element input
  23247. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  23248. * and `value` property of the element.
  23249. *
  23250. * @example
  23251. <example name="ngValue-directive" module="valueExample">
  23252. <file name="index.html">
  23253. <script>
  23254. angular.module('valueExample', [])
  23255. .controller('ExampleController', ['$scope', function($scope) {
  23256. $scope.names = ['pizza', 'unicorns', 'robots'];
  23257. $scope.my = { favorite: 'unicorns' };
  23258. }]);
  23259. </script>
  23260. <form ng-controller="ExampleController">
  23261. <h2>Which is your favorite?</h2>
  23262. <label ng-repeat="name in names" for="{{name}}">
  23263. {{name}}
  23264. <input type="radio"
  23265. ng-model="my.favorite"
  23266. ng-value="name"
  23267. id="{{name}}"
  23268. name="favorite">
  23269. </label>
  23270. <div>You chose {{my.favorite}}</div>
  23271. </form>
  23272. </file>
  23273. <file name="protractor.js" type="protractor">
  23274. var favorite = element(by.binding('my.favorite'));
  23275. it('should initialize to model', function() {
  23276. expect(favorite.getText()).toContain('unicorns');
  23277. });
  23278. it('should bind the values to the inputs', function() {
  23279. element.all(by.model('my.favorite')).get(0).click();
  23280. expect(favorite.getText()).toContain('pizza');
  23281. });
  23282. </file>
  23283. </example>
  23284. */
  23285. var ngValueDirective = function() {
  23286. /**
  23287. * inputs use the value attribute as their default value if the value property is not set.
  23288. * Once the value property has been set (by adding input), it will not react to changes to
  23289. * the value attribute anymore. Setting both attribute and property fixes this behavior, and
  23290. * makes it possible to use ngValue as a sort of one-way bind.
  23291. */
  23292. function updateElementValue(element, attr, value) {
  23293. // Support: IE9 only
  23294. // In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`).
  23295. var propValue = isDefined(value) ? value : (msie === 9) ? '' : null;
  23296. element.prop('value', propValue);
  23297. attr.$set('value', value);
  23298. }
  23299. return {
  23300. restrict: 'A',
  23301. priority: 100,
  23302. compile: function(tpl, tplAttr) {
  23303. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  23304. return function ngValueConstantLink(scope, elm, attr) {
  23305. var value = scope.$eval(attr.ngValue);
  23306. updateElementValue(elm, attr, value);
  23307. };
  23308. } else {
  23309. return function ngValueLink(scope, elm, attr) {
  23310. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  23311. updateElementValue(elm, attr, value);
  23312. });
  23313. };
  23314. }
  23315. }
  23316. };
  23317. };
  23318. /**
  23319. * @ngdoc directive
  23320. * @name ngBind
  23321. * @restrict AC
  23322. *
  23323. * @description
  23324. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  23325. * with the value of a given expression, and to update the text content when the value of that
  23326. * expression changes.
  23327. *
  23328. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  23329. * `{{ expression }}` which is similar but less verbose.
  23330. *
  23331. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  23332. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  23333. * element attribute, it makes the bindings invisible to the user while the page is loading.
  23334. *
  23335. * An alternative solution to this problem would be using the
  23336. * {@link ng.directive:ngCloak ngCloak} directive.
  23337. *
  23338. *
  23339. * @element ANY
  23340. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  23341. *
  23342. * @example
  23343. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  23344. <example module="bindExample" name="ng-bind">
  23345. <file name="index.html">
  23346. <script>
  23347. angular.module('bindExample', [])
  23348. .controller('ExampleController', ['$scope', function($scope) {
  23349. $scope.name = 'Whirled';
  23350. }]);
  23351. </script>
  23352. <div ng-controller="ExampleController">
  23353. <label>Enter name: <input type="text" ng-model="name"></label><br>
  23354. Hello <span ng-bind="name"></span>!
  23355. </div>
  23356. </file>
  23357. <file name="protractor.js" type="protractor">
  23358. it('should check ng-bind', function() {
  23359. var nameInput = element(by.model('name'));
  23360. expect(element(by.binding('name')).getText()).toBe('Whirled');
  23361. nameInput.clear();
  23362. nameInput.sendKeys('world');
  23363. expect(element(by.binding('name')).getText()).toBe('world');
  23364. });
  23365. </file>
  23366. </example>
  23367. */
  23368. var ngBindDirective = ['$compile', function($compile) {
  23369. return {
  23370. restrict: 'AC',
  23371. compile: function ngBindCompile(templateElement) {
  23372. $compile.$$addBindingClass(templateElement);
  23373. return function ngBindLink(scope, element, attr) {
  23374. $compile.$$addBindingInfo(element, attr.ngBind);
  23375. element = element[0];
  23376. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  23377. element.textContent = stringify(value);
  23378. });
  23379. };
  23380. }
  23381. };
  23382. }];
  23383. /**
  23384. * @ngdoc directive
  23385. * @name ngBindTemplate
  23386. *
  23387. * @description
  23388. * The `ngBindTemplate` directive specifies that the element
  23389. * text content should be replaced with the interpolation of the template
  23390. * in the `ngBindTemplate` attribute.
  23391. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  23392. * expressions. This directive is needed since some HTML elements
  23393. * (such as TITLE and OPTION) cannot contain SPAN elements.
  23394. *
  23395. * @element ANY
  23396. * @param {string} ngBindTemplate template of form
  23397. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  23398. *
  23399. * @example
  23400. * Try it here: enter text in text box and watch the greeting change.
  23401. <example module="bindExample" name="ng-bind-template">
  23402. <file name="index.html">
  23403. <script>
  23404. angular.module('bindExample', [])
  23405. .controller('ExampleController', ['$scope', function($scope) {
  23406. $scope.salutation = 'Hello';
  23407. $scope.name = 'World';
  23408. }]);
  23409. </script>
  23410. <div ng-controller="ExampleController">
  23411. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  23412. <label>Name: <input type="text" ng-model="name"></label><br>
  23413. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  23414. </div>
  23415. </file>
  23416. <file name="protractor.js" type="protractor">
  23417. it('should check ng-bind', function() {
  23418. var salutationElem = element(by.binding('salutation'));
  23419. var salutationInput = element(by.model('salutation'));
  23420. var nameInput = element(by.model('name'));
  23421. expect(salutationElem.getText()).toBe('Hello World!');
  23422. salutationInput.clear();
  23423. salutationInput.sendKeys('Greetings');
  23424. nameInput.clear();
  23425. nameInput.sendKeys('user');
  23426. expect(salutationElem.getText()).toBe('Greetings user!');
  23427. });
  23428. </file>
  23429. </example>
  23430. */
  23431. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  23432. return {
  23433. compile: function ngBindTemplateCompile(templateElement) {
  23434. $compile.$$addBindingClass(templateElement);
  23435. return function ngBindTemplateLink(scope, element, attr) {
  23436. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  23437. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  23438. element = element[0];
  23439. attr.$observe('ngBindTemplate', function(value) {
  23440. element.textContent = isUndefined(value) ? '' : value;
  23441. });
  23442. };
  23443. }
  23444. };
  23445. }];
  23446. /**
  23447. * @ngdoc directive
  23448. * @name ngBindHtml
  23449. *
  23450. * @description
  23451. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  23452. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  23453. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  23454. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  23455. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  23456. *
  23457. * You may also bypass sanitization for values you know are safe. To do so, bind to
  23458. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  23459. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  23460. *
  23461. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  23462. * will have an exception (instead of an exploit.)
  23463. *
  23464. * @element ANY
  23465. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  23466. *
  23467. * @example
  23468. <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
  23469. <file name="index.html">
  23470. <div ng-controller="ExampleController">
  23471. <p ng-bind-html="myHTML"></p>
  23472. </div>
  23473. </file>
  23474. <file name="script.js">
  23475. angular.module('bindHtmlExample', ['ngSanitize'])
  23476. .controller('ExampleController', ['$scope', function($scope) {
  23477. $scope.myHTML =
  23478. 'I am an <code>HTML</code>string with ' +
  23479. '<a href="#">links!</a> and other <em>stuff</em>';
  23480. }]);
  23481. </file>
  23482. <file name="protractor.js" type="protractor">
  23483. it('should check ng-bind-html', function() {
  23484. expect(element(by.binding('myHTML')).getText()).toBe(
  23485. 'I am an HTMLstring with links! and other stuff');
  23486. });
  23487. </file>
  23488. </example>
  23489. */
  23490. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  23491. return {
  23492. restrict: 'A',
  23493. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  23494. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  23495. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  23496. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  23497. return $sce.valueOf(val);
  23498. });
  23499. $compile.$$addBindingClass(tElement);
  23500. return function ngBindHtmlLink(scope, element, attr) {
  23501. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  23502. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  23503. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  23504. var value = ngBindHtmlGetter(scope);
  23505. element.html($sce.getTrustedHtml(value) || '');
  23506. });
  23507. };
  23508. }
  23509. };
  23510. }];
  23511. /**
  23512. * @ngdoc directive
  23513. * @name ngChange
  23514. *
  23515. * @description
  23516. * Evaluate the given expression when the user changes the input.
  23517. * The expression is evaluated immediately, unlike the JavaScript onchange event
  23518. * which only triggers at the end of a change (usually, when the user leaves the
  23519. * form element or presses the return key).
  23520. *
  23521. * The `ngChange` expression is only evaluated when a change in the input value causes
  23522. * a new value to be committed to the model.
  23523. *
  23524. * It will not be evaluated:
  23525. * * if the value returned from the `$parsers` transformation pipeline has not changed
  23526. * * if the input has continued to be invalid since the model will stay `null`
  23527. * * if the model is changed programmatically and not by a change to the input value
  23528. *
  23529. *
  23530. * Note, this directive requires `ngModel` to be present.
  23531. *
  23532. * @element input
  23533. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  23534. * in input value.
  23535. *
  23536. * @example
  23537. * <example name="ngChange-directive" module="changeExample">
  23538. * <file name="index.html">
  23539. * <script>
  23540. * angular.module('changeExample', [])
  23541. * .controller('ExampleController', ['$scope', function($scope) {
  23542. * $scope.counter = 0;
  23543. * $scope.change = function() {
  23544. * $scope.counter++;
  23545. * };
  23546. * }]);
  23547. * </script>
  23548. * <div ng-controller="ExampleController">
  23549. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  23550. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  23551. * <label for="ng-change-example2">Confirmed</label><br />
  23552. * <tt>debug = {{confirmed}}</tt><br/>
  23553. * <tt>counter = {{counter}}</tt><br/>
  23554. * </div>
  23555. * </file>
  23556. * <file name="protractor.js" type="protractor">
  23557. * var counter = element(by.binding('counter'));
  23558. * var debug = element(by.binding('confirmed'));
  23559. *
  23560. * it('should evaluate the expression if changing from view', function() {
  23561. * expect(counter.getText()).toContain('0');
  23562. *
  23563. * element(by.id('ng-change-example1')).click();
  23564. *
  23565. * expect(counter.getText()).toContain('1');
  23566. * expect(debug.getText()).toContain('true');
  23567. * });
  23568. *
  23569. * it('should not evaluate the expression if changing from model', function() {
  23570. * element(by.id('ng-change-example2')).click();
  23571. * expect(counter.getText()).toContain('0');
  23572. * expect(debug.getText()).toContain('true');
  23573. * });
  23574. * </file>
  23575. * </example>
  23576. */
  23577. var ngChangeDirective = valueFn({
  23578. restrict: 'A',
  23579. require: 'ngModel',
  23580. link: function(scope, element, attr, ctrl) {
  23581. ctrl.$viewChangeListeners.push(function() {
  23582. scope.$eval(attr.ngChange);
  23583. });
  23584. }
  23585. });
  23586. /* exported
  23587. ngClassDirective,
  23588. ngClassEvenDirective,
  23589. ngClassOddDirective
  23590. */
  23591. function classDirective(name, selector) {
  23592. name = 'ngClass' + name;
  23593. var indexWatchExpression;
  23594. return ['$parse', function($parse) {
  23595. return {
  23596. restrict: 'AC',
  23597. link: function(scope, element, attr) {
  23598. var expression = attr[name].trim();
  23599. var isOneTime = (expression.charAt(0) === ':') && (expression.charAt(1) === ':');
  23600. var watchInterceptor = isOneTime ? toFlatValue : toClassString;
  23601. var watchExpression = $parse(expression, watchInterceptor);
  23602. var watchAction = isOneTime ? ngClassOneTimeWatchAction : ngClassWatchAction;
  23603. var classCounts = element.data('$classCounts');
  23604. var oldModulo = true;
  23605. var oldClassString;
  23606. if (!classCounts) {
  23607. // Use createMap() to prevent class assumptions involving property
  23608. // names in Object.prototype
  23609. classCounts = createMap();
  23610. element.data('$classCounts', classCounts);
  23611. }
  23612. if (name !== 'ngClass') {
  23613. if (!indexWatchExpression) {
  23614. indexWatchExpression = $parse('$index', function moduloTwo($index) {
  23615. // eslint-disable-next-line no-bitwise
  23616. return $index & 1;
  23617. });
  23618. }
  23619. scope.$watch(indexWatchExpression, ngClassIndexWatchAction);
  23620. }
  23621. scope.$watch(watchExpression, watchAction, isOneTime);
  23622. function addClasses(classString) {
  23623. classString = digestClassCounts(split(classString), 1);
  23624. attr.$addClass(classString);
  23625. }
  23626. function removeClasses(classString) {
  23627. classString = digestClassCounts(split(classString), -1);
  23628. attr.$removeClass(classString);
  23629. }
  23630. function updateClasses(oldClassString, newClassString) {
  23631. var oldClassArray = split(oldClassString);
  23632. var newClassArray = split(newClassString);
  23633. var toRemoveArray = arrayDifference(oldClassArray, newClassArray);
  23634. var toAddArray = arrayDifference(newClassArray, oldClassArray);
  23635. var toRemoveString = digestClassCounts(toRemoveArray, -1);
  23636. var toAddString = digestClassCounts(toAddArray, 1);
  23637. attr.$addClass(toAddString);
  23638. attr.$removeClass(toRemoveString);
  23639. }
  23640. function digestClassCounts(classArray, count) {
  23641. var classesToUpdate = [];
  23642. forEach(classArray, function(className) {
  23643. if (count > 0 || classCounts[className]) {
  23644. classCounts[className] = (classCounts[className] || 0) + count;
  23645. if (classCounts[className] === +(count > 0)) {
  23646. classesToUpdate.push(className);
  23647. }
  23648. }
  23649. });
  23650. return classesToUpdate.join(' ');
  23651. }
  23652. function ngClassIndexWatchAction(newModulo) {
  23653. // This watch-action should run before the `ngClass[OneTime]WatchAction()`, thus it
  23654. // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the
  23655. // `ngClass[OneTime]WatchAction()` will update the classes.
  23656. if (newModulo === selector) {
  23657. addClasses(oldClassString);
  23658. } else {
  23659. removeClasses(oldClassString);
  23660. }
  23661. oldModulo = newModulo;
  23662. }
  23663. function ngClassOneTimeWatchAction(newClassValue) {
  23664. var newClassString = toClassString(newClassValue);
  23665. if (newClassString !== oldClassString) {
  23666. ngClassWatchAction(newClassString);
  23667. }
  23668. }
  23669. function ngClassWatchAction(newClassString) {
  23670. if (oldModulo === selector) {
  23671. updateClasses(oldClassString, newClassString);
  23672. }
  23673. oldClassString = newClassString;
  23674. }
  23675. }
  23676. };
  23677. }];
  23678. // Helpers
  23679. function arrayDifference(tokens1, tokens2) {
  23680. if (!tokens1 || !tokens1.length) return [];
  23681. if (!tokens2 || !tokens2.length) return tokens1;
  23682. var values = [];
  23683. outer:
  23684. for (var i = 0; i < tokens1.length; i++) {
  23685. var token = tokens1[i];
  23686. for (var j = 0; j < tokens2.length; j++) {
  23687. if (token === tokens2[j]) continue outer;
  23688. }
  23689. values.push(token);
  23690. }
  23691. return values;
  23692. }
  23693. function split(classString) {
  23694. return classString && classString.split(' ');
  23695. }
  23696. function toClassString(classValue) {
  23697. var classString = classValue;
  23698. if (isArray(classValue)) {
  23699. classString = classValue.map(toClassString).join(' ');
  23700. } else if (isObject(classValue)) {
  23701. classString = Object.keys(classValue).
  23702. filter(function(key) { return classValue[key]; }).
  23703. join(' ');
  23704. }
  23705. return classString;
  23706. }
  23707. function toFlatValue(classValue) {
  23708. var flatValue = classValue;
  23709. if (isArray(classValue)) {
  23710. flatValue = classValue.map(toFlatValue);
  23711. } else if (isObject(classValue)) {
  23712. var hasUndefined = false;
  23713. flatValue = Object.keys(classValue).filter(function(key) {
  23714. var value = classValue[key];
  23715. if (!hasUndefined && isUndefined(value)) {
  23716. hasUndefined = true;
  23717. }
  23718. return value;
  23719. });
  23720. if (hasUndefined) {
  23721. // Prevent the `oneTimeLiteralWatchInterceptor` from unregistering
  23722. // the watcher, by including at least one `undefined` value.
  23723. flatValue.push(undefined);
  23724. }
  23725. }
  23726. return flatValue;
  23727. }
  23728. }
  23729. /**
  23730. * @ngdoc directive
  23731. * @name ngClass
  23732. * @restrict AC
  23733. *
  23734. * @description
  23735. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  23736. * an expression that represents all classes to be added.
  23737. *
  23738. * The directive operates in three different ways, depending on which of three types the expression
  23739. * evaluates to:
  23740. *
  23741. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  23742. * names.
  23743. *
  23744. * 2. If the expression evaluates to an object, then for each key-value pair of the
  23745. * object with a truthy value the corresponding key is used as a class name.
  23746. *
  23747. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  23748. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  23749. * to give you more control over what CSS classes appear. See the code below for an example of this.
  23750. *
  23751. *
  23752. * The directive won't add duplicate classes if a particular class was already set.
  23753. *
  23754. * When the expression changes, the previously added classes are removed and only then are the
  23755. * new classes added.
  23756. *
  23757. * @knownIssue
  23758. * You should not use {@link guide/interpolation interpolation} in the value of the `class`
  23759. * attribute, when using the `ngClass` directive on the same element.
  23760. * See {@link guide/interpolation#known-issues here} for more info.
  23761. *
  23762. * @animations
  23763. * | Animation | Occurs |
  23764. * |----------------------------------|-------------------------------------|
  23765. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  23766. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  23767. *
  23768. * @element ANY
  23769. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  23770. * of the evaluation can be a string representing space delimited class
  23771. * names, an array, or a map of class names to boolean values. In the case of a map, the
  23772. * names of the properties whose values are truthy will be added as css classes to the
  23773. * element.
  23774. *
  23775. * @example Example that demonstrates basic bindings via ngClass directive.
  23776. <example name="ng-class">
  23777. <file name="index.html">
  23778. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  23779. <label>
  23780. <input type="checkbox" ng-model="deleted">
  23781. deleted (apply "strike" class)
  23782. </label><br>
  23783. <label>
  23784. <input type="checkbox" ng-model="important">
  23785. important (apply "bold" class)
  23786. </label><br>
  23787. <label>
  23788. <input type="checkbox" ng-model="error">
  23789. error (apply "has-error" class)
  23790. </label>
  23791. <hr>
  23792. <p ng-class="style">Using String Syntax</p>
  23793. <input type="text" ng-model="style"
  23794. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  23795. <hr>
  23796. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  23797. <input ng-model="style1"
  23798. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  23799. <input ng-model="style2"
  23800. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  23801. <input ng-model="style3"
  23802. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  23803. <hr>
  23804. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  23805. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  23806. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  23807. </file>
  23808. <file name="style.css">
  23809. .strike {
  23810. text-decoration: line-through;
  23811. }
  23812. .bold {
  23813. font-weight: bold;
  23814. }
  23815. .red {
  23816. color: red;
  23817. }
  23818. .has-error {
  23819. color: red;
  23820. background-color: yellow;
  23821. }
  23822. .orange {
  23823. color: orange;
  23824. }
  23825. </file>
  23826. <file name="protractor.js" type="protractor">
  23827. var ps = element.all(by.css('p'));
  23828. it('should let you toggle the class', function() {
  23829. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  23830. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  23831. element(by.model('important')).click();
  23832. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  23833. element(by.model('error')).click();
  23834. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  23835. });
  23836. it('should let you toggle string example', function() {
  23837. expect(ps.get(1).getAttribute('class')).toBe('');
  23838. element(by.model('style')).clear();
  23839. element(by.model('style')).sendKeys('red');
  23840. expect(ps.get(1).getAttribute('class')).toBe('red');
  23841. });
  23842. it('array example should have 3 classes', function() {
  23843. expect(ps.get(2).getAttribute('class')).toBe('');
  23844. element(by.model('style1')).sendKeys('bold');
  23845. element(by.model('style2')).sendKeys('strike');
  23846. element(by.model('style3')).sendKeys('red');
  23847. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  23848. });
  23849. it('array with map example should have 2 classes', function() {
  23850. expect(ps.last().getAttribute('class')).toBe('');
  23851. element(by.model('style4')).sendKeys('bold');
  23852. element(by.model('warning')).click();
  23853. expect(ps.last().getAttribute('class')).toBe('bold orange');
  23854. });
  23855. </file>
  23856. </example>
  23857. ## Animations
  23858. The example below demonstrates how to perform animations using ngClass.
  23859. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
  23860. <file name="index.html">
  23861. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  23862. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  23863. <br>
  23864. <span class="base-class" ng-class="myVar">Sample Text</span>
  23865. </file>
  23866. <file name="style.css">
  23867. .base-class {
  23868. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  23869. }
  23870. .base-class.my-class {
  23871. color: red;
  23872. font-size:3em;
  23873. }
  23874. </file>
  23875. <file name="protractor.js" type="protractor">
  23876. it('should check ng-class', function() {
  23877. expect(element(by.css('.base-class')).getAttribute('class')).not.
  23878. toMatch(/my-class/);
  23879. element(by.id('setbtn')).click();
  23880. expect(element(by.css('.base-class')).getAttribute('class')).
  23881. toMatch(/my-class/);
  23882. element(by.id('clearbtn')).click();
  23883. expect(element(by.css('.base-class')).getAttribute('class')).not.
  23884. toMatch(/my-class/);
  23885. });
  23886. </file>
  23887. </example>
  23888. ## ngClass and pre-existing CSS3 Transitions/Animations
  23889. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  23890. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  23891. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  23892. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  23893. {@link $animate#removeClass $animate.removeClass}.
  23894. */
  23895. var ngClassDirective = classDirective('', true);
  23896. /**
  23897. * @ngdoc directive
  23898. * @name ngClassOdd
  23899. * @restrict AC
  23900. *
  23901. * @description
  23902. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  23903. * {@link ng.directive:ngClass ngClass}, except they work in
  23904. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  23905. *
  23906. * This directive can be applied only within the scope of an
  23907. * {@link ng.directive:ngRepeat ngRepeat}.
  23908. *
  23909. * @element ANY
  23910. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  23911. * of the evaluation can be a string representing space delimited class names or an array.
  23912. *
  23913. * @example
  23914. <example name="ng-class-odd">
  23915. <file name="index.html">
  23916. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  23917. <li ng-repeat="name in names">
  23918. <span ng-class-odd="'odd'" ng-class-even="'even'">
  23919. {{name}}
  23920. </span>
  23921. </li>
  23922. </ol>
  23923. </file>
  23924. <file name="style.css">
  23925. .odd {
  23926. color: red;
  23927. }
  23928. .even {
  23929. color: blue;
  23930. }
  23931. </file>
  23932. <file name="protractor.js" type="protractor">
  23933. it('should check ng-class-odd and ng-class-even', function() {
  23934. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  23935. toMatch(/odd/);
  23936. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  23937. toMatch(/even/);
  23938. });
  23939. </file>
  23940. </example>
  23941. */
  23942. var ngClassOddDirective = classDirective('Odd', 0);
  23943. /**
  23944. * @ngdoc directive
  23945. * @name ngClassEven
  23946. * @restrict AC
  23947. *
  23948. * @description
  23949. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  23950. * {@link ng.directive:ngClass ngClass}, except they work in
  23951. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  23952. *
  23953. * This directive can be applied only within the scope of an
  23954. * {@link ng.directive:ngRepeat ngRepeat}.
  23955. *
  23956. * @element ANY
  23957. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  23958. * result of the evaluation can be a string representing space delimited class names or an array.
  23959. *
  23960. * @example
  23961. <example name="ng-class-even">
  23962. <file name="index.html">
  23963. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  23964. <li ng-repeat="name in names">
  23965. <span ng-class-odd="'odd'" ng-class-even="'even'">
  23966. {{name}} &nbsp; &nbsp; &nbsp;
  23967. </span>
  23968. </li>
  23969. </ol>
  23970. </file>
  23971. <file name="style.css">
  23972. .odd {
  23973. color: red;
  23974. }
  23975. .even {
  23976. color: blue;
  23977. }
  23978. </file>
  23979. <file name="protractor.js" type="protractor">
  23980. it('should check ng-class-odd and ng-class-even', function() {
  23981. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  23982. toMatch(/odd/);
  23983. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  23984. toMatch(/even/);
  23985. });
  23986. </file>
  23987. </example>
  23988. */
  23989. var ngClassEvenDirective = classDirective('Even', 1);
  23990. /**
  23991. * @ngdoc directive
  23992. * @name ngCloak
  23993. * @restrict AC
  23994. *
  23995. * @description
  23996. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  23997. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  23998. * directive to avoid the undesirable flicker effect caused by the html template display.
  23999. *
  24000. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  24001. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  24002. * of the browser view.
  24003. *
  24004. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  24005. * `angular.min.js`.
  24006. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24007. *
  24008. * ```css
  24009. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  24010. * display: none !important;
  24011. * }
  24012. * ```
  24013. *
  24014. * When this css rule is loaded by the browser, all html elements (including their children) that
  24015. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  24016. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  24017. * the compiled element visible.
  24018. *
  24019. * For the best result, the `angular.js` script must be loaded in the head section of the html
  24020. * document; alternatively, the css rule above must be included in the external stylesheet of the
  24021. * application.
  24022. *
  24023. * @element ANY
  24024. *
  24025. * @example
  24026. <example name="ng-cloak">
  24027. <file name="index.html">
  24028. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  24029. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  24030. </file>
  24031. <file name="protractor.js" type="protractor">
  24032. it('should remove the template directive and css class', function() {
  24033. expect($('#template1').getAttribute('ng-cloak')).
  24034. toBeNull();
  24035. expect($('#template2').getAttribute('ng-cloak')).
  24036. toBeNull();
  24037. });
  24038. </file>
  24039. </example>
  24040. *
  24041. */
  24042. var ngCloakDirective = ngDirective({
  24043. compile: function(element, attr) {
  24044. attr.$set('ngCloak', undefined);
  24045. element.removeClass('ng-cloak');
  24046. }
  24047. });
  24048. /**
  24049. * @ngdoc directive
  24050. * @name ngController
  24051. *
  24052. * @description
  24053. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  24054. * supports the principles behind the Model-View-Controller design pattern.
  24055. *
  24056. * MVC components in angular:
  24057. *
  24058. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  24059. * are accessed through bindings.
  24060. * * View — The template (HTML with data bindings) that is rendered into the View.
  24061. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  24062. * logic behind the application to decorate the scope with functions and values
  24063. *
  24064. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  24065. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  24066. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  24067. * and executed twice.
  24068. *
  24069. * @element ANY
  24070. * @scope
  24071. * @priority 500
  24072. * @param {expression} ngController Name of a constructor function registered with the current
  24073. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  24074. * that on the current scope evaluates to a constructor function.
  24075. *
  24076. * The controller instance can be published into a scope property by specifying
  24077. * `ng-controller="as propertyName"`.
  24078. *
  24079. * If the current `$controllerProvider` is configured to use globals (via
  24080. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  24081. * also be the name of a globally accessible constructor function (deprecated, not recommended).
  24082. *
  24083. * @example
  24084. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  24085. * greeting are methods declared on the controller (see source tab). These methods can
  24086. * easily be called from the angular markup. Any changes to the data are automatically reflected
  24087. * in the View without the need for a manual update.
  24088. *
  24089. * Two different declaration styles are included below:
  24090. *
  24091. * * one binds methods and properties directly onto the controller using `this`:
  24092. * `ng-controller="SettingsController1 as settings"`
  24093. * * one injects `$scope` into the controller:
  24094. * `ng-controller="SettingsController2"`
  24095. *
  24096. * The second option is more common in the Angular community, and is generally used in boilerplates
  24097. * and in this guide. However, there are advantages to binding properties directly to the controller
  24098. * and avoiding scope.
  24099. *
  24100. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  24101. * multiple controllers apply to an element.
  24102. * * If you are writing your controllers as classes you have easier access to the properties and
  24103. * methods, which will appear on the scope, from inside the controller code.
  24104. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  24105. * inheritance masking primitives.
  24106. *
  24107. * This example demonstrates the `controller as` syntax.
  24108. *
  24109. * <example name="ngControllerAs" module="controllerAsExample">
  24110. * <file name="index.html">
  24111. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  24112. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  24113. * <button ng-click="settings.greet()">greet</button><br/>
  24114. * Contact:
  24115. * <ul>
  24116. * <li ng-repeat="contact in settings.contacts">
  24117. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  24118. * <option>phone</option>
  24119. * <option>email</option>
  24120. * </select>
  24121. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24122. * <button ng-click="settings.clearContact(contact)">clear</button>
  24123. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  24124. * </li>
  24125. * <li><button ng-click="settings.addContact()">add</button></li>
  24126. * </ul>
  24127. * </div>
  24128. * </file>
  24129. * <file name="app.js">
  24130. * angular.module('controllerAsExample', [])
  24131. * .controller('SettingsController1', SettingsController1);
  24132. *
  24133. * function SettingsController1() {
  24134. * this.name = 'John Smith';
  24135. * this.contacts = [
  24136. * {type: 'phone', value: '408 555 1212'},
  24137. * {type: 'email', value: 'john.smith@example.org'}
  24138. * ];
  24139. * }
  24140. *
  24141. * SettingsController1.prototype.greet = function() {
  24142. * alert(this.name);
  24143. * };
  24144. *
  24145. * SettingsController1.prototype.addContact = function() {
  24146. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  24147. * };
  24148. *
  24149. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  24150. * var index = this.contacts.indexOf(contactToRemove);
  24151. * this.contacts.splice(index, 1);
  24152. * };
  24153. *
  24154. * SettingsController1.prototype.clearContact = function(contact) {
  24155. * contact.type = 'phone';
  24156. * contact.value = '';
  24157. * };
  24158. * </file>
  24159. * <file name="protractor.js" type="protractor">
  24160. * it('should check controller as', function() {
  24161. * var container = element(by.id('ctrl-as-exmpl'));
  24162. * expect(container.element(by.model('settings.name'))
  24163. * .getAttribute('value')).toBe('John Smith');
  24164. *
  24165. * var firstRepeat =
  24166. * container.element(by.repeater('contact in settings.contacts').row(0));
  24167. * var secondRepeat =
  24168. * container.element(by.repeater('contact in settings.contacts').row(1));
  24169. *
  24170. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24171. * .toBe('408 555 1212');
  24172. *
  24173. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24174. * .toBe('john.smith@example.org');
  24175. *
  24176. * firstRepeat.element(by.buttonText('clear')).click();
  24177. *
  24178. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24179. * .toBe('');
  24180. *
  24181. * container.element(by.buttonText('add')).click();
  24182. *
  24183. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  24184. * .element(by.model('contact.value'))
  24185. * .getAttribute('value'))
  24186. * .toBe('yourname@example.org');
  24187. * });
  24188. * </file>
  24189. * </example>
  24190. *
  24191. * This example demonstrates the "attach to `$scope`" style of controller.
  24192. *
  24193. * <example name="ngController" module="controllerExample">
  24194. * <file name="index.html">
  24195. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  24196. * <label>Name: <input type="text" ng-model="name"/></label>
  24197. * <button ng-click="greet()">greet</button><br/>
  24198. * Contact:
  24199. * <ul>
  24200. * <li ng-repeat="contact in contacts">
  24201. * <select ng-model="contact.type" id="select_{{$index}}">
  24202. * <option>phone</option>
  24203. * <option>email</option>
  24204. * </select>
  24205. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24206. * <button ng-click="clearContact(contact)">clear</button>
  24207. * <button ng-click="removeContact(contact)">X</button>
  24208. * </li>
  24209. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  24210. * </ul>
  24211. * </div>
  24212. * </file>
  24213. * <file name="app.js">
  24214. * angular.module('controllerExample', [])
  24215. * .controller('SettingsController2', ['$scope', SettingsController2]);
  24216. *
  24217. * function SettingsController2($scope) {
  24218. * $scope.name = 'John Smith';
  24219. * $scope.contacts = [
  24220. * {type:'phone', value:'408 555 1212'},
  24221. * {type:'email', value:'john.smith@example.org'}
  24222. * ];
  24223. *
  24224. * $scope.greet = function() {
  24225. * alert($scope.name);
  24226. * };
  24227. *
  24228. * $scope.addContact = function() {
  24229. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  24230. * };
  24231. *
  24232. * $scope.removeContact = function(contactToRemove) {
  24233. * var index = $scope.contacts.indexOf(contactToRemove);
  24234. * $scope.contacts.splice(index, 1);
  24235. * };
  24236. *
  24237. * $scope.clearContact = function(contact) {
  24238. * contact.type = 'phone';
  24239. * contact.value = '';
  24240. * };
  24241. * }
  24242. * </file>
  24243. * <file name="protractor.js" type="protractor">
  24244. * it('should check controller', function() {
  24245. * var container = element(by.id('ctrl-exmpl'));
  24246. *
  24247. * expect(container.element(by.model('name'))
  24248. * .getAttribute('value')).toBe('John Smith');
  24249. *
  24250. * var firstRepeat =
  24251. * container.element(by.repeater('contact in contacts').row(0));
  24252. * var secondRepeat =
  24253. * container.element(by.repeater('contact in contacts').row(1));
  24254. *
  24255. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24256. * .toBe('408 555 1212');
  24257. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24258. * .toBe('john.smith@example.org');
  24259. *
  24260. * firstRepeat.element(by.buttonText('clear')).click();
  24261. *
  24262. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24263. * .toBe('');
  24264. *
  24265. * container.element(by.buttonText('add')).click();
  24266. *
  24267. * expect(container.element(by.repeater('contact in contacts').row(2))
  24268. * .element(by.model('contact.value'))
  24269. * .getAttribute('value'))
  24270. * .toBe('yourname@example.org');
  24271. * });
  24272. * </file>
  24273. *</example>
  24274. */
  24275. var ngControllerDirective = [function() {
  24276. return {
  24277. restrict: 'A',
  24278. scope: true,
  24279. controller: '@',
  24280. priority: 500
  24281. };
  24282. }];
  24283. /**
  24284. * @ngdoc directive
  24285. * @name ngCsp
  24286. *
  24287. * @restrict A
  24288. * @element ANY
  24289. * @description
  24290. *
  24291. * Angular has some features that can conflict with certain restrictions that are applied when using
  24292. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  24293. *
  24294. * If you intend to implement CSP with these rules then you must tell Angular not to use these
  24295. * features.
  24296. *
  24297. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  24298. *
  24299. *
  24300. * The following default rules in CSP affect Angular:
  24301. *
  24302. * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute
  24303. * code from strings is forbidden. Angular makes use of this in the {@link $parse} service to
  24304. * provide a 30% increase in the speed of evaluating Angular expressions. (This CSP rule can be
  24305. * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would
  24306. * weaken the protections offered by CSP.)
  24307. *
  24308. * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden.
  24309. * This prevents apps from injecting custom styles directly into the document. Angular makes use of
  24310. * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these
  24311. * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css`
  24312. * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but
  24313. * it is generally not recommended as it would weaken the protections offered by CSP.)
  24314. *
  24315. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking dynamic code
  24316. * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically
  24317. * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a
  24318. * CSP error to be logged in the console:
  24319. *
  24320. * ```
  24321. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  24322. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  24323. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  24324. * ```
  24325. *
  24326. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  24327. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  24328. * the `angular.js` file.
  24329. *
  24330. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  24331. *
  24332. * You can specify which of the CSP related Angular features should be deactivated by providing
  24333. * a value for the `ng-csp` attribute. The options are as follows:
  24334. *
  24335. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  24336. *
  24337. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  24338. *
  24339. * You can use these values in the following combinations:
  24340. *
  24341. *
  24342. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  24343. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous
  24344. * versions of Angular.
  24345. *
  24346. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  24347. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous
  24348. * versions of Angular.
  24349. *
  24350. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can
  24351. * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  24352. *
  24353. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  24354. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  24355. *
  24356. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  24357. * styles nor use eval, which is the same as an empty: ng-csp.
  24358. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  24359. *
  24360. * @example
  24361. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  24362. ```html
  24363. <!doctype html>
  24364. <html ng-app ng-csp>
  24365. ...
  24366. ...
  24367. </html>
  24368. ```
  24369. * @example
  24370. <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! -->
  24371. <example name="example.csp" module="cspExample" ng-csp="true">
  24372. <file name="index.html">
  24373. <div ng-controller="MainController as ctrl">
  24374. <div>
  24375. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  24376. <span id="counter">
  24377. {{ctrl.counter}}
  24378. </span>
  24379. </div>
  24380. <div>
  24381. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  24382. <span id="evilError">
  24383. {{ctrl.evilError}}
  24384. </span>
  24385. </div>
  24386. </div>
  24387. </file>
  24388. <file name="script.js">
  24389. angular.module('cspExample', [])
  24390. .controller('MainController', function MainController() {
  24391. this.counter = 0;
  24392. this.inc = function() {
  24393. this.counter++;
  24394. };
  24395. this.evil = function() {
  24396. try {
  24397. eval('1+2'); // eslint-disable-line no-eval
  24398. } catch (e) {
  24399. this.evilError = e.message;
  24400. }
  24401. };
  24402. });
  24403. </file>
  24404. <file name="protractor.js" type="protractor">
  24405. var util, webdriver;
  24406. var incBtn = element(by.id('inc'));
  24407. var counter = element(by.id('counter'));
  24408. var evilBtn = element(by.id('evil'));
  24409. var evilError = element(by.id('evilError'));
  24410. function getAndClearSevereErrors() {
  24411. return browser.manage().logs().get('browser').then(function(browserLog) {
  24412. return browserLog.filter(function(logEntry) {
  24413. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  24414. });
  24415. });
  24416. }
  24417. function clearErrors() {
  24418. getAndClearSevereErrors();
  24419. }
  24420. function expectNoErrors() {
  24421. getAndClearSevereErrors().then(function(filteredLog) {
  24422. expect(filteredLog.length).toEqual(0);
  24423. if (filteredLog.length) {
  24424. console.log('browser console errors: ' + util.inspect(filteredLog));
  24425. }
  24426. });
  24427. }
  24428. function expectError(regex) {
  24429. getAndClearSevereErrors().then(function(filteredLog) {
  24430. var found = false;
  24431. filteredLog.forEach(function(log) {
  24432. if (log.message.match(regex)) {
  24433. found = true;
  24434. }
  24435. });
  24436. if (!found) {
  24437. throw new Error('expected an error that matches ' + regex);
  24438. }
  24439. });
  24440. }
  24441. beforeEach(function() {
  24442. util = require('util');
  24443. webdriver = require('selenium-webdriver');
  24444. });
  24445. // For now, we only test on Chrome,
  24446. // as Safari does not load the page with Protractor's injected scripts,
  24447. // and Firefox webdriver always disables content security policy (#6358)
  24448. if (browser.params.browser !== 'chrome') {
  24449. return;
  24450. }
  24451. it('should not report errors when the page is loaded', function() {
  24452. // clear errors so we are not dependent on previous tests
  24453. clearErrors();
  24454. // Need to reload the page as the page is already loaded when
  24455. // we come here
  24456. browser.driver.getCurrentUrl().then(function(url) {
  24457. browser.get(url);
  24458. });
  24459. expectNoErrors();
  24460. });
  24461. it('should evaluate expressions', function() {
  24462. expect(counter.getText()).toEqual('0');
  24463. incBtn.click();
  24464. expect(counter.getText()).toEqual('1');
  24465. expectNoErrors();
  24466. });
  24467. it('should throw and report an error when using "eval"', function() {
  24468. evilBtn.click();
  24469. expect(evilError.getText()).toMatch(/Content Security Policy/);
  24470. expectError(/Content Security Policy/);
  24471. });
  24472. </file>
  24473. </example>
  24474. */
  24475. // `ngCsp` is not implemented as a proper directive any more, because we need it be processed while
  24476. // we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()`
  24477. // fn that looks for the `ng-csp` attribute anywhere in the current doc.
  24478. /**
  24479. * @ngdoc directive
  24480. * @name ngClick
  24481. *
  24482. * @description
  24483. * The ngClick directive allows you to specify custom behavior when
  24484. * an element is clicked.
  24485. *
  24486. * @element ANY
  24487. * @priority 0
  24488. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  24489. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  24490. *
  24491. * @example
  24492. <example name="ng-click">
  24493. <file name="index.html">
  24494. <button ng-click="count = count + 1" ng-init="count=0">
  24495. Increment
  24496. </button>
  24497. <span>
  24498. count: {{count}}
  24499. </span>
  24500. </file>
  24501. <file name="protractor.js" type="protractor">
  24502. it('should check ng-click', function() {
  24503. expect(element(by.binding('count')).getText()).toMatch('0');
  24504. element(by.css('button')).click();
  24505. expect(element(by.binding('count')).getText()).toMatch('1');
  24506. });
  24507. </file>
  24508. </example>
  24509. */
  24510. /*
  24511. * A collection of directives that allows creation of custom event handlers that are defined as
  24512. * angular expressions and are compiled and executed within the current scope.
  24513. */
  24514. var ngEventDirectives = {};
  24515. // For events that might fire synchronously during DOM manipulation
  24516. // we need to execute their event handlers asynchronously using $evalAsync,
  24517. // so that they are not executed in an inconsistent state.
  24518. var forceAsyncEvents = {
  24519. 'blur': true,
  24520. 'focus': true
  24521. };
  24522. forEach(
  24523. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  24524. function(eventName) {
  24525. var directiveName = directiveNormalize('ng-' + eventName);
  24526. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  24527. return {
  24528. restrict: 'A',
  24529. compile: function($element, attr) {
  24530. // NOTE:
  24531. // We expose the powerful `$event` object on the scope that provides access to the Window,
  24532. // etc. This is OK, because expressions are not sandboxed any more (and the expression
  24533. // sandbox was never meant to be a security feature anyway).
  24534. var fn = $parse(attr[directiveName]);
  24535. return function ngEventHandler(scope, element) {
  24536. element.on(eventName, function(event) {
  24537. var callback = function() {
  24538. fn(scope, {$event: event});
  24539. };
  24540. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  24541. scope.$evalAsync(callback);
  24542. } else {
  24543. scope.$apply(callback);
  24544. }
  24545. });
  24546. };
  24547. }
  24548. };
  24549. }];
  24550. }
  24551. );
  24552. /**
  24553. * @ngdoc directive
  24554. * @name ngDblclick
  24555. *
  24556. * @description
  24557. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  24558. *
  24559. * @element ANY
  24560. * @priority 0
  24561. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  24562. * a dblclick. (The Event object is available as `$event`)
  24563. *
  24564. * @example
  24565. <example name="ng-dblclick">
  24566. <file name="index.html">
  24567. <button ng-dblclick="count = count + 1" ng-init="count=0">
  24568. Increment (on double click)
  24569. </button>
  24570. count: {{count}}
  24571. </file>
  24572. </example>
  24573. */
  24574. /**
  24575. * @ngdoc directive
  24576. * @name ngMousedown
  24577. *
  24578. * @description
  24579. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  24580. *
  24581. * @element ANY
  24582. * @priority 0
  24583. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  24584. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  24585. *
  24586. * @example
  24587. <example name="ng-mousedown">
  24588. <file name="index.html">
  24589. <button ng-mousedown="count = count + 1" ng-init="count=0">
  24590. Increment (on mouse down)
  24591. </button>
  24592. count: {{count}}
  24593. </file>
  24594. </example>
  24595. */
  24596. /**
  24597. * @ngdoc directive
  24598. * @name ngMouseup
  24599. *
  24600. * @description
  24601. * Specify custom behavior on mouseup event.
  24602. *
  24603. * @element ANY
  24604. * @priority 0
  24605. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  24606. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  24607. *
  24608. * @example
  24609. <example name="ng-mouseup">
  24610. <file name="index.html">
  24611. <button ng-mouseup="count = count + 1" ng-init="count=0">
  24612. Increment (on mouse up)
  24613. </button>
  24614. count: {{count}}
  24615. </file>
  24616. </example>
  24617. */
  24618. /**
  24619. * @ngdoc directive
  24620. * @name ngMouseover
  24621. *
  24622. * @description
  24623. * Specify custom behavior on mouseover event.
  24624. *
  24625. * @element ANY
  24626. * @priority 0
  24627. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  24628. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  24629. *
  24630. * @example
  24631. <example name="ng-mouseover">
  24632. <file name="index.html">
  24633. <button ng-mouseover="count = count + 1" ng-init="count=0">
  24634. Increment (when mouse is over)
  24635. </button>
  24636. count: {{count}}
  24637. </file>
  24638. </example>
  24639. */
  24640. /**
  24641. * @ngdoc directive
  24642. * @name ngMouseenter
  24643. *
  24644. * @description
  24645. * Specify custom behavior on mouseenter event.
  24646. *
  24647. * @element ANY
  24648. * @priority 0
  24649. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  24650. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  24651. *
  24652. * @example
  24653. <example name="ng-mouseenter">
  24654. <file name="index.html">
  24655. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  24656. Increment (when mouse enters)
  24657. </button>
  24658. count: {{count}}
  24659. </file>
  24660. </example>
  24661. */
  24662. /**
  24663. * @ngdoc directive
  24664. * @name ngMouseleave
  24665. *
  24666. * @description
  24667. * Specify custom behavior on mouseleave event.
  24668. *
  24669. * @element ANY
  24670. * @priority 0
  24671. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  24672. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  24673. *
  24674. * @example
  24675. <example name="ng-mouseleave">
  24676. <file name="index.html">
  24677. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  24678. Increment (when mouse leaves)
  24679. </button>
  24680. count: {{count}}
  24681. </file>
  24682. </example>
  24683. */
  24684. /**
  24685. * @ngdoc directive
  24686. * @name ngMousemove
  24687. *
  24688. * @description
  24689. * Specify custom behavior on mousemove event.
  24690. *
  24691. * @element ANY
  24692. * @priority 0
  24693. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  24694. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  24695. *
  24696. * @example
  24697. <example name="ng-mousemove">
  24698. <file name="index.html">
  24699. <button ng-mousemove="count = count + 1" ng-init="count=0">
  24700. Increment (when mouse moves)
  24701. </button>
  24702. count: {{count}}
  24703. </file>
  24704. </example>
  24705. */
  24706. /**
  24707. * @ngdoc directive
  24708. * @name ngKeydown
  24709. *
  24710. * @description
  24711. * Specify custom behavior on keydown event.
  24712. *
  24713. * @element ANY
  24714. * @priority 0
  24715. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  24716. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  24717. *
  24718. * @example
  24719. <example name="ng-keydown">
  24720. <file name="index.html">
  24721. <input ng-keydown="count = count + 1" ng-init="count=0">
  24722. key down count: {{count}}
  24723. </file>
  24724. </example>
  24725. */
  24726. /**
  24727. * @ngdoc directive
  24728. * @name ngKeyup
  24729. *
  24730. * @description
  24731. * Specify custom behavior on keyup event.
  24732. *
  24733. * @element ANY
  24734. * @priority 0
  24735. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  24736. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  24737. *
  24738. * @example
  24739. <example name="ng-keyup">
  24740. <file name="index.html">
  24741. <p>Typing in the input box below updates the key count</p>
  24742. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  24743. <p>Typing in the input box below updates the keycode</p>
  24744. <input ng-keyup="event=$event">
  24745. <p>event keyCode: {{ event.keyCode }}</p>
  24746. <p>event altKey: {{ event.altKey }}</p>
  24747. </file>
  24748. </example>
  24749. */
  24750. /**
  24751. * @ngdoc directive
  24752. * @name ngKeypress
  24753. *
  24754. * @description
  24755. * Specify custom behavior on keypress event.
  24756. *
  24757. * @element ANY
  24758. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  24759. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  24760. * and can be interrogated for keyCode, altKey, etc.)
  24761. *
  24762. * @example
  24763. <example name="ng-keypress">
  24764. <file name="index.html">
  24765. <input ng-keypress="count = count + 1" ng-init="count=0">
  24766. key press count: {{count}}
  24767. </file>
  24768. </example>
  24769. */
  24770. /**
  24771. * @ngdoc directive
  24772. * @name ngSubmit
  24773. *
  24774. * @description
  24775. * Enables binding angular expressions to onsubmit events.
  24776. *
  24777. * Additionally it prevents the default action (which for form means sending the request to the
  24778. * server and reloading the current page), but only if the form does not contain `action`,
  24779. * `data-action`, or `x-action` attributes.
  24780. *
  24781. * <div class="alert alert-warning">
  24782. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  24783. * `ngSubmit` handlers together. See the
  24784. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  24785. * for a detailed discussion of when `ngSubmit` may be triggered.
  24786. * </div>
  24787. *
  24788. * @element form
  24789. * @priority 0
  24790. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  24791. * ({@link guide/expression#-event- Event object is available as `$event`})
  24792. *
  24793. * @example
  24794. <example module="submitExample" name="ng-submit">
  24795. <file name="index.html">
  24796. <script>
  24797. angular.module('submitExample', [])
  24798. .controller('ExampleController', ['$scope', function($scope) {
  24799. $scope.list = [];
  24800. $scope.text = 'hello';
  24801. $scope.submit = function() {
  24802. if ($scope.text) {
  24803. $scope.list.push(this.text);
  24804. $scope.text = '';
  24805. }
  24806. };
  24807. }]);
  24808. </script>
  24809. <form ng-submit="submit()" ng-controller="ExampleController">
  24810. Enter text and hit enter:
  24811. <input type="text" ng-model="text" name="text" />
  24812. <input type="submit" id="submit" value="Submit" />
  24813. <pre>list={{list}}</pre>
  24814. </form>
  24815. </file>
  24816. <file name="protractor.js" type="protractor">
  24817. it('should check ng-submit', function() {
  24818. expect(element(by.binding('list')).getText()).toBe('list=[]');
  24819. element(by.css('#submit')).click();
  24820. expect(element(by.binding('list')).getText()).toContain('hello');
  24821. expect(element(by.model('text')).getAttribute('value')).toBe('');
  24822. });
  24823. it('should ignore empty strings', function() {
  24824. expect(element(by.binding('list')).getText()).toBe('list=[]');
  24825. element(by.css('#submit')).click();
  24826. element(by.css('#submit')).click();
  24827. expect(element(by.binding('list')).getText()).toContain('hello');
  24828. });
  24829. </file>
  24830. </example>
  24831. */
  24832. /**
  24833. * @ngdoc directive
  24834. * @name ngFocus
  24835. *
  24836. * @description
  24837. * Specify custom behavior on focus event.
  24838. *
  24839. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  24840. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  24841. * during an `$apply` to ensure a consistent state.
  24842. *
  24843. * @element window, input, select, textarea, a
  24844. * @priority 0
  24845. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  24846. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  24847. *
  24848. * @example
  24849. * See {@link ng.directive:ngClick ngClick}
  24850. */
  24851. /**
  24852. * @ngdoc directive
  24853. * @name ngBlur
  24854. *
  24855. * @description
  24856. * Specify custom behavior on blur event.
  24857. *
  24858. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  24859. * an element has lost focus.
  24860. *
  24861. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  24862. * (e.g. removing a focussed input),
  24863. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  24864. * during an `$apply` to ensure a consistent state.
  24865. *
  24866. * @element window, input, select, textarea, a
  24867. * @priority 0
  24868. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  24869. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  24870. *
  24871. * @example
  24872. * See {@link ng.directive:ngClick ngClick}
  24873. */
  24874. /**
  24875. * @ngdoc directive
  24876. * @name ngCopy
  24877. *
  24878. * @description
  24879. * Specify custom behavior on copy event.
  24880. *
  24881. * @element window, input, select, textarea, a
  24882. * @priority 0
  24883. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  24884. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  24885. *
  24886. * @example
  24887. <example name="ng-copy">
  24888. <file name="index.html">
  24889. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  24890. copied: {{copied}}
  24891. </file>
  24892. </example>
  24893. */
  24894. /**
  24895. * @ngdoc directive
  24896. * @name ngCut
  24897. *
  24898. * @description
  24899. * Specify custom behavior on cut event.
  24900. *
  24901. * @element window, input, select, textarea, a
  24902. * @priority 0
  24903. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  24904. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  24905. *
  24906. * @example
  24907. <example name="ng-cut">
  24908. <file name="index.html">
  24909. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  24910. cut: {{cut}}
  24911. </file>
  24912. </example>
  24913. */
  24914. /**
  24915. * @ngdoc directive
  24916. * @name ngPaste
  24917. *
  24918. * @description
  24919. * Specify custom behavior on paste event.
  24920. *
  24921. * @element window, input, select, textarea, a
  24922. * @priority 0
  24923. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  24924. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  24925. *
  24926. * @example
  24927. <example name="ng-paste">
  24928. <file name="index.html">
  24929. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  24930. pasted: {{paste}}
  24931. </file>
  24932. </example>
  24933. */
  24934. /**
  24935. * @ngdoc directive
  24936. * @name ngIf
  24937. * @restrict A
  24938. * @multiElement
  24939. *
  24940. * @description
  24941. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  24942. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  24943. * value then the element is removed from the DOM, otherwise a clone of the
  24944. * element is reinserted into the DOM.
  24945. *
  24946. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  24947. * element in the DOM rather than changing its visibility via the `display` css property. A common
  24948. * case when this difference is significant is when using css selectors that rely on an element's
  24949. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  24950. *
  24951. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  24952. * is created when the element is restored. The scope created within `ngIf` inherits from
  24953. * its parent scope using
  24954. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  24955. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  24956. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  24957. * variable within the child scope will override (hide) the value in the parent scope.
  24958. *
  24959. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  24960. * is if an element's class attribute is directly modified after it's compiled, using something like
  24961. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  24962. * the added class will be lost because the original compiled state is used to regenerate the element.
  24963. *
  24964. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  24965. * and `leave` effects.
  24966. *
  24967. * @animations
  24968. * | Animation | Occurs |
  24969. * |----------------------------------|-------------------------------------|
  24970. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  24971. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  24972. *
  24973. * @element ANY
  24974. * @scope
  24975. * @priority 600
  24976. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  24977. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  24978. * element is added to the DOM tree.
  24979. *
  24980. * @example
  24981. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
  24982. <file name="index.html">
  24983. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  24984. Show when checked:
  24985. <span ng-if="checked" class="animate-if">
  24986. This is removed when the checkbox is unchecked.
  24987. </span>
  24988. </file>
  24989. <file name="animations.css">
  24990. .animate-if {
  24991. background:white;
  24992. border:1px solid black;
  24993. padding:10px;
  24994. }
  24995. .animate-if.ng-enter, .animate-if.ng-leave {
  24996. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24997. }
  24998. .animate-if.ng-enter,
  24999. .animate-if.ng-leave.ng-leave-active {
  25000. opacity:0;
  25001. }
  25002. .animate-if.ng-leave,
  25003. .animate-if.ng-enter.ng-enter-active {
  25004. opacity:1;
  25005. }
  25006. </file>
  25007. </example>
  25008. */
  25009. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  25010. return {
  25011. multiElement: true,
  25012. transclude: 'element',
  25013. priority: 600,
  25014. terminal: true,
  25015. restrict: 'A',
  25016. $$tlb: true,
  25017. link: function($scope, $element, $attr, ctrl, $transclude) {
  25018. var block, childScope, previousElements;
  25019. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  25020. if (value) {
  25021. if (!childScope) {
  25022. $transclude(function(clone, newScope) {
  25023. childScope = newScope;
  25024. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  25025. // Note: We only need the first/last node of the cloned nodes.
  25026. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  25027. // by a directive with templateUrl when its template arrives.
  25028. block = {
  25029. clone: clone
  25030. };
  25031. $animate.enter(clone, $element.parent(), $element);
  25032. });
  25033. }
  25034. } else {
  25035. if (previousElements) {
  25036. previousElements.remove();
  25037. previousElements = null;
  25038. }
  25039. if (childScope) {
  25040. childScope.$destroy();
  25041. childScope = null;
  25042. }
  25043. if (block) {
  25044. previousElements = getBlockNodes(block.clone);
  25045. $animate.leave(previousElements).done(function(response) {
  25046. if (response !== false) previousElements = null;
  25047. });
  25048. block = null;
  25049. }
  25050. }
  25051. });
  25052. }
  25053. };
  25054. }];
  25055. /**
  25056. * @ngdoc directive
  25057. * @name ngInclude
  25058. * @restrict ECA
  25059. *
  25060. * @description
  25061. * Fetches, compiles and includes an external HTML fragment.
  25062. *
  25063. * By default, the template URL is restricted to the same domain and protocol as the
  25064. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  25065. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  25066. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  25067. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  25068. * ng.$sce Strict Contextual Escaping}.
  25069. *
  25070. * In addition, the browser's
  25071. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  25072. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  25073. * policy may further restrict whether the template is successfully loaded.
  25074. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  25075. * access on some browsers.
  25076. *
  25077. * @animations
  25078. * | Animation | Occurs |
  25079. * |----------------------------------|-------------------------------------|
  25080. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  25081. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  25082. *
  25083. * The enter and leave animation occur concurrently.
  25084. *
  25085. * @scope
  25086. * @priority 400
  25087. *
  25088. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  25089. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  25090. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  25091. * <div class="alert alert-warning">
  25092. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  25093. * a function with the name on the window element, which will usually throw a
  25094. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  25095. * different form that {@link guide/directive#normalization matches} `onload`.
  25096. * </div>
  25097. *
  25098. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  25099. * $anchorScroll} to scroll the viewport after the content is loaded.
  25100. *
  25101. * - If the attribute is not set, disable scrolling.
  25102. * - If the attribute is set without value, enable scrolling.
  25103. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  25104. *
  25105. * @example
  25106. <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
  25107. <file name="index.html">
  25108. <div ng-controller="ExampleController">
  25109. <select ng-model="template" ng-options="t.name for t in templates">
  25110. <option value="">(blank)</option>
  25111. </select>
  25112. url of the template: <code>{{template.url}}</code>
  25113. <hr/>
  25114. <div class="slide-animate-container">
  25115. <div class="slide-animate" ng-include="template.url"></div>
  25116. </div>
  25117. </div>
  25118. </file>
  25119. <file name="script.js">
  25120. angular.module('includeExample', ['ngAnimate'])
  25121. .controller('ExampleController', ['$scope', function($scope) {
  25122. $scope.templates =
  25123. [{ name: 'template1.html', url: 'template1.html'},
  25124. { name: 'template2.html', url: 'template2.html'}];
  25125. $scope.template = $scope.templates[0];
  25126. }]);
  25127. </file>
  25128. <file name="template1.html">
  25129. Content of template1.html
  25130. </file>
  25131. <file name="template2.html">
  25132. Content of template2.html
  25133. </file>
  25134. <file name="animations.css">
  25135. .slide-animate-container {
  25136. position:relative;
  25137. background:white;
  25138. border:1px solid black;
  25139. height:40px;
  25140. overflow:hidden;
  25141. }
  25142. .slide-animate {
  25143. padding:10px;
  25144. }
  25145. .slide-animate.ng-enter, .slide-animate.ng-leave {
  25146. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25147. position:absolute;
  25148. top:0;
  25149. left:0;
  25150. right:0;
  25151. bottom:0;
  25152. display:block;
  25153. padding:10px;
  25154. }
  25155. .slide-animate.ng-enter {
  25156. top:-50px;
  25157. }
  25158. .slide-animate.ng-enter.ng-enter-active {
  25159. top:0;
  25160. }
  25161. .slide-animate.ng-leave {
  25162. top:0;
  25163. }
  25164. .slide-animate.ng-leave.ng-leave-active {
  25165. top:50px;
  25166. }
  25167. </file>
  25168. <file name="protractor.js" type="protractor">
  25169. var templateSelect = element(by.model('template'));
  25170. var includeElem = element(by.css('[ng-include]'));
  25171. it('should load template1.html', function() {
  25172. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  25173. });
  25174. it('should load template2.html', function() {
  25175. if (browser.params.browser === 'firefox') {
  25176. // Firefox can't handle using selects
  25177. // See https://github.com/angular/protractor/issues/480
  25178. return;
  25179. }
  25180. templateSelect.click();
  25181. templateSelect.all(by.css('option')).get(2).click();
  25182. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  25183. });
  25184. it('should change to blank', function() {
  25185. if (browser.params.browser === 'firefox') {
  25186. // Firefox can't handle using selects
  25187. return;
  25188. }
  25189. templateSelect.click();
  25190. templateSelect.all(by.css('option')).get(0).click();
  25191. expect(includeElem.isPresent()).toBe(false);
  25192. });
  25193. </file>
  25194. </example>
  25195. */
  25196. /**
  25197. * @ngdoc event
  25198. * @name ngInclude#$includeContentRequested
  25199. * @eventType emit on the scope ngInclude was declared in
  25200. * @description
  25201. * Emitted every time the ngInclude content is requested.
  25202. *
  25203. * @param {Object} angularEvent Synthetic event object.
  25204. * @param {String} src URL of content to load.
  25205. */
  25206. /**
  25207. * @ngdoc event
  25208. * @name ngInclude#$includeContentLoaded
  25209. * @eventType emit on the current ngInclude scope
  25210. * @description
  25211. * Emitted every time the ngInclude content is reloaded.
  25212. *
  25213. * @param {Object} angularEvent Synthetic event object.
  25214. * @param {String} src URL of content to load.
  25215. */
  25216. /**
  25217. * @ngdoc event
  25218. * @name ngInclude#$includeContentError
  25219. * @eventType emit on the scope ngInclude was declared in
  25220. * @description
  25221. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  25222. *
  25223. * @param {Object} angularEvent Synthetic event object.
  25224. * @param {String} src URL of content to load.
  25225. */
  25226. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  25227. function($templateRequest, $anchorScroll, $animate) {
  25228. return {
  25229. restrict: 'ECA',
  25230. priority: 400,
  25231. terminal: true,
  25232. transclude: 'element',
  25233. controller: angular.noop,
  25234. compile: function(element, attr) {
  25235. var srcExp = attr.ngInclude || attr.src,
  25236. onloadExp = attr.onload || '',
  25237. autoScrollExp = attr.autoscroll;
  25238. return function(scope, $element, $attr, ctrl, $transclude) {
  25239. var changeCounter = 0,
  25240. currentScope,
  25241. previousElement,
  25242. currentElement;
  25243. var cleanupLastIncludeContent = function() {
  25244. if (previousElement) {
  25245. previousElement.remove();
  25246. previousElement = null;
  25247. }
  25248. if (currentScope) {
  25249. currentScope.$destroy();
  25250. currentScope = null;
  25251. }
  25252. if (currentElement) {
  25253. $animate.leave(currentElement).done(function(response) {
  25254. if (response !== false) previousElement = null;
  25255. });
  25256. previousElement = currentElement;
  25257. currentElement = null;
  25258. }
  25259. };
  25260. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  25261. var afterAnimation = function(response) {
  25262. if (response !== false && isDefined(autoScrollExp) &&
  25263. (!autoScrollExp || scope.$eval(autoScrollExp))) {
  25264. $anchorScroll();
  25265. }
  25266. };
  25267. var thisChangeId = ++changeCounter;
  25268. if (src) {
  25269. //set the 2nd param to true to ignore the template request error so that the inner
  25270. //contents and scope can be cleaned up.
  25271. $templateRequest(src, true).then(function(response) {
  25272. if (scope.$$destroyed) return;
  25273. if (thisChangeId !== changeCounter) return;
  25274. var newScope = scope.$new();
  25275. ctrl.template = response;
  25276. // Note: This will also link all children of ng-include that were contained in the original
  25277. // html. If that content contains controllers, ... they could pollute/change the scope.
  25278. // However, using ng-include on an element with additional content does not make sense...
  25279. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  25280. // function is called before linking the content, which would apply child
  25281. // directives to non existing elements.
  25282. var clone = $transclude(newScope, function(clone) {
  25283. cleanupLastIncludeContent();
  25284. $animate.enter(clone, null, $element).done(afterAnimation);
  25285. });
  25286. currentScope = newScope;
  25287. currentElement = clone;
  25288. currentScope.$emit('$includeContentLoaded', src);
  25289. scope.$eval(onloadExp);
  25290. }, function() {
  25291. if (scope.$$destroyed) return;
  25292. if (thisChangeId === changeCounter) {
  25293. cleanupLastIncludeContent();
  25294. scope.$emit('$includeContentError', src);
  25295. }
  25296. });
  25297. scope.$emit('$includeContentRequested', src);
  25298. } else {
  25299. cleanupLastIncludeContent();
  25300. ctrl.template = null;
  25301. }
  25302. });
  25303. };
  25304. }
  25305. };
  25306. }];
  25307. // This directive is called during the $transclude call of the first `ngInclude` directive.
  25308. // It will replace and compile the content of the element with the loaded template.
  25309. // We need this directive so that the element content is already filled when
  25310. // the link function of another directive on the same element as ngInclude
  25311. // is called.
  25312. var ngIncludeFillContentDirective = ['$compile',
  25313. function($compile) {
  25314. return {
  25315. restrict: 'ECA',
  25316. priority: -400,
  25317. require: 'ngInclude',
  25318. link: function(scope, $element, $attr, ctrl) {
  25319. if (toString.call($element[0]).match(/SVG/)) {
  25320. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  25321. // support innerHTML, so detect this here and try to generate the contents
  25322. // specially.
  25323. $element.empty();
  25324. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  25325. function namespaceAdaptedClone(clone) {
  25326. $element.append(clone);
  25327. }, {futureParentElement: $element});
  25328. return;
  25329. }
  25330. $element.html(ctrl.template);
  25331. $compile($element.contents())(scope);
  25332. }
  25333. };
  25334. }];
  25335. /**
  25336. * @ngdoc directive
  25337. * @name ngInit
  25338. * @restrict AC
  25339. *
  25340. * @description
  25341. * The `ngInit` directive allows you to evaluate an expression in the
  25342. * current scope.
  25343. *
  25344. * <div class="alert alert-danger">
  25345. * This directive can be abused to add unnecessary amounts of logic into your templates.
  25346. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  25347. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  25348. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  25349. * rather than `ngInit` to initialize values on a scope.
  25350. * </div>
  25351. *
  25352. * <div class="alert alert-warning">
  25353. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  25354. * sure you have parentheses to ensure correct operator precedence:
  25355. * <pre class="prettyprint">
  25356. * `<div ng-init="test1 = ($index | toString)"></div>`
  25357. * </pre>
  25358. * </div>
  25359. *
  25360. * @priority 450
  25361. *
  25362. * @element ANY
  25363. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  25364. *
  25365. * @example
  25366. <example module="initExample" name="ng-init">
  25367. <file name="index.html">
  25368. <script>
  25369. angular.module('initExample', [])
  25370. .controller('ExampleController', ['$scope', function($scope) {
  25371. $scope.list = [['a', 'b'], ['c', 'd']];
  25372. }]);
  25373. </script>
  25374. <div ng-controller="ExampleController">
  25375. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  25376. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  25377. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  25378. </div>
  25379. </div>
  25380. </div>
  25381. </file>
  25382. <file name="protractor.js" type="protractor">
  25383. it('should alias index positions', function() {
  25384. var elements = element.all(by.css('.example-init'));
  25385. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  25386. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  25387. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  25388. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  25389. });
  25390. </file>
  25391. </example>
  25392. */
  25393. var ngInitDirective = ngDirective({
  25394. priority: 450,
  25395. compile: function() {
  25396. return {
  25397. pre: function(scope, element, attrs) {
  25398. scope.$eval(attrs.ngInit);
  25399. }
  25400. };
  25401. }
  25402. });
  25403. /**
  25404. * @ngdoc directive
  25405. * @name ngList
  25406. *
  25407. * @description
  25408. * Text input that converts between a delimited string and an array of strings. The default
  25409. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  25410. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  25411. *
  25412. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  25413. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  25414. * list item is respected. This implies that the user of the directive is responsible for
  25415. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  25416. * tab or newline character.
  25417. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  25418. * when joining the list items back together) and whitespace around each list item is stripped
  25419. * before it is added to the model.
  25420. *
  25421. * ### Example with Validation
  25422. *
  25423. * <example name="ngList-directive" module="listExample">
  25424. * <file name="app.js">
  25425. * angular.module('listExample', [])
  25426. * .controller('ExampleController', ['$scope', function($scope) {
  25427. * $scope.names = ['morpheus', 'neo', 'trinity'];
  25428. * }]);
  25429. * </file>
  25430. * <file name="index.html">
  25431. * <form name="myForm" ng-controller="ExampleController">
  25432. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  25433. * <span role="alert">
  25434. * <span class="error" ng-show="myForm.namesInput.$error.required">
  25435. * Required!</span>
  25436. * </span>
  25437. * <br>
  25438. * <tt>names = {{names}}</tt><br/>
  25439. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  25440. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  25441. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  25442. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  25443. * </form>
  25444. * </file>
  25445. * <file name="protractor.js" type="protractor">
  25446. * var listInput = element(by.model('names'));
  25447. * var names = element(by.exactBinding('names'));
  25448. * var valid = element(by.binding('myForm.namesInput.$valid'));
  25449. * var error = element(by.css('span.error'));
  25450. *
  25451. * it('should initialize to model', function() {
  25452. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  25453. * expect(valid.getText()).toContain('true');
  25454. * expect(error.getCssValue('display')).toBe('none');
  25455. * });
  25456. *
  25457. * it('should be invalid if empty', function() {
  25458. * listInput.clear();
  25459. * listInput.sendKeys('');
  25460. *
  25461. * expect(names.getText()).toContain('');
  25462. * expect(valid.getText()).toContain('false');
  25463. * expect(error.getCssValue('display')).not.toBe('none');
  25464. * });
  25465. * </file>
  25466. * </example>
  25467. *
  25468. * ### Example - splitting on newline
  25469. * <example name="ngList-directive-newlines">
  25470. * <file name="index.html">
  25471. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  25472. * <pre>{{ list | json }}</pre>
  25473. * </file>
  25474. * <file name="protractor.js" type="protractor">
  25475. * it("should split the text by newlines", function() {
  25476. * var listInput = element(by.model('list'));
  25477. * var output = element(by.binding('list | json'));
  25478. * listInput.sendKeys('abc\ndef\nghi');
  25479. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  25480. * });
  25481. * </file>
  25482. * </example>
  25483. *
  25484. * @element input
  25485. * @param {string=} ngList optional delimiter that should be used to split the value.
  25486. */
  25487. var ngListDirective = function() {
  25488. return {
  25489. restrict: 'A',
  25490. priority: 100,
  25491. require: 'ngModel',
  25492. link: function(scope, element, attr, ctrl) {
  25493. var ngList = attr.ngList || ', ';
  25494. var trimValues = attr.ngTrim !== 'false';
  25495. var separator = trimValues ? trim(ngList) : ngList;
  25496. var parse = function(viewValue) {
  25497. // If the viewValue is invalid (say required but empty) it will be `undefined`
  25498. if (isUndefined(viewValue)) return;
  25499. var list = [];
  25500. if (viewValue) {
  25501. forEach(viewValue.split(separator), function(value) {
  25502. if (value) list.push(trimValues ? trim(value) : value);
  25503. });
  25504. }
  25505. return list;
  25506. };
  25507. ctrl.$parsers.push(parse);
  25508. ctrl.$formatters.push(function(value) {
  25509. if (isArray(value)) {
  25510. return value.join(ngList);
  25511. }
  25512. return undefined;
  25513. });
  25514. // Override the standard $isEmpty because an empty array means the input is empty.
  25515. ctrl.$isEmpty = function(value) {
  25516. return !value || !value.length;
  25517. };
  25518. }
  25519. };
  25520. };
  25521. /* global VALID_CLASS: true,
  25522. INVALID_CLASS: true,
  25523. PRISTINE_CLASS: true,
  25524. DIRTY_CLASS: true,
  25525. UNTOUCHED_CLASS: true,
  25526. TOUCHED_CLASS: true,
  25527. PENDING_CLASS: true,
  25528. addSetValidityMethod: true,
  25529. setupValidity: true,
  25530. defaultModelOptions: false
  25531. */
  25532. var VALID_CLASS = 'ng-valid',
  25533. INVALID_CLASS = 'ng-invalid',
  25534. PRISTINE_CLASS = 'ng-pristine',
  25535. DIRTY_CLASS = 'ng-dirty',
  25536. UNTOUCHED_CLASS = 'ng-untouched',
  25537. TOUCHED_CLASS = 'ng-touched',
  25538. EMPTY_CLASS = 'ng-empty',
  25539. NOT_EMPTY_CLASS = 'ng-not-empty';
  25540. var ngModelMinErr = minErr('ngModel');
  25541. /**
  25542. * @ngdoc type
  25543. * @name ngModel.NgModelController
  25544. *
  25545. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  25546. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  25547. * is set.
  25548. *
  25549. * @property {*} $modelValue The value in the model that the control is bound to.
  25550. *
  25551. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  25552. * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue
  25553. `$viewValue`} from the DOM, usually via user input.
  25554. See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation.
  25555. Note that the `$parsers` are not called when the bound ngModel expression changes programmatically.
  25556. The functions are called in array order, each passing
  25557. its return value through to the next. The last return value is forwarded to the
  25558. {@link ngModel.NgModelController#$validators `$validators`} collection.
  25559. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  25560. `$viewValue`}.
  25561. Returning `undefined` from a parser means a parse error occurred. In that case,
  25562. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  25563. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  25564. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  25565. This simple example shows a parser that would convert text input value to lowercase:
  25566. * ```js
  25567. * function parse(value) {
  25568. * if (value) {
  25569. * return value.toLowerCase();
  25570. * }
  25571. * }
  25572. * ngModelController.$parsers.push(parse);
  25573. * ```
  25574. *
  25575. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  25576. the bound ngModel expression changes programmatically. The `$formatters` are not called when the
  25577. value of the control is changed by user interaction.
  25578. Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue
  25579. `$modelValue`} for display in the control.
  25580. The functions are called in reverse array order, each passing the value through to the
  25581. next. The last return value is used as the actual DOM value.
  25582. This simple example shows a formatter that would convert the model value to uppercase:
  25583. * ```js
  25584. * function format(value) {
  25585. * if (value) {
  25586. * return value.toUpperCase();
  25587. * }
  25588. * }
  25589. * ngModel.$formatters.push(format);
  25590. * ```
  25591. *
  25592. * @property {Object.<string, function>} $validators A collection of validators that are applied
  25593. * whenever the model value changes. The key value within the object refers to the name of the
  25594. * validator while the function refers to the validation operation. The validation operation is
  25595. * provided with the model value as an argument and must return a true or false value depending
  25596. * on the response of that validation.
  25597. *
  25598. * ```js
  25599. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  25600. * var value = modelValue || viewValue;
  25601. * return /[0-9]+/.test(value) &&
  25602. * /[a-z]+/.test(value) &&
  25603. * /[A-Z]+/.test(value) &&
  25604. * /\W+/.test(value);
  25605. * };
  25606. * ```
  25607. *
  25608. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  25609. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  25610. * is expected to return a promise when it is run during the model validation process. Once the promise
  25611. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  25612. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  25613. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  25614. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  25615. * will only run once all synchronous validators have passed.
  25616. *
  25617. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  25618. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  25619. *
  25620. * ```js
  25621. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  25622. * var value = modelValue || viewValue;
  25623. *
  25624. * // Lookup user by username
  25625. * return $http.get('/api/users/' + value).
  25626. * then(function resolved() {
  25627. * //username exists, this means validation fails
  25628. * return $q.reject('exists');
  25629. * }, function rejected() {
  25630. * //username does not exist, therefore this validation passes
  25631. * return true;
  25632. * });
  25633. * };
  25634. * ```
  25635. *
  25636. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  25637. * view value has changed. It is called with no arguments, and its return value is ignored.
  25638. * This can be used in place of additional $watches against the model value.
  25639. *
  25640. * @property {Object} $error An object hash with all failing validator ids as keys.
  25641. * @property {Object} $pending An object hash with all pending validator ids as keys.
  25642. *
  25643. * @property {boolean} $untouched True if control has not lost focus yet.
  25644. * @property {boolean} $touched True if control has lost focus.
  25645. * @property {boolean} $pristine True if user has not interacted with the control yet.
  25646. * @property {boolean} $dirty True if user has already interacted with the control.
  25647. * @property {boolean} $valid True if there is no error.
  25648. * @property {boolean} $invalid True if at least one error on the control.
  25649. * @property {string} $name The name attribute of the control.
  25650. *
  25651. * @description
  25652. *
  25653. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  25654. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  25655. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  25656. * listening to DOM events.
  25657. * Such DOM related logic should be provided by other directives which make use of
  25658. * `NgModelController` for data-binding to control elements.
  25659. * Angular provides this DOM logic for most {@link input `input`} elements.
  25660. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  25661. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  25662. *
  25663. * @example
  25664. * ### Custom Control Example
  25665. * This example shows how to use `NgModelController` with a custom control to achieve
  25666. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  25667. * collaborate together to achieve the desired result.
  25668. *
  25669. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  25670. * contents be edited in place by the user.
  25671. *
  25672. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  25673. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  25674. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  25675. * that content using the `$sce` service.
  25676. *
  25677. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  25678. <file name="style.css">
  25679. [contenteditable] {
  25680. border: 1px solid black;
  25681. background-color: white;
  25682. min-height: 20px;
  25683. }
  25684. .ng-invalid {
  25685. border: 1px solid red;
  25686. }
  25687. </file>
  25688. <file name="script.js">
  25689. angular.module('customControl', ['ngSanitize']).
  25690. directive('contenteditable', ['$sce', function($sce) {
  25691. return {
  25692. restrict: 'A', // only activate on element attribute
  25693. require: '?ngModel', // get a hold of NgModelController
  25694. link: function(scope, element, attrs, ngModel) {
  25695. if (!ngModel) return; // do nothing if no ng-model
  25696. // Specify how UI should be updated
  25697. ngModel.$render = function() {
  25698. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  25699. };
  25700. // Listen for change events to enable binding
  25701. element.on('blur keyup change', function() {
  25702. scope.$evalAsync(read);
  25703. });
  25704. read(); // initialize
  25705. // Write data to the model
  25706. function read() {
  25707. var html = element.html();
  25708. // When we clear the content editable the browser leaves a <br> behind
  25709. // If strip-br attribute is provided then we strip this out
  25710. if (attrs.stripBr && html === '<br>') {
  25711. html = '';
  25712. }
  25713. ngModel.$setViewValue(html);
  25714. }
  25715. }
  25716. };
  25717. }]);
  25718. </file>
  25719. <file name="index.html">
  25720. <form name="myForm">
  25721. <div contenteditable
  25722. name="myWidget" ng-model="userContent"
  25723. strip-br="true"
  25724. required>Change me!</div>
  25725. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  25726. <hr>
  25727. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  25728. </form>
  25729. </file>
  25730. <file name="protractor.js" type="protractor">
  25731. it('should data-bind and become invalid', function() {
  25732. if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
  25733. // SafariDriver can't handle contenteditable
  25734. // and Firefox driver can't clear contenteditables very well
  25735. return;
  25736. }
  25737. var contentEditable = element(by.css('[contenteditable]'));
  25738. var content = 'Change me!';
  25739. expect(contentEditable.getText()).toEqual(content);
  25740. contentEditable.clear();
  25741. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  25742. expect(contentEditable.getText()).toEqual('');
  25743. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  25744. });
  25745. </file>
  25746. * </example>
  25747. *
  25748. *
  25749. */
  25750. NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];
  25751. function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {
  25752. this.$viewValue = Number.NaN;
  25753. this.$modelValue = Number.NaN;
  25754. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  25755. this.$validators = {};
  25756. this.$asyncValidators = {};
  25757. this.$parsers = [];
  25758. this.$formatters = [];
  25759. this.$viewChangeListeners = [];
  25760. this.$untouched = true;
  25761. this.$touched = false;
  25762. this.$pristine = true;
  25763. this.$dirty = false;
  25764. this.$valid = true;
  25765. this.$invalid = false;
  25766. this.$error = {}; // keep invalid keys here
  25767. this.$$success = {}; // keep valid keys here
  25768. this.$pending = undefined; // keep pending keys here
  25769. this.$name = $interpolate($attr.name || '', false)($scope);
  25770. this.$$parentForm = nullFormCtrl;
  25771. this.$options = defaultModelOptions;
  25772. this.$$parsedNgModel = $parse($attr.ngModel);
  25773. this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;
  25774. this.$$ngModelGet = this.$$parsedNgModel;
  25775. this.$$ngModelSet = this.$$parsedNgModelAssign;
  25776. this.$$pendingDebounce = null;
  25777. this.$$parserValid = undefined;
  25778. this.$$currentValidationRunId = 0;
  25779. this.$$scope = $scope;
  25780. this.$$attr = $attr;
  25781. this.$$element = $element;
  25782. this.$$animate = $animate;
  25783. this.$$timeout = $timeout;
  25784. this.$$parse = $parse;
  25785. this.$$q = $q;
  25786. this.$$exceptionHandler = $exceptionHandler;
  25787. setupValidity(this);
  25788. setupModelWatcher(this);
  25789. }
  25790. NgModelController.prototype = {
  25791. $$initGetterSetters: function() {
  25792. if (this.$options.getOption('getterSetter')) {
  25793. var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),
  25794. invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');
  25795. this.$$ngModelGet = function($scope) {
  25796. var modelValue = this.$$parsedNgModel($scope);
  25797. if (isFunction(modelValue)) {
  25798. modelValue = invokeModelGetter($scope);
  25799. }
  25800. return modelValue;
  25801. };
  25802. this.$$ngModelSet = function($scope, newValue) {
  25803. if (isFunction(this.$$parsedNgModel($scope))) {
  25804. invokeModelSetter($scope, {$$$p: newValue});
  25805. } else {
  25806. this.$$parsedNgModelAssign($scope, newValue);
  25807. }
  25808. };
  25809. } else if (!this.$$parsedNgModel.assign) {
  25810. throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
  25811. this.$$attr.ngModel, startingTag(this.$$element));
  25812. }
  25813. },
  25814. /**
  25815. * @ngdoc method
  25816. * @name ngModel.NgModelController#$render
  25817. *
  25818. * @description
  25819. * Called when the view needs to be updated. It is expected that the user of the ng-model
  25820. * directive will implement this method.
  25821. *
  25822. * The `$render()` method is invoked in the following situations:
  25823. *
  25824. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  25825. * committed value then `$render()` is called to update the input control.
  25826. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  25827. * the `$viewValue` are different from last time.
  25828. *
  25829. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  25830. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  25831. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  25832. * invoked if you only change a property on the objects.
  25833. */
  25834. $render: noop,
  25835. /**
  25836. * @ngdoc method
  25837. * @name ngModel.NgModelController#$isEmpty
  25838. *
  25839. * @description
  25840. * This is called when we need to determine if the value of an input is empty.
  25841. *
  25842. * For instance, the required directive does this to work out if the input has data or not.
  25843. *
  25844. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  25845. *
  25846. * You can override this for input directives whose concept of being empty is different from the
  25847. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  25848. * implies empty.
  25849. *
  25850. * @param {*} value The value of the input to check for emptiness.
  25851. * @returns {boolean} True if `value` is "empty".
  25852. */
  25853. $isEmpty: function(value) {
  25854. // eslint-disable-next-line no-self-compare
  25855. return isUndefined(value) || value === '' || value === null || value !== value;
  25856. },
  25857. $$updateEmptyClasses: function(value) {
  25858. if (this.$isEmpty(value)) {
  25859. this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);
  25860. this.$$animate.addClass(this.$$element, EMPTY_CLASS);
  25861. } else {
  25862. this.$$animate.removeClass(this.$$element, EMPTY_CLASS);
  25863. this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);
  25864. }
  25865. },
  25866. /**
  25867. * @ngdoc method
  25868. * @name ngModel.NgModelController#$setPristine
  25869. *
  25870. * @description
  25871. * Sets the control to its pristine state.
  25872. *
  25873. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  25874. * state (`ng-pristine` class). A model is considered to be pristine when the control
  25875. * has not been changed from when first compiled.
  25876. */
  25877. $setPristine: function() {
  25878. this.$dirty = false;
  25879. this.$pristine = true;
  25880. this.$$animate.removeClass(this.$$element, DIRTY_CLASS);
  25881. this.$$animate.addClass(this.$$element, PRISTINE_CLASS);
  25882. },
  25883. /**
  25884. * @ngdoc method
  25885. * @name ngModel.NgModelController#$setDirty
  25886. *
  25887. * @description
  25888. * Sets the control to its dirty state.
  25889. *
  25890. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  25891. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  25892. * from when first compiled.
  25893. */
  25894. $setDirty: function() {
  25895. this.$dirty = true;
  25896. this.$pristine = false;
  25897. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  25898. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  25899. this.$$parentForm.$setDirty();
  25900. },
  25901. /**
  25902. * @ngdoc method
  25903. * @name ngModel.NgModelController#$setUntouched
  25904. *
  25905. * @description
  25906. * Sets the control to its untouched state.
  25907. *
  25908. * This method can be called to remove the `ng-touched` class and set the control to its
  25909. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  25910. * by default, however this function can be used to restore that state if the model has
  25911. * already been touched by the user.
  25912. */
  25913. $setUntouched: function() {
  25914. this.$touched = false;
  25915. this.$untouched = true;
  25916. this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  25917. },
  25918. /**
  25919. * @ngdoc method
  25920. * @name ngModel.NgModelController#$setTouched
  25921. *
  25922. * @description
  25923. * Sets the control to its touched state.
  25924. *
  25925. * This method can be called to remove the `ng-untouched` class and set the control to its
  25926. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  25927. * first focused the control element and then shifted focus away from the control (blur event).
  25928. */
  25929. $setTouched: function() {
  25930. this.$touched = true;
  25931. this.$untouched = false;
  25932. this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  25933. },
  25934. /**
  25935. * @ngdoc method
  25936. * @name ngModel.NgModelController#$rollbackViewValue
  25937. *
  25938. * @description
  25939. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  25940. * which may be caused by a pending debounced event or because the input is waiting for some
  25941. * future event.
  25942. *
  25943. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  25944. * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of
  25945. * sync with the ngModel's `$modelValue`.
  25946. *
  25947. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  25948. * and reset the input to the last committed view value.
  25949. *
  25950. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  25951. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  25952. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  25953. *
  25954. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  25955. * input which may have such events pending. This is important in order to make sure that the
  25956. * input field will be updated with the new model value and any pending operations are cancelled.
  25957. *
  25958. * <example name="ng-model-cancel-update" module="cancel-update-example">
  25959. * <file name="app.js">
  25960. * angular.module('cancel-update-example', [])
  25961. *
  25962. * .controller('CancelUpdateController', ['$scope', function($scope) {
  25963. * $scope.model = {value1: '', value2: ''};
  25964. *
  25965. * $scope.setEmpty = function(e, value, rollback) {
  25966. * if (e.keyCode === 27) {
  25967. * e.preventDefault();
  25968. * if (rollback) {
  25969. * $scope.myForm[value].$rollbackViewValue();
  25970. * }
  25971. * $scope.model[value] = '';
  25972. * }
  25973. * };
  25974. * }]);
  25975. * </file>
  25976. * <file name="index.html">
  25977. * <div ng-controller="CancelUpdateController">
  25978. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  25979. * empty them. Follow these steps and observe the difference:</p>
  25980. * <ol>
  25981. * <li>Type something in the input. You will see that the model is not yet updated</li>
  25982. * <li>Press the Escape key.
  25983. * <ol>
  25984. * <li> In the first example, nothing happens, because the model is already '', and no
  25985. * update is detected. If you blur the input, the model will be set to the current view.
  25986. * </li>
  25987. * <li> In the second example, the pending update is cancelled, and the input is set back
  25988. * to the last committed view value (''). Blurring the input does nothing.
  25989. * </li>
  25990. * </ol>
  25991. * </li>
  25992. * </ol>
  25993. *
  25994. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  25995. * <div>
  25996. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  25997. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  25998. * ng-keydown="setEmpty($event, 'value1')">
  25999. * value1: "{{ model.value1 }}"
  26000. * </div>
  26001. *
  26002. * <div>
  26003. * <p id="inputDescription2">With $rollbackViewValue():</p>
  26004. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  26005. * ng-keydown="setEmpty($event, 'value2', true)">
  26006. * value2: "{{ model.value2 }}"
  26007. * </div>
  26008. * </form>
  26009. * </div>
  26010. * </file>
  26011. <file name="style.css">
  26012. div {
  26013. display: table-cell;
  26014. }
  26015. div:nth-child(1) {
  26016. padding-right: 30px;
  26017. }
  26018. </file>
  26019. * </example>
  26020. */
  26021. $rollbackViewValue: function() {
  26022. this.$$timeout.cancel(this.$$pendingDebounce);
  26023. this.$viewValue = this.$$lastCommittedViewValue;
  26024. this.$render();
  26025. },
  26026. /**
  26027. * @ngdoc method
  26028. * @name ngModel.NgModelController#$validate
  26029. *
  26030. * @description
  26031. * Runs each of the registered validators (first synchronous validators and then
  26032. * asynchronous validators).
  26033. * If the validity changes to invalid, the model will be set to `undefined`,
  26034. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  26035. * If the validity changes to valid, it will set the model to the last available valid
  26036. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  26037. */
  26038. $validate: function() {
  26039. // ignore $validate before model is initialized
  26040. if (isNumberNaN(this.$modelValue)) {
  26041. return;
  26042. }
  26043. var viewValue = this.$$lastCommittedViewValue;
  26044. // Note: we use the $$rawModelValue as $modelValue might have been
  26045. // set to undefined during a view -> model update that found validation
  26046. // errors. We can't parse the view here, since that could change
  26047. // the model although neither viewValue nor the model on the scope changed
  26048. var modelValue = this.$$rawModelValue;
  26049. var prevValid = this.$valid;
  26050. var prevModelValue = this.$modelValue;
  26051. var allowInvalid = this.$options.getOption('allowInvalid');
  26052. var that = this;
  26053. this.$$runValidators(modelValue, viewValue, function(allValid) {
  26054. // If there was no change in validity, don't update the model
  26055. // This prevents changing an invalid modelValue to undefined
  26056. if (!allowInvalid && prevValid !== allValid) {
  26057. // Note: Don't check this.$valid here, as we could have
  26058. // external validators (e.g. calculated on the server),
  26059. // that just call $setValidity and need the model value
  26060. // to calculate their validity.
  26061. that.$modelValue = allValid ? modelValue : undefined;
  26062. if (that.$modelValue !== prevModelValue) {
  26063. that.$$writeModelToScope();
  26064. }
  26065. }
  26066. });
  26067. },
  26068. $$runValidators: function(modelValue, viewValue, doneCallback) {
  26069. this.$$currentValidationRunId++;
  26070. var localValidationRunId = this.$$currentValidationRunId;
  26071. var that = this;
  26072. // check parser error
  26073. if (!processParseErrors()) {
  26074. validationDone(false);
  26075. return;
  26076. }
  26077. if (!processSyncValidators()) {
  26078. validationDone(false);
  26079. return;
  26080. }
  26081. processAsyncValidators();
  26082. function processParseErrors() {
  26083. var errorKey = that.$$parserName || 'parse';
  26084. if (isUndefined(that.$$parserValid)) {
  26085. setValidity(errorKey, null);
  26086. } else {
  26087. if (!that.$$parserValid) {
  26088. forEach(that.$validators, function(v, name) {
  26089. setValidity(name, null);
  26090. });
  26091. forEach(that.$asyncValidators, function(v, name) {
  26092. setValidity(name, null);
  26093. });
  26094. }
  26095. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  26096. setValidity(errorKey, that.$$parserValid);
  26097. return that.$$parserValid;
  26098. }
  26099. return true;
  26100. }
  26101. function processSyncValidators() {
  26102. var syncValidatorsValid = true;
  26103. forEach(that.$validators, function(validator, name) {
  26104. var result = Boolean(validator(modelValue, viewValue));
  26105. syncValidatorsValid = syncValidatorsValid && result;
  26106. setValidity(name, result);
  26107. });
  26108. if (!syncValidatorsValid) {
  26109. forEach(that.$asyncValidators, function(v, name) {
  26110. setValidity(name, null);
  26111. });
  26112. return false;
  26113. }
  26114. return true;
  26115. }
  26116. function processAsyncValidators() {
  26117. var validatorPromises = [];
  26118. var allValid = true;
  26119. forEach(that.$asyncValidators, function(validator, name) {
  26120. var promise = validator(modelValue, viewValue);
  26121. if (!isPromiseLike(promise)) {
  26122. throw ngModelMinErr('nopromise',
  26123. 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
  26124. }
  26125. setValidity(name, undefined);
  26126. validatorPromises.push(promise.then(function() {
  26127. setValidity(name, true);
  26128. }, function() {
  26129. allValid = false;
  26130. setValidity(name, false);
  26131. }));
  26132. });
  26133. if (!validatorPromises.length) {
  26134. validationDone(true);
  26135. } else {
  26136. that.$$q.all(validatorPromises).then(function() {
  26137. validationDone(allValid);
  26138. }, noop);
  26139. }
  26140. }
  26141. function setValidity(name, isValid) {
  26142. if (localValidationRunId === that.$$currentValidationRunId) {
  26143. that.$setValidity(name, isValid);
  26144. }
  26145. }
  26146. function validationDone(allValid) {
  26147. if (localValidationRunId === that.$$currentValidationRunId) {
  26148. doneCallback(allValid);
  26149. }
  26150. }
  26151. },
  26152. /**
  26153. * @ngdoc method
  26154. * @name ngModel.NgModelController#$commitViewValue
  26155. *
  26156. * @description
  26157. * Commit a pending update to the `$modelValue`.
  26158. *
  26159. * Updates may be pending by a debounced event or because the input is waiting for a some future
  26160. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  26161. * usually handles calling this in response to input events.
  26162. */
  26163. $commitViewValue: function() {
  26164. var viewValue = this.$viewValue;
  26165. this.$$timeout.cancel(this.$$pendingDebounce);
  26166. // If the view value has not changed then we should just exit, except in the case where there is
  26167. // a native validator on the element. In this case the validation state may have changed even though
  26168. // the viewValue has stayed empty.
  26169. if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {
  26170. return;
  26171. }
  26172. this.$$updateEmptyClasses(viewValue);
  26173. this.$$lastCommittedViewValue = viewValue;
  26174. // change to dirty
  26175. if (this.$pristine) {
  26176. this.$setDirty();
  26177. }
  26178. this.$$parseAndValidate();
  26179. },
  26180. $$parseAndValidate: function() {
  26181. var viewValue = this.$$lastCommittedViewValue;
  26182. var modelValue = viewValue;
  26183. var that = this;
  26184. this.$$parserValid = isUndefined(modelValue) ? undefined : true;
  26185. if (this.$$parserValid) {
  26186. for (var i = 0; i < this.$parsers.length; i++) {
  26187. modelValue = this.$parsers[i](modelValue);
  26188. if (isUndefined(modelValue)) {
  26189. this.$$parserValid = false;
  26190. break;
  26191. }
  26192. }
  26193. }
  26194. if (isNumberNaN(this.$modelValue)) {
  26195. // this.$modelValue has not been touched yet...
  26196. this.$modelValue = this.$$ngModelGet(this.$$scope);
  26197. }
  26198. var prevModelValue = this.$modelValue;
  26199. var allowInvalid = this.$options.getOption('allowInvalid');
  26200. this.$$rawModelValue = modelValue;
  26201. if (allowInvalid) {
  26202. this.$modelValue = modelValue;
  26203. writeToModelIfNeeded();
  26204. }
  26205. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  26206. // This can happen if e.g. $setViewValue is called from inside a parser
  26207. this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {
  26208. if (!allowInvalid) {
  26209. // Note: Don't check this.$valid here, as we could have
  26210. // external validators (e.g. calculated on the server),
  26211. // that just call $setValidity and need the model value
  26212. // to calculate their validity.
  26213. that.$modelValue = allValid ? modelValue : undefined;
  26214. writeToModelIfNeeded();
  26215. }
  26216. });
  26217. function writeToModelIfNeeded() {
  26218. if (that.$modelValue !== prevModelValue) {
  26219. that.$$writeModelToScope();
  26220. }
  26221. }
  26222. },
  26223. $$writeModelToScope: function() {
  26224. this.$$ngModelSet(this.$$scope, this.$modelValue);
  26225. forEach(this.$viewChangeListeners, function(listener) {
  26226. try {
  26227. listener();
  26228. } catch (e) {
  26229. // eslint-disable-next-line no-invalid-this
  26230. this.$$exceptionHandler(e);
  26231. }
  26232. }, this);
  26233. },
  26234. /**
  26235. * @ngdoc method
  26236. * @name ngModel.NgModelController#$setViewValue
  26237. *
  26238. * @description
  26239. * Update the view value.
  26240. *
  26241. * This method should be called when a control wants to change the view value; typically,
  26242. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  26243. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  26244. * calls it when an option is selected.
  26245. *
  26246. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  26247. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  26248. * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and
  26249. * `$asyncValidators` are called and the value is applied to `$modelValue`.
  26250. * Finally, the value is set to the **expression** specified in the `ng-model` attribute and
  26251. * all the registered change listeners, in the `$viewChangeListeners` list are called.
  26252. *
  26253. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  26254. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  26255. * `updateOn` events is triggered on the DOM element.
  26256. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  26257. * directive is used with a custom debounce for this particular event.
  26258. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  26259. * is specified, once the timer runs out.
  26260. *
  26261. * When used with standard inputs, the view value will always be a string (which is in some cases
  26262. * parsed into another type, such as a `Date` object for `input[date]`.)
  26263. * However, custom controls might also pass objects to this method. In this case, we should make
  26264. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  26265. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  26266. * the property of the object then ngModel will not realize that the object has changed and
  26267. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  26268. * not change properties of the copy once it has been passed to `$setViewValue`.
  26269. * Otherwise you may cause the model value on the scope to change incorrectly.
  26270. *
  26271. * <div class="alert alert-info">
  26272. * In any case, the value passed to the method should always reflect the current value
  26273. * of the control. For example, if you are calling `$setViewValue` for an input element,
  26274. * you should pass the input DOM value. Otherwise, the control and the scope model become
  26275. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  26276. * the control's DOM value in any way. If we want to change the control's DOM value
  26277. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  26278. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  26279. * to update the DOM, and finally call `$validate` on it.
  26280. * </div>
  26281. *
  26282. * @param {*} value value from the view.
  26283. * @param {string} trigger Event that triggered the update.
  26284. */
  26285. $setViewValue: function(value, trigger) {
  26286. this.$viewValue = value;
  26287. if (this.$options.getOption('updateOnDefault')) {
  26288. this.$$debounceViewValueCommit(trigger);
  26289. }
  26290. },
  26291. $$debounceViewValueCommit: function(trigger) {
  26292. var debounceDelay = this.$options.getOption('debounce');
  26293. if (isNumber(debounceDelay[trigger])) {
  26294. debounceDelay = debounceDelay[trigger];
  26295. } else if (isNumber(debounceDelay['default'])) {
  26296. debounceDelay = debounceDelay['default'];
  26297. }
  26298. this.$$timeout.cancel(this.$$pendingDebounce);
  26299. var that = this;
  26300. if (debounceDelay > 0) { // this fails if debounceDelay is an object
  26301. this.$$pendingDebounce = this.$$timeout(function() {
  26302. that.$commitViewValue();
  26303. }, debounceDelay);
  26304. } else if (this.$$scope.$root.$$phase) {
  26305. this.$commitViewValue();
  26306. } else {
  26307. this.$$scope.$apply(function() {
  26308. that.$commitViewValue();
  26309. });
  26310. }
  26311. },
  26312. /**
  26313. * @ngdoc method
  26314. *
  26315. * @name ngModel.NgModelController#$overrideModelOptions
  26316. *
  26317. * @description
  26318. *
  26319. * Override the current model options settings programmatically.
  26320. *
  26321. * The previous `ModelOptions` value will not be modified. Instead, a
  26322. * new `ModelOptions` object will inherit from the previous one overriding
  26323. * or inheriting settings that are defined in the given parameter.
  26324. *
  26325. * See {@link ngModelOptions} for information about what options can be specified
  26326. * and how model option inheritance works.
  26327. *
  26328. * @param {Object} options a hash of settings to override the previous options
  26329. *
  26330. */
  26331. $overrideModelOptions: function(options) {
  26332. this.$options = this.$options.createChild(options);
  26333. }
  26334. };
  26335. function setupModelWatcher(ctrl) {
  26336. // model -> value
  26337. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  26338. // 1. scope value is 'a'
  26339. // 2. user enters 'b'
  26340. // 3. ng-change kicks in and reverts scope value to 'a'
  26341. // -> scope value did not change since the last digest as
  26342. // ng-change executes in apply phase
  26343. // 4. view should be changed back to 'a'
  26344. ctrl.$$scope.$watch(function ngModelWatch() {
  26345. var modelValue = ctrl.$$ngModelGet(ctrl.$$scope);
  26346. // if scope model value and ngModel value are out of sync
  26347. // TODO(perf): why not move this to the action fn?
  26348. if (modelValue !== ctrl.$modelValue &&
  26349. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  26350. // eslint-disable-next-line no-self-compare
  26351. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  26352. ) {
  26353. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  26354. ctrl.$$parserValid = undefined;
  26355. var formatters = ctrl.$formatters,
  26356. idx = formatters.length;
  26357. var viewValue = modelValue;
  26358. while (idx--) {
  26359. viewValue = formatters[idx](viewValue);
  26360. }
  26361. if (ctrl.$viewValue !== viewValue) {
  26362. ctrl.$$updateEmptyClasses(viewValue);
  26363. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  26364. ctrl.$render();
  26365. // It is possible that model and view value have been updated during render
  26366. ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop);
  26367. }
  26368. }
  26369. return modelValue;
  26370. });
  26371. }
  26372. /**
  26373. * @ngdoc method
  26374. * @name ngModel.NgModelController#$setValidity
  26375. *
  26376. * @description
  26377. * Change the validity state, and notify the form.
  26378. *
  26379. * This method can be called within $parsers/$formatters or a custom validation implementation.
  26380. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  26381. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  26382. *
  26383. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  26384. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  26385. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  26386. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  26387. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  26388. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  26389. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  26390. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  26391. * Skipped is used by Angular when validators do not run because of parse errors and
  26392. * when `$asyncValidators` do not run because any of the `$validators` failed.
  26393. */
  26394. addSetValidityMethod({
  26395. clazz: NgModelController,
  26396. set: function(object, property) {
  26397. object[property] = true;
  26398. },
  26399. unset: function(object, property) {
  26400. delete object[property];
  26401. }
  26402. });
  26403. /**
  26404. * @ngdoc directive
  26405. * @name ngModel
  26406. *
  26407. * @element input
  26408. * @priority 1
  26409. *
  26410. * @description
  26411. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  26412. * property on the scope using {@link ngModel.NgModelController NgModelController},
  26413. * which is created and exposed by this directive.
  26414. *
  26415. * `ngModel` is responsible for:
  26416. *
  26417. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  26418. * require.
  26419. * - Providing validation behavior (i.e. required, number, email, url).
  26420. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  26421. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  26422. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  26423. * - Registering the control with its parent {@link ng.directive:form form}.
  26424. *
  26425. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  26426. * current scope. If the property doesn't already exist on this scope, it will be created
  26427. * implicitly and added to the scope.
  26428. *
  26429. * For best practices on using `ngModel`, see:
  26430. *
  26431. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  26432. *
  26433. * For basic examples, how to use `ngModel`, see:
  26434. *
  26435. * - {@link ng.directive:input input}
  26436. * - {@link input[text] text}
  26437. * - {@link input[checkbox] checkbox}
  26438. * - {@link input[radio] radio}
  26439. * - {@link input[number] number}
  26440. * - {@link input[email] email}
  26441. * - {@link input[url] url}
  26442. * - {@link input[date] date}
  26443. * - {@link input[datetime-local] datetime-local}
  26444. * - {@link input[time] time}
  26445. * - {@link input[month] month}
  26446. * - {@link input[week] week}
  26447. * - {@link ng.directive:select select}
  26448. * - {@link ng.directive:textarea textarea}
  26449. *
  26450. * # Complex Models (objects or collections)
  26451. *
  26452. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  26453. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  26454. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  26455. *
  26456. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  26457. *
  26458. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  26459. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  26460. * if the select is given the `multiple` attribute.
  26461. *
  26462. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  26463. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  26464. * not trigger a re-rendering of the model.
  26465. *
  26466. * # CSS classes
  26467. * The following CSS classes are added and removed on the associated input/select/textarea element
  26468. * depending on the validity of the model.
  26469. *
  26470. * - `ng-valid`: the model is valid
  26471. * - `ng-invalid`: the model is invalid
  26472. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  26473. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  26474. * - `ng-pristine`: the control hasn't been interacted with yet
  26475. * - `ng-dirty`: the control has been interacted with
  26476. * - `ng-touched`: the control has been blurred
  26477. * - `ng-untouched`: the control hasn't been blurred
  26478. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  26479. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  26480. * by the {@link ngModel.NgModelController#$isEmpty} method
  26481. * - `ng-not-empty`: the view contains a non-empty value
  26482. *
  26483. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  26484. *
  26485. * ## Animation Hooks
  26486. *
  26487. * Animations within models are triggered when any of the associated CSS classes are added and removed
  26488. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  26489. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  26490. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  26491. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  26492. *
  26493. * The following example shows a simple way to utilize CSS transitions to style an input element
  26494. * that has been rendered as invalid after it has been validated:
  26495. *
  26496. * <pre>
  26497. * //be sure to include ngAnimate as a module to hook into more
  26498. * //advanced animations
  26499. * .my-input {
  26500. * transition:0.5s linear all;
  26501. * background: white;
  26502. * }
  26503. * .my-input.ng-invalid {
  26504. * background: red;
  26505. * color:white;
  26506. * }
  26507. * </pre>
  26508. *
  26509. * @example
  26510. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
  26511. <file name="index.html">
  26512. <script>
  26513. angular.module('inputExample', [])
  26514. .controller('ExampleController', ['$scope', function($scope) {
  26515. $scope.val = '1';
  26516. }]);
  26517. </script>
  26518. <style>
  26519. .my-input {
  26520. transition:all linear 0.5s;
  26521. background: transparent;
  26522. }
  26523. .my-input.ng-invalid {
  26524. color:white;
  26525. background: red;
  26526. }
  26527. </style>
  26528. <p id="inputDescription">
  26529. Update input to see transitions when valid/invalid.
  26530. Integer is a valid value.
  26531. </p>
  26532. <form name="testForm" ng-controller="ExampleController">
  26533. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  26534. aria-describedby="inputDescription" />
  26535. </form>
  26536. </file>
  26537. * </example>
  26538. *
  26539. * ## Binding to a getter/setter
  26540. *
  26541. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  26542. * function that returns a representation of the model when called with zero arguments, and sets
  26543. * the internal state of a model when called with an argument. It's sometimes useful to use this
  26544. * for models that have an internal representation that's different from what the model exposes
  26545. * to the view.
  26546. *
  26547. * <div class="alert alert-success">
  26548. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  26549. * frequently than other parts of your code.
  26550. * </div>
  26551. *
  26552. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  26553. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  26554. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  26555. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  26556. *
  26557. * The following example shows how to use `ngModel` with a getter/setter:
  26558. *
  26559. * @example
  26560. * <example name="ngModel-getter-setter" module="getterSetterExample">
  26561. <file name="index.html">
  26562. <div ng-controller="ExampleController">
  26563. <form name="userForm">
  26564. <label>Name:
  26565. <input type="text" name="userName"
  26566. ng-model="user.name"
  26567. ng-model-options="{ getterSetter: true }" />
  26568. </label>
  26569. </form>
  26570. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  26571. </div>
  26572. </file>
  26573. <file name="app.js">
  26574. angular.module('getterSetterExample', [])
  26575. .controller('ExampleController', ['$scope', function($scope) {
  26576. var _name = 'Brian';
  26577. $scope.user = {
  26578. name: function(newName) {
  26579. // Note that newName can be undefined for two reasons:
  26580. // 1. Because it is called as a getter and thus called with no arguments
  26581. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  26582. // input is invalid
  26583. return arguments.length ? (_name = newName) : _name;
  26584. }
  26585. };
  26586. }]);
  26587. </file>
  26588. * </example>
  26589. */
  26590. var ngModelDirective = ['$rootScope', function($rootScope) {
  26591. return {
  26592. restrict: 'A',
  26593. require: ['ngModel', '^?form', '^?ngModelOptions'],
  26594. controller: NgModelController,
  26595. // Prelink needs to run before any input directive
  26596. // so that we can set the NgModelOptions in NgModelController
  26597. // before anyone else uses it.
  26598. priority: 1,
  26599. compile: function ngModelCompile(element) {
  26600. // Setup initial state of the control
  26601. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  26602. return {
  26603. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  26604. var modelCtrl = ctrls[0],
  26605. formCtrl = ctrls[1] || modelCtrl.$$parentForm,
  26606. optionsCtrl = ctrls[2];
  26607. if (optionsCtrl) {
  26608. modelCtrl.$options = optionsCtrl.$options;
  26609. }
  26610. modelCtrl.$$initGetterSetters();
  26611. // notify others, especially parent forms
  26612. formCtrl.$addControl(modelCtrl);
  26613. attr.$observe('name', function(newValue) {
  26614. if (modelCtrl.$name !== newValue) {
  26615. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  26616. }
  26617. });
  26618. scope.$on('$destroy', function() {
  26619. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  26620. });
  26621. },
  26622. post: function ngModelPostLink(scope, element, attr, ctrls) {
  26623. var modelCtrl = ctrls[0];
  26624. if (modelCtrl.$options.getOption('updateOn')) {
  26625. element.on(modelCtrl.$options.getOption('updateOn'), function(ev) {
  26626. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  26627. });
  26628. }
  26629. function setTouched() {
  26630. modelCtrl.$setTouched();
  26631. }
  26632. element.on('blur', function() {
  26633. if (modelCtrl.$touched) return;
  26634. if ($rootScope.$$phase) {
  26635. scope.$evalAsync(setTouched);
  26636. } else {
  26637. scope.$apply(setTouched);
  26638. }
  26639. });
  26640. }
  26641. };
  26642. }
  26643. };
  26644. }];
  26645. /* exported defaultModelOptions */
  26646. var defaultModelOptions;
  26647. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  26648. /**
  26649. * @ngdoc type
  26650. * @name ModelOptions
  26651. * @description
  26652. * A container for the options set by the {@link ngModelOptions} directive
  26653. */
  26654. function ModelOptions(options) {
  26655. this.$$options = options;
  26656. }
  26657. ModelOptions.prototype = {
  26658. /**
  26659. * @ngdoc method
  26660. * @name ModelOptions#getOption
  26661. * @param {string} name the name of the option to retrieve
  26662. * @returns {*} the value of the option
  26663. * @description
  26664. * Returns the value of the given option
  26665. */
  26666. getOption: function(name) {
  26667. return this.$$options[name];
  26668. },
  26669. /**
  26670. * @ngdoc method
  26671. * @name ModelOptions#createChild
  26672. * @param {Object} options a hash of options for the new child that will override the parent's options
  26673. * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
  26674. */
  26675. createChild: function(options) {
  26676. var inheritAll = false;
  26677. // make a shallow copy
  26678. options = extend({}, options);
  26679. // Inherit options from the parent if specified by the value `"$inherit"`
  26680. forEach(options, /* @this */ function(option, key) {
  26681. if (option === '$inherit') {
  26682. if (key === '*') {
  26683. inheritAll = true;
  26684. } else {
  26685. options[key] = this.$$options[key];
  26686. // `updateOn` is special so we must also inherit the `updateOnDefault` option
  26687. if (key === 'updateOn') {
  26688. options.updateOnDefault = this.$$options.updateOnDefault;
  26689. }
  26690. }
  26691. } else {
  26692. if (key === 'updateOn') {
  26693. // If the `updateOn` property contains the `default` event then we have to remove
  26694. // it from the event list and set the `updateOnDefault` flag.
  26695. options.updateOnDefault = false;
  26696. options[key] = trim(option.replace(DEFAULT_REGEXP, function() {
  26697. options.updateOnDefault = true;
  26698. return ' ';
  26699. }));
  26700. }
  26701. }
  26702. }, this);
  26703. if (inheritAll) {
  26704. // We have a property of the form: `"*": "$inherit"`
  26705. delete options['*'];
  26706. defaults(options, this.$$options);
  26707. }
  26708. // Finally add in any missing defaults
  26709. defaults(options, defaultModelOptions.$$options);
  26710. return new ModelOptions(options);
  26711. }
  26712. };
  26713. defaultModelOptions = new ModelOptions({
  26714. updateOn: '',
  26715. updateOnDefault: true,
  26716. debounce: 0,
  26717. getterSetter: false,
  26718. allowInvalid: false,
  26719. timezone: null
  26720. });
  26721. /**
  26722. * @ngdoc directive
  26723. * @name ngModelOptions
  26724. *
  26725. * @description
  26726. * This directive allows you to modify the behaviour of {@link ngModel} directives within your
  26727. * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}
  26728. * directives will use the options of their nearest `ngModelOptions` ancestor.
  26729. *
  26730. * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as
  26731. * an Angular expression. This expression should evaluate to an object, whose properties contain
  26732. * the settings. For example: `<div "ng-model-options"="{ debounce: 100 }"`.
  26733. *
  26734. * ## Inheriting Options
  26735. *
  26736. * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions`
  26737. * directive by giving it the value of `"$inherit"`.
  26738. * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the
  26739. * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings
  26740. * will be used.
  26741. *
  26742. * For example given the following fragment of HTML
  26743. *
  26744. *
  26745. * ```html
  26746. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  26747. * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }">
  26748. * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" />
  26749. * </form>
  26750. * </div>
  26751. * ```
  26752. *
  26753. * the `input` element will have the following settings
  26754. *
  26755. * ```js
  26756. * { allowInvalid: true, updateOn: 'default', debounce: 0 }
  26757. * ```
  26758. *
  26759. * Notice that the `debounce` setting was not inherited and used the default value instead.
  26760. *
  26761. * You can specify that all undefined settings are automatically inherited from an ancestor by
  26762. * including a property with key of `"*"` and value of `"$inherit"`.
  26763. *
  26764. * For example given the following fragment of HTML
  26765. *
  26766. *
  26767. * ```html
  26768. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  26769. * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }">
  26770. * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" />
  26771. * </form>
  26772. * </div>
  26773. * ```
  26774. *
  26775. * the `input` element will have the following settings
  26776. *
  26777. * ```js
  26778. * { allowInvalid: true, updateOn: 'default', debounce: 200 }
  26779. * ```
  26780. *
  26781. * Notice that the `debounce` setting now inherits the value from the outer `<div>` element.
  26782. *
  26783. * If you are creating a reusable component then you should be careful when using `"*": "$inherit"`
  26784. * since you may inadvertently inherit a setting in the future that changes the behavior of your component.
  26785. *
  26786. *
  26787. * ## Triggering and debouncing model updates
  26788. *
  26789. * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
  26790. * trigger a model update and/or a debouncing delay so that the actual update only takes place when
  26791. * a timer expires; this timer will be reset after another change takes place.
  26792. *
  26793. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  26794. * be different from the value in the actual model. This means that if you update the model you
  26795. * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in
  26796. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  26797. *
  26798. * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}
  26799. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  26800. * important because `form` controllers are published to the related scope under the name in their
  26801. * `name` attribute.
  26802. *
  26803. * Any pending changes will take place immediately when an enclosing form is submitted via the
  26804. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  26805. * to have access to the updated model.
  26806. *
  26807. * The following example shows how to override immediate updates. Changes on the inputs within the
  26808. * form will update the model only when the control loses focus (blur event). If `escape` key is
  26809. * pressed while the input field is focused, the value is reset to the value in the current model.
  26810. *
  26811. * <example name="ngModelOptions-directive-blur" module="optionsExample">
  26812. * <file name="index.html">
  26813. * <div ng-controller="ExampleController">
  26814. * <form name="userForm">
  26815. * <label>
  26816. * Name:
  26817. * <input type="text" name="userName"
  26818. * ng-model="user.name"
  26819. * ng-model-options="{ updateOn: 'blur' }"
  26820. * ng-keyup="cancel($event)" />
  26821. * </label><br />
  26822. * <label>
  26823. * Other data:
  26824. * <input type="text" ng-model="user.data" />
  26825. * </label><br />
  26826. * </form>
  26827. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  26828. * </div>
  26829. * </file>
  26830. * <file name="app.js">
  26831. * angular.module('optionsExample', [])
  26832. * .controller('ExampleController', ['$scope', function($scope) {
  26833. * $scope.user = { name: 'say', data: '' };
  26834. *
  26835. * $scope.cancel = function(e) {
  26836. * if (e.keyCode === 27) {
  26837. * $scope.userForm.userName.$rollbackViewValue();
  26838. * }
  26839. * };
  26840. * }]);
  26841. * </file>
  26842. * <file name="protractor.js" type="protractor">
  26843. * var model = element(by.binding('user.name'));
  26844. * var input = element(by.model('user.name'));
  26845. * var other = element(by.model('user.data'));
  26846. *
  26847. * it('should allow custom events', function() {
  26848. * input.sendKeys(' hello');
  26849. * input.click();
  26850. * expect(model.getText()).toEqual('say');
  26851. * other.click();
  26852. * expect(model.getText()).toEqual('say hello');
  26853. * });
  26854. *
  26855. * it('should $rollbackViewValue when model changes', function() {
  26856. * input.sendKeys(' hello');
  26857. * expect(input.getAttribute('value')).toEqual('say hello');
  26858. * input.sendKeys(protractor.Key.ESCAPE);
  26859. * expect(input.getAttribute('value')).toEqual('say');
  26860. * other.click();
  26861. * expect(model.getText()).toEqual('say');
  26862. * });
  26863. * </file>
  26864. * </example>
  26865. *
  26866. * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
  26867. * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  26868. *
  26869. * <example name="ngModelOptions-directive-debounce" module="optionsExample">
  26870. * <file name="index.html">
  26871. * <div ng-controller="ExampleController">
  26872. * <form name="userForm">
  26873. * Name:
  26874. * <input type="text" name="userName"
  26875. * ng-model="user.name"
  26876. * ng-model-options="{ debounce: 1000 }" />
  26877. * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  26878. * </form>
  26879. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  26880. * </div>
  26881. * </file>
  26882. * <file name="app.js">
  26883. * angular.module('optionsExample', [])
  26884. * .controller('ExampleController', ['$scope', function($scope) {
  26885. * $scope.user = { name: 'say' };
  26886. * }]);
  26887. * </file>
  26888. * </example>
  26889. *
  26890. * ## Model updates and validation
  26891. *
  26892. * The default behaviour in `ngModel` is that the model value is set to `undefined` when the
  26893. * validation determines that the value is invalid. By setting the `allowInvalid` property to true,
  26894. * the model will still be updated even if the value is invalid.
  26895. *
  26896. *
  26897. * ## Connecting to the scope
  26898. *
  26899. * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
  26900. * on the scope refers to a "getter/setter" function rather than the value itself.
  26901. *
  26902. * The following example shows how to bind to getter/setters:
  26903. *
  26904. * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  26905. * <file name="index.html">
  26906. * <div ng-controller="ExampleController">
  26907. * <form name="userForm">
  26908. * <label>
  26909. * Name:
  26910. * <input type="text" name="userName"
  26911. * ng-model="user.name"
  26912. * ng-model-options="{ getterSetter: true }" />
  26913. * </label>
  26914. * </form>
  26915. * <pre>user.name = <span ng-bind="user.name()"></span></pre>
  26916. * </div>
  26917. * </file>
  26918. * <file name="app.js">
  26919. * angular.module('getterSetterExample', [])
  26920. * .controller('ExampleController', ['$scope', function($scope) {
  26921. * var _name = 'Brian';
  26922. * $scope.user = {
  26923. * name: function(newName) {
  26924. * return angular.isDefined(newName) ? (_name = newName) : _name;
  26925. * }
  26926. * };
  26927. * }]);
  26928. * </file>
  26929. * </example>
  26930. *
  26931. *
  26932. * ## Specifying timezones
  26933. *
  26934. * You can specify the timezone that date/time input directives expect by providing its name in the
  26935. * `timezone` property.
  26936. *
  26937. * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and
  26938. * and its descendents. Valid keys are:
  26939. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  26940. * events using an space delimited list. There is a special event called `default` that
  26941. * matches the default events belonging to the control.
  26942. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  26943. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  26944. * custom value for each event. For example:
  26945. * ```
  26946. * ng-model-options="{
  26947. * updateOn: 'default blur',
  26948. * debounce: { 'default': 500, 'blur': 0 }
  26949. * }"
  26950. * ```
  26951. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  26952. * not validate correctly instead of the default behavior of setting the model to undefined.
  26953. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  26954. * `ngModel` as getters/setters.
  26955. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  26956. * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the
  26957. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  26958. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  26959. * If not specified, the timezone of the browser will be used.
  26960. *
  26961. */
  26962. var ngModelOptionsDirective = function() {
  26963. NgModelOptionsController.$inject = ['$attrs', '$scope'];
  26964. function NgModelOptionsController($attrs, $scope) {
  26965. this.$$attrs = $attrs;
  26966. this.$$scope = $scope;
  26967. }
  26968. NgModelOptionsController.prototype = {
  26969. $onInit: function() {
  26970. var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions;
  26971. var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions);
  26972. this.$options = parentOptions.createChild(modelOptionsDefinition);
  26973. }
  26974. };
  26975. return {
  26976. restrict: 'A',
  26977. // ngModelOptions needs to run before ngModel and input directives
  26978. priority: 10,
  26979. require: {parentCtrl: '?^^ngModelOptions'},
  26980. bindToController: true,
  26981. controller: NgModelOptionsController
  26982. };
  26983. };
  26984. // shallow copy over values from `src` that are not already specified on `dst`
  26985. function defaults(dst, src) {
  26986. forEach(src, function(value, key) {
  26987. if (!isDefined(dst[key])) {
  26988. dst[key] = value;
  26989. }
  26990. });
  26991. }
  26992. /**
  26993. * @ngdoc directive
  26994. * @name ngNonBindable
  26995. * @restrict AC
  26996. * @priority 1000
  26997. *
  26998. * @description
  26999. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  27000. * DOM element. This is useful if the element contains what appears to be Angular directives and
  27001. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  27002. * displays snippets of code, for instance.
  27003. *
  27004. * @element ANY
  27005. *
  27006. * @example
  27007. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  27008. * but the one wrapped in `ngNonBindable` is left alone.
  27009. *
  27010. * @example
  27011. <example name="ng-non-bindable">
  27012. <file name="index.html">
  27013. <div>Normal: {{1 + 2}}</div>
  27014. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  27015. </file>
  27016. <file name="protractor.js" type="protractor">
  27017. it('should check ng-non-bindable', function() {
  27018. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  27019. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  27020. });
  27021. </file>
  27022. </example>
  27023. */
  27024. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  27025. /* exported ngOptionsDirective */
  27026. /* global jqLiteRemove */
  27027. var ngOptionsMinErr = minErr('ngOptions');
  27028. /**
  27029. * @ngdoc directive
  27030. * @name ngOptions
  27031. * @restrict A
  27032. *
  27033. * @description
  27034. *
  27035. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  27036. * elements for the `<select>` element using the array or object obtained by evaluating the
  27037. * `ngOptions` comprehension expression.
  27038. *
  27039. * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of
  27040. * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits:
  27041. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  27042. * comprehension expression
  27043. * - reduced memory consumption by not creating a new scope for each repeated instance
  27044. * - increased render speed by creating the options in a documentFragment instead of individually
  27045. *
  27046. * When an item in the `<select>` menu is selected, the array element or object property
  27047. * represented by the selected option will be bound to the model identified by the `ngModel`
  27048. * directive.
  27049. *
  27050. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  27051. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  27052. * option. See example below for demonstration.
  27053. *
  27054. * ## Complex Models (objects or collections)
  27055. *
  27056. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  27057. * binding the select to a model that is an object or a collection.
  27058. *
  27059. * One issue occurs if you want to preselect an option. For example, if you set
  27060. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  27061. * because the objects are not identical. So by default, you should always reference the item in your collection
  27062. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  27063. *
  27064. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  27065. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  27066. * collection items have an id property, you would `track by item.id`.
  27067. *
  27068. * A different issue with objects or collections is that ngModel won't detect if an object property or
  27069. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  27070. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  27071. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  27072. * has not changed identity, but only a property on the object or an item in the collection changes.
  27073. *
  27074. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  27075. * if the model is an array). This means that changing a property deeper than the first level inside the
  27076. * object/collection will not trigger a re-rendering.
  27077. *
  27078. * ## `select` **`as`**
  27079. *
  27080. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  27081. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  27082. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  27083. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  27084. *
  27085. *
  27086. * ### `select` **`as`** and **`track by`**
  27087. *
  27088. * <div class="alert alert-warning">
  27089. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  27090. * </div>
  27091. *
  27092. * Given this array of items on the $scope:
  27093. *
  27094. * ```js
  27095. * $scope.items = [{
  27096. * id: 1,
  27097. * label: 'aLabel',
  27098. * subItem: { name: 'aSubItem' }
  27099. * }, {
  27100. * id: 2,
  27101. * label: 'bLabel',
  27102. * subItem: { name: 'bSubItem' }
  27103. * }];
  27104. * ```
  27105. *
  27106. * This will work:
  27107. *
  27108. * ```html
  27109. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  27110. * ```
  27111. * ```js
  27112. * $scope.selected = $scope.items[0];
  27113. * ```
  27114. *
  27115. * but this will not work:
  27116. *
  27117. * ```html
  27118. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  27119. * ```
  27120. * ```js
  27121. * $scope.selected = $scope.items[0].subItem;
  27122. * ```
  27123. *
  27124. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  27125. * `items` array. Because the selected option has been set programmatically in the controller, the
  27126. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  27127. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  27128. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  27129. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  27130. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  27131. *
  27132. *
  27133. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  27134. * @param {comprehension_expression} ngOptions in one of the following forms:
  27135. *
  27136. * * for array data sources:
  27137. * * `label` **`for`** `value` **`in`** `array`
  27138. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  27139. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  27140. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  27141. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  27142. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  27143. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  27144. * (for including a filter with `track by`)
  27145. * * for object data sources:
  27146. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  27147. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  27148. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  27149. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  27150. * * `select` **`as`** `label` **`group by`** `group`
  27151. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  27152. * * `select` **`as`** `label` **`disable when`** `disable`
  27153. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  27154. *
  27155. * Where:
  27156. *
  27157. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  27158. * * `value`: local variable which will refer to each item in the `array` or each property value
  27159. * of `object` during iteration.
  27160. * * `key`: local variable which will refer to a property name in `object` during iteration.
  27161. * * `label`: The result of this expression will be the label for `<option>` element. The
  27162. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  27163. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  27164. * element. If not specified, `select` expression will default to `value`.
  27165. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  27166. * DOM element.
  27167. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  27168. * element. Return `true` to disable.
  27169. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  27170. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  27171. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  27172. * even when the options are recreated (e.g. reloaded from the server).
  27173. * @param {string=} name Property name of the form under which the control is published.
  27174. * @param {string=} required The control is considered valid only if value is entered.
  27175. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  27176. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  27177. * `required` when you want to data-bind to the `required` attribute.
  27178. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  27179. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  27180. *
  27181. * @example
  27182. <example module="selectExample" name="select">
  27183. <file name="index.html">
  27184. <script>
  27185. angular.module('selectExample', [])
  27186. .controller('ExampleController', ['$scope', function($scope) {
  27187. $scope.colors = [
  27188. {name:'black', shade:'dark'},
  27189. {name:'white', shade:'light', notAnOption: true},
  27190. {name:'red', shade:'dark'},
  27191. {name:'blue', shade:'dark', notAnOption: true},
  27192. {name:'yellow', shade:'light', notAnOption: false}
  27193. ];
  27194. $scope.myColor = $scope.colors[2]; // red
  27195. }]);
  27196. </script>
  27197. <div ng-controller="ExampleController">
  27198. <ul>
  27199. <li ng-repeat="color in colors">
  27200. <label>Name: <input ng-model="color.name"></label>
  27201. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  27202. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  27203. </li>
  27204. <li>
  27205. <button ng-click="colors.push({})">add</button>
  27206. </li>
  27207. </ul>
  27208. <hr/>
  27209. <label>Color (null not allowed):
  27210. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  27211. </label><br/>
  27212. <label>Color (null allowed):
  27213. <span class="nullable">
  27214. <select ng-model="myColor" ng-options="color.name for color in colors">
  27215. <option value="">-- choose color --</option>
  27216. </select>
  27217. </span></label><br/>
  27218. <label>Color grouped by shade:
  27219. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  27220. </select>
  27221. </label><br/>
  27222. <label>Color grouped by shade, with some disabled:
  27223. <select ng-model="myColor"
  27224. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  27225. </select>
  27226. </label><br/>
  27227. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  27228. <br/>
  27229. <hr/>
  27230. Currently selected: {{ {selected_color:myColor} }}
  27231. <div style="border:solid 1px black; height:20px"
  27232. ng-style="{'background-color':myColor.name}">
  27233. </div>
  27234. </div>
  27235. </file>
  27236. <file name="protractor.js" type="protractor">
  27237. it('should check ng-options', function() {
  27238. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  27239. element.all(by.model('myColor')).first().click();
  27240. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  27241. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  27242. element(by.css('.nullable select[ng-model="myColor"]')).click();
  27243. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  27244. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  27245. });
  27246. </file>
  27247. </example>
  27248. */
  27249. /* eslint-disable max-len */
  27250. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999
  27251. 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]+?))?$/;
  27252. // 1: value expression (valueFn)
  27253. // 2: label expression (displayFn)
  27254. // 3: group by expression (groupByFn)
  27255. // 4: disable when expression (disableWhenFn)
  27256. // 5: array item variable name
  27257. // 6: object item key variable name
  27258. // 7: object item value variable name
  27259. // 8: collection expression
  27260. // 9: track by expression
  27261. /* eslint-enable */
  27262. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  27263. function parseOptionsExpression(optionsExp, selectElement, scope) {
  27264. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  27265. if (!(match)) {
  27266. throw ngOptionsMinErr('iexp',
  27267. 'Expected expression in form of ' +
  27268. '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
  27269. ' but got \'{0}\'. Element: {1}',
  27270. optionsExp, startingTag(selectElement));
  27271. }
  27272. // Extract the parts from the ngOptions expression
  27273. // The variable name for the value of the item in the collection
  27274. var valueName = match[5] || match[7];
  27275. // The variable name for the key of the item in the collection
  27276. var keyName = match[6];
  27277. // An expression that generates the viewValue for an option if there is a label expression
  27278. var selectAs = / as /.test(match[0]) && match[1];
  27279. // An expression that is used to track the id of each object in the options collection
  27280. var trackBy = match[9];
  27281. // An expression that generates the viewValue for an option if there is no label expression
  27282. var valueFn = $parse(match[2] ? match[1] : valueName);
  27283. var selectAsFn = selectAs && $parse(selectAs);
  27284. var viewValueFn = selectAsFn || valueFn;
  27285. var trackByFn = trackBy && $parse(trackBy);
  27286. // Get the value by which we are going to track the option
  27287. // if we have a trackFn then use that (passing scope and locals)
  27288. // otherwise just hash the given viewValue
  27289. var getTrackByValueFn = trackBy ?
  27290. function(value, locals) { return trackByFn(scope, locals); } :
  27291. function getHashOfValue(value) { return hashKey(value); };
  27292. var getTrackByValue = function(value, key) {
  27293. return getTrackByValueFn(value, getLocals(value, key));
  27294. };
  27295. var displayFn = $parse(match[2] || match[1]);
  27296. var groupByFn = $parse(match[3] || '');
  27297. var disableWhenFn = $parse(match[4] || '');
  27298. var valuesFn = $parse(match[8]);
  27299. var locals = {};
  27300. var getLocals = keyName ? function(value, key) {
  27301. locals[keyName] = key;
  27302. locals[valueName] = value;
  27303. return locals;
  27304. } : function(value) {
  27305. locals[valueName] = value;
  27306. return locals;
  27307. };
  27308. function Option(selectValue, viewValue, label, group, disabled) {
  27309. this.selectValue = selectValue;
  27310. this.viewValue = viewValue;
  27311. this.label = label;
  27312. this.group = group;
  27313. this.disabled = disabled;
  27314. }
  27315. function getOptionValuesKeys(optionValues) {
  27316. var optionValuesKeys;
  27317. if (!keyName && isArrayLike(optionValues)) {
  27318. optionValuesKeys = optionValues;
  27319. } else {
  27320. // if object, extract keys, in enumeration order, unsorted
  27321. optionValuesKeys = [];
  27322. for (var itemKey in optionValues) {
  27323. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  27324. optionValuesKeys.push(itemKey);
  27325. }
  27326. }
  27327. }
  27328. return optionValuesKeys;
  27329. }
  27330. return {
  27331. trackBy: trackBy,
  27332. getTrackByValue: getTrackByValue,
  27333. getWatchables: $parse(valuesFn, function(optionValues) {
  27334. // Create a collection of things that we would like to watch (watchedArray)
  27335. // so that they can all be watched using a single $watchCollection
  27336. // that only runs the handler once if anything changes
  27337. var watchedArray = [];
  27338. optionValues = optionValues || [];
  27339. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27340. var optionValuesLength = optionValuesKeys.length;
  27341. for (var index = 0; index < optionValuesLength; index++) {
  27342. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27343. var value = optionValues[key];
  27344. var locals = getLocals(value, key);
  27345. var selectValue = getTrackByValueFn(value, locals);
  27346. watchedArray.push(selectValue);
  27347. // Only need to watch the displayFn if there is a specific label expression
  27348. if (match[2] || match[1]) {
  27349. var label = displayFn(scope, locals);
  27350. watchedArray.push(label);
  27351. }
  27352. // Only need to watch the disableWhenFn if there is a specific disable expression
  27353. if (match[4]) {
  27354. var disableWhen = disableWhenFn(scope, locals);
  27355. watchedArray.push(disableWhen);
  27356. }
  27357. }
  27358. return watchedArray;
  27359. }),
  27360. getOptions: function() {
  27361. var optionItems = [];
  27362. var selectValueMap = {};
  27363. // The option values were already computed in the `getWatchables` fn,
  27364. // which must have been called to trigger `getOptions`
  27365. var optionValues = valuesFn(scope) || [];
  27366. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27367. var optionValuesLength = optionValuesKeys.length;
  27368. for (var index = 0; index < optionValuesLength; index++) {
  27369. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27370. var value = optionValues[key];
  27371. var locals = getLocals(value, key);
  27372. var viewValue = viewValueFn(scope, locals);
  27373. var selectValue = getTrackByValueFn(viewValue, locals);
  27374. var label = displayFn(scope, locals);
  27375. var group = groupByFn(scope, locals);
  27376. var disabled = disableWhenFn(scope, locals);
  27377. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  27378. optionItems.push(optionItem);
  27379. selectValueMap[selectValue] = optionItem;
  27380. }
  27381. return {
  27382. items: optionItems,
  27383. selectValueMap: selectValueMap,
  27384. getOptionFromViewValue: function(value) {
  27385. return selectValueMap[getTrackByValue(value)];
  27386. },
  27387. getViewValueFromOption: function(option) {
  27388. // If the viewValue could be an object that may be mutated by the application,
  27389. // we need to make a copy and not return the reference to the value on the option.
  27390. return trackBy ? copy(option.viewValue) : option.viewValue;
  27391. }
  27392. };
  27393. }
  27394. };
  27395. }
  27396. // we can't just jqLite('<option>') since jqLite is not smart enough
  27397. // to create it in <select> and IE barfs otherwise.
  27398. var optionTemplate = window.document.createElement('option'),
  27399. optGroupTemplate = window.document.createElement('optgroup');
  27400. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  27401. var selectCtrl = ctrls[0];
  27402. var ngModelCtrl = ctrls[1];
  27403. var multiple = attr.multiple;
  27404. // The emptyOption allows the application developer to provide their own custom "empty"
  27405. // option when the viewValue does not match any of the option values.
  27406. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  27407. if (children[i].value === '') {
  27408. selectCtrl.hasEmptyOption = true;
  27409. selectCtrl.emptyOption = children.eq(i);
  27410. break;
  27411. }
  27412. }
  27413. var providedEmptyOption = !!selectCtrl.emptyOption;
  27414. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  27415. unknownOption.val('?');
  27416. var options;
  27417. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  27418. // This stores the newly created options before they are appended to the select.
  27419. // Since the contents are removed from the fragment when it is appended,
  27420. // we only need to create it once.
  27421. var listFragment = $document[0].createDocumentFragment();
  27422. // Overwrite the implementation. ngOptions doesn't use hashes
  27423. selectCtrl.generateUnknownOptionValue = function(val) {
  27424. return '?';
  27425. };
  27426. // Update the controller methods for multiple selectable options
  27427. if (!multiple) {
  27428. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  27429. var selectedOption = options.selectValueMap[selectElement.val()];
  27430. var option = options.getOptionFromViewValue(value);
  27431. // Make sure to remove the selected attribute from the previously selected option
  27432. // Otherwise, screen readers might get confused
  27433. if (selectedOption) selectedOption.element.removeAttribute('selected');
  27434. if (option) {
  27435. // Don't update the option when it is already selected.
  27436. // For example, the browser will select the first option by default. In that case,
  27437. // most properties are set automatically - except the `selected` attribute, which we
  27438. // set always
  27439. if (selectElement[0].value !== option.selectValue) {
  27440. selectCtrl.removeUnknownOption();
  27441. selectCtrl.unselectEmptyOption();
  27442. selectElement[0].value = option.selectValue;
  27443. option.element.selected = true;
  27444. }
  27445. option.element.setAttribute('selected', 'selected');
  27446. } else {
  27447. if (providedEmptyOption) {
  27448. selectCtrl.selectEmptyOption();
  27449. } else if (selectCtrl.unknownOption.parent().length) {
  27450. selectCtrl.updateUnknownOption(value);
  27451. } else {
  27452. selectCtrl.renderUnknownOption(value);
  27453. }
  27454. }
  27455. };
  27456. selectCtrl.readValue = function readNgOptionsValue() {
  27457. var selectedOption = options.selectValueMap[selectElement.val()];
  27458. if (selectedOption && !selectedOption.disabled) {
  27459. selectCtrl.unselectEmptyOption();
  27460. selectCtrl.removeUnknownOption();
  27461. return options.getViewValueFromOption(selectedOption);
  27462. }
  27463. return null;
  27464. };
  27465. // If we are using `track by` then we must watch the tracked value on the model
  27466. // since ngModel only watches for object identity change
  27467. // FIXME: When a user selects an option, this watch will fire needlessly
  27468. if (ngOptions.trackBy) {
  27469. scope.$watch(
  27470. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  27471. function() { ngModelCtrl.$render(); }
  27472. );
  27473. }
  27474. } else {
  27475. selectCtrl.writeValue = function writeNgOptionsMultiple(values) {
  27476. // Only set `<option>.selected` if necessary, in order to prevent some browsers from
  27477. // scrolling to `<option>` elements that are outside the `<select>` element's viewport.
  27478. var selectedOptions = values && values.map(getAndUpdateSelectedOption) || [];
  27479. options.items.forEach(function(option) {
  27480. if (option.element.selected && !includes(selectedOptions, option)) {
  27481. option.element.selected = false;
  27482. }
  27483. });
  27484. };
  27485. selectCtrl.readValue = function readNgOptionsMultiple() {
  27486. var selectedValues = selectElement.val() || [],
  27487. selections = [];
  27488. forEach(selectedValues, function(value) {
  27489. var option = options.selectValueMap[value];
  27490. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  27491. });
  27492. return selections;
  27493. };
  27494. // If we are using `track by` then we must watch these tracked values on the model
  27495. // since ngModel only watches for object identity change
  27496. if (ngOptions.trackBy) {
  27497. scope.$watchCollection(function() {
  27498. if (isArray(ngModelCtrl.$viewValue)) {
  27499. return ngModelCtrl.$viewValue.map(function(value) {
  27500. return ngOptions.getTrackByValue(value);
  27501. });
  27502. }
  27503. }, function() {
  27504. ngModelCtrl.$render();
  27505. });
  27506. }
  27507. }
  27508. if (providedEmptyOption) {
  27509. // we need to remove it before calling selectElement.empty() because otherwise IE will
  27510. // remove the label from the element. wtf?
  27511. selectCtrl.emptyOption.remove();
  27512. // compile the element since there might be bindings in it
  27513. $compile(selectCtrl.emptyOption)(scope);
  27514. if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) {
  27515. // This means the empty option has currently no actual DOM node, probably because
  27516. // it has been modified by a transclusion directive.
  27517. selectCtrl.hasEmptyOption = false;
  27518. // Redefine the registerOption function, which will catch
  27519. // options that are added by ngIf etc. (rendering of the node is async because of
  27520. // lazy transclusion)
  27521. selectCtrl.registerOption = function(optionScope, optionEl) {
  27522. if (optionEl.val() === '') {
  27523. selectCtrl.hasEmptyOption = true;
  27524. selectCtrl.emptyOption = optionEl;
  27525. selectCtrl.emptyOption.removeClass('ng-scope');
  27526. // This ensures the new empty option is selected if previously no option was selected
  27527. ngModelCtrl.$render();
  27528. optionEl.on('$destroy', function() {
  27529. selectCtrl.hasEmptyOption = false;
  27530. selectCtrl.emptyOption = undefined;
  27531. });
  27532. }
  27533. };
  27534. } else {
  27535. // remove the class, which is added automatically because we recompile the element and it
  27536. // becomes the compilation root
  27537. selectCtrl.emptyOption.removeClass('ng-scope');
  27538. }
  27539. }
  27540. selectElement.empty();
  27541. // We need to do this here to ensure that the options object is defined
  27542. // when we first hit it in writeNgOptionsValue
  27543. updateOptions();
  27544. // We will re-render the option elements if the option values or labels change
  27545. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  27546. // ------------------------------------------------------------------ //
  27547. function addOptionElement(option, parent) {
  27548. var optionElement = optionTemplate.cloneNode(false);
  27549. parent.appendChild(optionElement);
  27550. updateOptionElement(option, optionElement);
  27551. }
  27552. function getAndUpdateSelectedOption(viewValue) {
  27553. var option = options.getOptionFromViewValue(viewValue);
  27554. var element = option && option.element;
  27555. if (element && !element.selected) element.selected = true;
  27556. return option;
  27557. }
  27558. function updateOptionElement(option, element) {
  27559. option.element = element;
  27560. element.disabled = option.disabled;
  27561. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  27562. // selects in certain circumstances when multiple selects are next to each other and display
  27563. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  27564. // See https://github.com/angular/angular.js/issues/11314 for more info.
  27565. // This is unfortunately untestable with unit / e2e tests
  27566. if (option.label !== element.label) {
  27567. element.label = option.label;
  27568. element.textContent = option.label;
  27569. }
  27570. element.value = option.selectValue;
  27571. }
  27572. function updateOptions() {
  27573. var previousValue = options && selectCtrl.readValue();
  27574. // We must remove all current options, but cannot simply set innerHTML = null
  27575. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  27576. // must preserve.
  27577. // Instead, iterate over the current option elements and remove them or their optgroup
  27578. // parents
  27579. if (options) {
  27580. for (var i = options.items.length - 1; i >= 0; i--) {
  27581. var option = options.items[i];
  27582. if (isDefined(option.group)) {
  27583. jqLiteRemove(option.element.parentNode);
  27584. } else {
  27585. jqLiteRemove(option.element);
  27586. }
  27587. }
  27588. }
  27589. options = ngOptions.getOptions();
  27590. var groupElementMap = {};
  27591. // Ensure that the empty option is always there if it was explicitly provided
  27592. if (providedEmptyOption) {
  27593. selectElement.prepend(selectCtrl.emptyOption);
  27594. }
  27595. options.items.forEach(function addOption(option) {
  27596. var groupElement;
  27597. if (isDefined(option.group)) {
  27598. // This option is to live in a group
  27599. // See if we have already created this group
  27600. groupElement = groupElementMap[option.group];
  27601. if (!groupElement) {
  27602. groupElement = optGroupTemplate.cloneNode(false);
  27603. listFragment.appendChild(groupElement);
  27604. // Update the label on the group element
  27605. // "null" is special cased because of Safari
  27606. groupElement.label = option.group === null ? 'null' : option.group;
  27607. // Store it for use later
  27608. groupElementMap[option.group] = groupElement;
  27609. }
  27610. addOptionElement(option, groupElement);
  27611. } else {
  27612. // This option is not in a group
  27613. addOptionElement(option, listFragment);
  27614. }
  27615. });
  27616. selectElement[0].appendChild(listFragment);
  27617. ngModelCtrl.$render();
  27618. // Check to see if the value has changed due to the update to the options
  27619. if (!ngModelCtrl.$isEmpty(previousValue)) {
  27620. var nextValue = selectCtrl.readValue();
  27621. var isNotPrimitive = ngOptions.trackBy || multiple;
  27622. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  27623. ngModelCtrl.$setViewValue(nextValue);
  27624. ngModelCtrl.$render();
  27625. }
  27626. }
  27627. }
  27628. }
  27629. return {
  27630. restrict: 'A',
  27631. terminal: true,
  27632. require: ['select', 'ngModel'],
  27633. link: {
  27634. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  27635. // Deactivate the SelectController.register method to prevent
  27636. // option directives from accidentally registering themselves
  27637. // (and unwanted $destroy handlers etc.)
  27638. ctrls[0].registerOption = noop;
  27639. },
  27640. post: ngOptionsPostLink
  27641. }
  27642. };
  27643. }];
  27644. /**
  27645. * @ngdoc directive
  27646. * @name ngPluralize
  27647. * @restrict EA
  27648. *
  27649. * @description
  27650. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  27651. * These rules are bundled with angular.js, but can be overridden
  27652. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  27653. * by specifying the mappings between
  27654. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  27655. * and the strings to be displayed.
  27656. *
  27657. * # Plural categories and explicit number rules
  27658. * There are two
  27659. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  27660. * in Angular's default en-US locale: "one" and "other".
  27661. *
  27662. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  27663. * any number that is not 1), an explicit number rule can only match one number. For example, the
  27664. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  27665. * and explicit number rules throughout the rest of this documentation.
  27666. *
  27667. * # Configuring ngPluralize
  27668. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  27669. * You can also provide an optional attribute, `offset`.
  27670. *
  27671. * The value of the `count` attribute can be either a string or an {@link guide/expression
  27672. * Angular expression}; these are evaluated on the current scope for its bound value.
  27673. *
  27674. * The `when` attribute specifies the mappings between plural categories and the actual
  27675. * string to be displayed. The value of the attribute should be a JSON object.
  27676. *
  27677. * The following example shows how to configure ngPluralize:
  27678. *
  27679. * ```html
  27680. * <ng-pluralize count="personCount"
  27681. when="{'0': 'Nobody is viewing.',
  27682. * 'one': '1 person is viewing.',
  27683. * 'other': '{} people are viewing.'}">
  27684. * </ng-pluralize>
  27685. *```
  27686. *
  27687. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  27688. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  27689. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  27690. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  27691. * show "a dozen people are viewing".
  27692. *
  27693. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  27694. * into pluralized strings. In the previous example, Angular will replace `{}` with
  27695. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  27696. * for <span ng-non-bindable>{{numberExpression}}</span>.
  27697. *
  27698. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  27699. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  27700. *
  27701. * # Configuring ngPluralize with offset
  27702. * The `offset` attribute allows further customization of pluralized text, which can result in
  27703. * a better user experience. For example, instead of the message "4 people are viewing this document",
  27704. * you might display "John, Kate and 2 others are viewing this document".
  27705. * The offset attribute allows you to offset a number by any desired value.
  27706. * Let's take a look at an example:
  27707. *
  27708. * ```html
  27709. * <ng-pluralize count="personCount" offset=2
  27710. * when="{'0': 'Nobody is viewing.',
  27711. * '1': '{{person1}} is viewing.',
  27712. * '2': '{{person1}} and {{person2}} are viewing.',
  27713. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  27714. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  27715. * </ng-pluralize>
  27716. * ```
  27717. *
  27718. * Notice that we are still using two plural categories(one, other), but we added
  27719. * three explicit number rules 0, 1 and 2.
  27720. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  27721. * When three people view the document, no explicit number rule is found, so
  27722. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  27723. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  27724. * is shown.
  27725. *
  27726. * Note that when you specify offsets, you must provide explicit number rules for
  27727. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  27728. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  27729. * plural categories "one" and "other".
  27730. *
  27731. * @param {string|expression} count The variable to be bound to.
  27732. * @param {string} when The mapping between plural category to its corresponding strings.
  27733. * @param {number=} offset Offset to deduct from the total number.
  27734. *
  27735. * @example
  27736. <example module="pluralizeExample" name="ng-pluralize">
  27737. <file name="index.html">
  27738. <script>
  27739. angular.module('pluralizeExample', [])
  27740. .controller('ExampleController', ['$scope', function($scope) {
  27741. $scope.person1 = 'Igor';
  27742. $scope.person2 = 'Misko';
  27743. $scope.personCount = 1;
  27744. }]);
  27745. </script>
  27746. <div ng-controller="ExampleController">
  27747. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  27748. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  27749. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  27750. <!--- Example with simple pluralization rules for en locale --->
  27751. Without Offset:
  27752. <ng-pluralize count="personCount"
  27753. when="{'0': 'Nobody is viewing.',
  27754. 'one': '1 person is viewing.',
  27755. 'other': '{} people are viewing.'}">
  27756. </ng-pluralize><br>
  27757. <!--- Example with offset --->
  27758. With Offset(2):
  27759. <ng-pluralize count="personCount" offset=2
  27760. when="{'0': 'Nobody is viewing.',
  27761. '1': '{{person1}} is viewing.',
  27762. '2': '{{person1}} and {{person2}} are viewing.',
  27763. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  27764. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  27765. </ng-pluralize>
  27766. </div>
  27767. </file>
  27768. <file name="protractor.js" type="protractor">
  27769. it('should show correct pluralized string', function() {
  27770. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  27771. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  27772. var countInput = element(by.model('personCount'));
  27773. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  27774. expect(withOffset.getText()).toEqual('Igor is viewing.');
  27775. countInput.clear();
  27776. countInput.sendKeys('0');
  27777. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  27778. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  27779. countInput.clear();
  27780. countInput.sendKeys('2');
  27781. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  27782. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  27783. countInput.clear();
  27784. countInput.sendKeys('3');
  27785. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  27786. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  27787. countInput.clear();
  27788. countInput.sendKeys('4');
  27789. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  27790. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  27791. });
  27792. it('should show data-bound names', function() {
  27793. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  27794. var personCount = element(by.model('personCount'));
  27795. var person1 = element(by.model('person1'));
  27796. var person2 = element(by.model('person2'));
  27797. personCount.clear();
  27798. personCount.sendKeys('4');
  27799. person1.clear();
  27800. person1.sendKeys('Di');
  27801. person2.clear();
  27802. person2.sendKeys('Vojta');
  27803. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  27804. });
  27805. </file>
  27806. </example>
  27807. */
  27808. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  27809. var BRACE = /{}/g,
  27810. IS_WHEN = /^when(Minus)?(.+)$/;
  27811. return {
  27812. link: function(scope, element, attr) {
  27813. var numberExp = attr.count,
  27814. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  27815. offset = attr.offset || 0,
  27816. whens = scope.$eval(whenExp) || {},
  27817. whensExpFns = {},
  27818. startSymbol = $interpolate.startSymbol(),
  27819. endSymbol = $interpolate.endSymbol(),
  27820. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  27821. watchRemover = angular.noop,
  27822. lastCount;
  27823. forEach(attr, function(expression, attributeName) {
  27824. var tmpMatch = IS_WHEN.exec(attributeName);
  27825. if (tmpMatch) {
  27826. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  27827. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  27828. }
  27829. });
  27830. forEach(whens, function(expression, key) {
  27831. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  27832. });
  27833. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  27834. var count = parseFloat(newVal);
  27835. var countIsNaN = isNumberNaN(count);
  27836. if (!countIsNaN && !(count in whens)) {
  27837. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  27838. // Otherwise, check it against pluralization rules in $locale service.
  27839. count = $locale.pluralCat(count - offset);
  27840. }
  27841. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  27842. // In JS `NaN !== NaN`, so we have to explicitly check.
  27843. if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
  27844. watchRemover();
  27845. var whenExpFn = whensExpFns[count];
  27846. if (isUndefined(whenExpFn)) {
  27847. if (newVal != null) {
  27848. $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
  27849. }
  27850. watchRemover = noop;
  27851. updateElementText();
  27852. } else {
  27853. watchRemover = scope.$watch(whenExpFn, updateElementText);
  27854. }
  27855. lastCount = count;
  27856. }
  27857. });
  27858. function updateElementText(newText) {
  27859. element.text(newText || '');
  27860. }
  27861. }
  27862. };
  27863. }];
  27864. /* exported ngRepeatDirective */
  27865. /**
  27866. * @ngdoc directive
  27867. * @name ngRepeat
  27868. * @multiElement
  27869. * @restrict A
  27870. *
  27871. * @description
  27872. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  27873. * instance gets its own scope, where the given loop variable is set to the current collection item,
  27874. * and `$index` is set to the item index or key.
  27875. *
  27876. * Special properties are exposed on the local scope of each template instance, including:
  27877. *
  27878. * | Variable | Type | Details |
  27879. * |-----------|-----------------|-----------------------------------------------------------------------------|
  27880. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  27881. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  27882. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  27883. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  27884. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  27885. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  27886. *
  27887. * <div class="alert alert-info">
  27888. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  27889. * This may be useful when, for instance, nesting ngRepeats.
  27890. * </div>
  27891. *
  27892. *
  27893. * # Iterating over object properties
  27894. *
  27895. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  27896. * syntax:
  27897. *
  27898. * ```js
  27899. * <div ng-repeat="(key, value) in myObj"> ... </div>
  27900. * ```
  27901. *
  27902. * However, there are a few limitations compared to array iteration:
  27903. *
  27904. * - The JavaScript specification does not define the order of keys
  27905. * returned for an object, so Angular relies on the order returned by the browser
  27906. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  27907. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  27908. * and reinstated. See the
  27909. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  27910. *
  27911. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  27912. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  27913. *
  27914. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  27915. * objects, and will throw an error if used with one.
  27916. *
  27917. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  27918. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  27919. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  27920. * or implement a `$watch` on the object yourself.
  27921. *
  27922. *
  27923. * # Tracking and Duplicates
  27924. *
  27925. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  27926. * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:
  27927. *
  27928. * * When an item is added, a new instance of the template is added to the DOM.
  27929. * * When an item is removed, its template instance is removed from the DOM.
  27930. * * When items are reordered, their respective templates are reordered in the DOM.
  27931. *
  27932. * To minimize creation of DOM elements, `ngRepeat` uses a function
  27933. * to "keep track" of all items in the collection and their corresponding DOM elements.
  27934. * For example, if an item is added to the collection, `ngRepeat` will know that all other items
  27935. * already have DOM elements, and will not re-render them.
  27936. *
  27937. * The default tracking function (which tracks items by their identity) does not allow
  27938. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  27939. * to maintain a one-to-one mapping between collection items and DOM elements.
  27940. *
  27941. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  27942. * with your own using the `track by` expression.
  27943. *
  27944. * For example, you may track items by the index of each item in the collection, using the
  27945. * special scope property `$index`:
  27946. * ```html
  27947. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  27948. * {{n}}
  27949. * </div>
  27950. * ```
  27951. *
  27952. * You may also use arbitrary expressions in `track by`, including references to custom functions
  27953. * on the scope:
  27954. * ```html
  27955. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  27956. * {{n}}
  27957. * </div>
  27958. * ```
  27959. *
  27960. * <div class="alert alert-success">
  27961. * If you are working with objects that have a unique identifier property, you should track
  27962. * by this identifier instead of the object instance. Should you reload your data later, `ngRepeat`
  27963. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  27964. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  27965. * this significantly improves rendering performance. If you don't have a unique identifier,
  27966. * `track by $index` can also provide a performance boost.
  27967. * </div>
  27968. *
  27969. * ```html
  27970. * <div ng-repeat="model in collection track by model.id">
  27971. * {{model.name}}
  27972. * </div>
  27973. * ```
  27974. *
  27975. * <br />
  27976. * <div class="alert alert-warning">
  27977. * Avoid using `track by $index` when the repeated template contains
  27978. * {@link guide/expression#one-time-binding one-time bindings}. In such cases, the `nth` DOM
  27979. * element will always be matched with the `nth` item of the array, so the bindings on that element
  27980. * will not be updated even when the corresponding item changes, essentially causing the view to get
  27981. * out-of-sync with the underlying data.
  27982. * </div>
  27983. *
  27984. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  27985. * `$id` function, which tracks items by their identity:
  27986. * ```html
  27987. * <div ng-repeat="obj in collection track by $id(obj)">
  27988. * {{obj.prop}}
  27989. * </div>
  27990. * ```
  27991. *
  27992. * <br />
  27993. * <div class="alert alert-warning">
  27994. * **Note:** `track by` must always be the last expression:
  27995. * </div>
  27996. * ```
  27997. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  27998. * {{model.name}}
  27999. * </div>
  28000. * ```
  28001. *
  28002. *
  28003. * # Special repeat start and end points
  28004. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  28005. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  28006. * 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)
  28007. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  28008. *
  28009. * The example below makes use of this feature:
  28010. * ```html
  28011. * <header ng-repeat-start="item in items">
  28012. * Header {{ item }}
  28013. * </header>
  28014. * <div class="body">
  28015. * Body {{ item }}
  28016. * </div>
  28017. * <footer ng-repeat-end>
  28018. * Footer {{ item }}
  28019. * </footer>
  28020. * ```
  28021. *
  28022. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  28023. * ```html
  28024. * <header>
  28025. * Header A
  28026. * </header>
  28027. * <div class="body">
  28028. * Body A
  28029. * </div>
  28030. * <footer>
  28031. * Footer A
  28032. * </footer>
  28033. * <header>
  28034. * Header B
  28035. * </header>
  28036. * <div class="body">
  28037. * Body B
  28038. * </div>
  28039. * <footer>
  28040. * Footer B
  28041. * </footer>
  28042. * ```
  28043. *
  28044. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  28045. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  28046. *
  28047. * @animations
  28048. * | Animation | Occurs |
  28049. * |----------------------------------|-------------------------------------|
  28050. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  28051. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  28052. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  28053. *
  28054. * See the example below for defining CSS animations with ngRepeat.
  28055. *
  28056. * @element ANY
  28057. * @scope
  28058. * @priority 1000
  28059. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  28060. * formats are currently supported:
  28061. *
  28062. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  28063. * is a scope expression giving the collection to enumerate.
  28064. *
  28065. * For example: `album in artist.albums`.
  28066. *
  28067. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  28068. * and `expression` is the scope expression giving the collection to enumerate.
  28069. *
  28070. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  28071. *
  28072. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  28073. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  28074. * is specified, ng-repeat associates elements by identity. It is an error to have
  28075. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  28076. * mapped to the same DOM element, which is not possible.)
  28077. *
  28078. * Note that the tracking expression must come last, after any filters, and the alias expression.
  28079. *
  28080. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  28081. * will be associated by item identity in the array.
  28082. *
  28083. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  28084. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  28085. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  28086. * element in the same way in the DOM.
  28087. *
  28088. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  28089. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  28090. * property is same.
  28091. *
  28092. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  28093. * to items in conjunction with a tracking expression.
  28094. *
  28095. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  28096. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  28097. * when a filter is active on the repeater, but the filtered result set is empty.
  28098. *
  28099. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  28100. * the items have been processed through the filter.
  28101. *
  28102. * Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
  28103. * (and not as operator, inside an expression).
  28104. *
  28105. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  28106. *
  28107. * @example
  28108. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  28109. * results by name or by age. New (entering) and removed (leaving) items are animated.
  28110. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true" name="ng-repeat">
  28111. <file name="index.html">
  28112. <div ng-controller="repeatController">
  28113. I have {{friends.length}} friends. They are:
  28114. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  28115. <ul class="example-animate-container">
  28116. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  28117. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  28118. </li>
  28119. <li class="animate-repeat" ng-if="results.length === 0">
  28120. <strong>No results found...</strong>
  28121. </li>
  28122. </ul>
  28123. </div>
  28124. </file>
  28125. <file name="script.js">
  28126. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  28127. $scope.friends = [
  28128. {name:'John', age:25, gender:'boy'},
  28129. {name:'Jessie', age:30, gender:'girl'},
  28130. {name:'Johanna', age:28, gender:'girl'},
  28131. {name:'Joy', age:15, gender:'girl'},
  28132. {name:'Mary', age:28, gender:'girl'},
  28133. {name:'Peter', age:95, gender:'boy'},
  28134. {name:'Sebastian', age:50, gender:'boy'},
  28135. {name:'Erika', age:27, gender:'girl'},
  28136. {name:'Patrick', age:40, gender:'boy'},
  28137. {name:'Samantha', age:60, gender:'girl'}
  28138. ];
  28139. });
  28140. </file>
  28141. <file name="animations.css">
  28142. .example-animate-container {
  28143. background:white;
  28144. border:1px solid black;
  28145. list-style:none;
  28146. margin:0;
  28147. padding:0 10px;
  28148. }
  28149. .animate-repeat {
  28150. line-height:30px;
  28151. list-style:none;
  28152. box-sizing:border-box;
  28153. }
  28154. .animate-repeat.ng-move,
  28155. .animate-repeat.ng-enter,
  28156. .animate-repeat.ng-leave {
  28157. transition:all linear 0.5s;
  28158. }
  28159. .animate-repeat.ng-leave.ng-leave-active,
  28160. .animate-repeat.ng-move,
  28161. .animate-repeat.ng-enter {
  28162. opacity:0;
  28163. max-height:0;
  28164. }
  28165. .animate-repeat.ng-leave,
  28166. .animate-repeat.ng-move.ng-move-active,
  28167. .animate-repeat.ng-enter.ng-enter-active {
  28168. opacity:1;
  28169. max-height:30px;
  28170. }
  28171. </file>
  28172. <file name="protractor.js" type="protractor">
  28173. var friends = element.all(by.repeater('friend in friends'));
  28174. it('should render initial data set', function() {
  28175. expect(friends.count()).toBe(10);
  28176. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  28177. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  28178. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  28179. expect(element(by.binding('friends.length')).getText())
  28180. .toMatch("I have 10 friends. They are:");
  28181. });
  28182. it('should update repeater when filter predicate changes', function() {
  28183. expect(friends.count()).toBe(10);
  28184. element(by.model('q')).sendKeys('ma');
  28185. expect(friends.count()).toBe(2);
  28186. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  28187. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  28188. });
  28189. </file>
  28190. </example>
  28191. */
  28192. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  28193. var NG_REMOVED = '$$NG_REMOVED';
  28194. var ngRepeatMinErr = minErr('ngRepeat');
  28195. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  28196. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  28197. scope[valueIdentifier] = value;
  28198. if (keyIdentifier) scope[keyIdentifier] = key;
  28199. scope.$index = index;
  28200. scope.$first = (index === 0);
  28201. scope.$last = (index === (arrayLength - 1));
  28202. scope.$middle = !(scope.$first || scope.$last);
  28203. // eslint-disable-next-line no-bitwise
  28204. scope.$odd = !(scope.$even = (index & 1) === 0);
  28205. };
  28206. var getBlockStart = function(block) {
  28207. return block.clone[0];
  28208. };
  28209. var getBlockEnd = function(block) {
  28210. return block.clone[block.clone.length - 1];
  28211. };
  28212. return {
  28213. restrict: 'A',
  28214. multiElement: true,
  28215. transclude: 'element',
  28216. priority: 1000,
  28217. terminal: true,
  28218. $$tlb: true,
  28219. compile: function ngRepeatCompile($element, $attr) {
  28220. var expression = $attr.ngRepeat;
  28221. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  28222. 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*$/);
  28223. if (!match) {
  28224. throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
  28225. expression);
  28226. }
  28227. var lhs = match[1];
  28228. var rhs = match[2];
  28229. var aliasAs = match[3];
  28230. var trackByExp = match[4];
  28231. match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
  28232. if (!match) {
  28233. throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
  28234. lhs);
  28235. }
  28236. var valueIdentifier = match[3] || match[1];
  28237. var keyIdentifier = match[2];
  28238. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  28239. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  28240. throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
  28241. aliasAs);
  28242. }
  28243. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  28244. var hashFnLocals = {$id: hashKey};
  28245. if (trackByExp) {
  28246. trackByExpGetter = $parse(trackByExp);
  28247. } else {
  28248. trackByIdArrayFn = function(key, value) {
  28249. return hashKey(value);
  28250. };
  28251. trackByIdObjFn = function(key) {
  28252. return key;
  28253. };
  28254. }
  28255. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  28256. if (trackByExpGetter) {
  28257. trackByIdExpFn = function(key, value, index) {
  28258. // assign key, value, and $index to the locals so that they can be used in hash functions
  28259. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  28260. hashFnLocals[valueIdentifier] = value;
  28261. hashFnLocals.$index = index;
  28262. return trackByExpGetter($scope, hashFnLocals);
  28263. };
  28264. }
  28265. // Store a list of elements from previous run. This is a hash where key is the item from the
  28266. // iterator, and the value is objects with following properties.
  28267. // - scope: bound scope
  28268. // - element: previous element.
  28269. // - index: position
  28270. //
  28271. // We are using no-proto object so that we don't need to guard against inherited props via
  28272. // hasOwnProperty.
  28273. var lastBlockMap = createMap();
  28274. //watch props
  28275. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  28276. var index, length,
  28277. previousNode = $element[0], // node that cloned nodes should be inserted after
  28278. // initialized to the comment node anchor
  28279. nextNode,
  28280. // Same as lastBlockMap but it has the current state. It will become the
  28281. // lastBlockMap on the next iteration.
  28282. nextBlockMap = createMap(),
  28283. collectionLength,
  28284. key, value, // key/value of iteration
  28285. trackById,
  28286. trackByIdFn,
  28287. collectionKeys,
  28288. block, // last object information {scope, element, id}
  28289. nextBlockOrder,
  28290. elementsToRemove;
  28291. if (aliasAs) {
  28292. $scope[aliasAs] = collection;
  28293. }
  28294. if (isArrayLike(collection)) {
  28295. collectionKeys = collection;
  28296. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  28297. } else {
  28298. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  28299. // if object, extract keys, in enumeration order, unsorted
  28300. collectionKeys = [];
  28301. for (var itemKey in collection) {
  28302. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  28303. collectionKeys.push(itemKey);
  28304. }
  28305. }
  28306. }
  28307. collectionLength = collectionKeys.length;
  28308. nextBlockOrder = new Array(collectionLength);
  28309. // locate existing items
  28310. for (index = 0; index < collectionLength; index++) {
  28311. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28312. value = collection[key];
  28313. trackById = trackByIdFn(key, value, index);
  28314. if (lastBlockMap[trackById]) {
  28315. // found previously seen block
  28316. block = lastBlockMap[trackById];
  28317. delete lastBlockMap[trackById];
  28318. nextBlockMap[trackById] = block;
  28319. nextBlockOrder[index] = block;
  28320. } else if (nextBlockMap[trackById]) {
  28321. // if collision detected. restore lastBlockMap and throw an error
  28322. forEach(nextBlockOrder, function(block) {
  28323. if (block && block.scope) lastBlockMap[block.id] = block;
  28324. });
  28325. throw ngRepeatMinErr('dupes',
  28326. 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
  28327. expression, trackById, value);
  28328. } else {
  28329. // new never before seen block
  28330. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  28331. nextBlockMap[trackById] = true;
  28332. }
  28333. }
  28334. // remove leftover items
  28335. for (var blockKey in lastBlockMap) {
  28336. block = lastBlockMap[blockKey];
  28337. elementsToRemove = getBlockNodes(block.clone);
  28338. $animate.leave(elementsToRemove);
  28339. if (elementsToRemove[0].parentNode) {
  28340. // if the element was not removed yet because of pending animation, mark it as deleted
  28341. // so that we can ignore it later
  28342. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  28343. elementsToRemove[index][NG_REMOVED] = true;
  28344. }
  28345. }
  28346. block.scope.$destroy();
  28347. }
  28348. // we are not using forEach for perf reasons (trying to avoid #call)
  28349. for (index = 0; index < collectionLength; index++) {
  28350. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28351. value = collection[key];
  28352. block = nextBlockOrder[index];
  28353. if (block.scope) {
  28354. // if we have already seen this object, then we need to reuse the
  28355. // associated scope/element
  28356. nextNode = previousNode;
  28357. // skip nodes that are already pending removal via leave animation
  28358. do {
  28359. nextNode = nextNode.nextSibling;
  28360. } while (nextNode && nextNode[NG_REMOVED]);
  28361. if (getBlockStart(block) !== nextNode) {
  28362. // existing item which got moved
  28363. $animate.move(getBlockNodes(block.clone), null, previousNode);
  28364. }
  28365. previousNode = getBlockEnd(block);
  28366. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28367. } else {
  28368. // new item which we don't know about
  28369. $transclude(function ngRepeatTransclude(clone, scope) {
  28370. block.scope = scope;
  28371. // http://jsperf.com/clone-vs-createcomment
  28372. var endNode = ngRepeatEndComment.cloneNode(false);
  28373. clone[clone.length++] = endNode;
  28374. $animate.enter(clone, null, previousNode);
  28375. previousNode = endNode;
  28376. // Note: We only need the first/last node of the cloned nodes.
  28377. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  28378. // by a directive with templateUrl when its template arrives.
  28379. block.clone = clone;
  28380. nextBlockMap[block.id] = block;
  28381. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28382. });
  28383. }
  28384. }
  28385. lastBlockMap = nextBlockMap;
  28386. });
  28387. };
  28388. }
  28389. };
  28390. }];
  28391. var NG_HIDE_CLASS = 'ng-hide';
  28392. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  28393. /**
  28394. * @ngdoc directive
  28395. * @name ngShow
  28396. * @multiElement
  28397. *
  28398. * @description
  28399. * The `ngShow` directive shows or hides the given HTML element based on the expression provided to
  28400. * the `ngShow` attribute.
  28401. *
  28402. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  28403. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  28404. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  28405. * {@link ng.directive:ngCsp ngCsp}).
  28406. *
  28407. * ```html
  28408. * <!-- when $scope.myValue is truthy (element is visible) -->
  28409. * <div ng-show="myValue"></div>
  28410. *
  28411. * <!-- when $scope.myValue is falsy (element is hidden) -->
  28412. * <div ng-show="myValue" class="ng-hide"></div>
  28413. * ```
  28414. *
  28415. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added
  28416. * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide`
  28417. * CSS class is removed from the element causing the element not to appear hidden.
  28418. *
  28419. * ## Why is `!important` used?
  28420. *
  28421. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  28422. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  28423. * simple as changing the display style on a HTML list item would make hidden elements appear
  28424. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  28425. *
  28426. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  28427. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  28428. * developer chooses to override the styling to change how to hide an element then it is just a
  28429. * matter of using `!important` in their own CSS code.
  28430. *
  28431. * ### Overriding `.ng-hide`
  28432. *
  28433. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  28434. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  28435. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  28436. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  28437. *
  28438. * ```css
  28439. * .ng-hide:not(.ng-hide-animate) {
  28440. * /&#42; These are just alternative ways of hiding an element &#42;/
  28441. * display: block!important;
  28442. * position: absolute;
  28443. * top: -9999px;
  28444. * left: -9999px;
  28445. * }
  28446. * ```
  28447. *
  28448. * By default you don't need to override anything in CSS and the animations will work around the
  28449. * display style.
  28450. *
  28451. * ## A note about animations with `ngShow`
  28452. *
  28453. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  28454. * directive expression is true and false. This system works like the animation system present with
  28455. * `ngClass` except that you must also include the `!important` flag to override the display
  28456. * property so that the elements are not actually hidden during the animation.
  28457. *
  28458. * ```css
  28459. * /&#42; A working example can be found at the bottom of this page. &#42;/
  28460. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28461. * transition: all 0.5s linear;
  28462. * }
  28463. *
  28464. * .my-element.ng-hide-add { ... }
  28465. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  28466. * .my-element.ng-hide-remove { ... }
  28467. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  28468. * ```
  28469. *
  28470. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  28471. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  28472. *
  28473. * @animations
  28474. * | Animation | Occurs |
  28475. * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
  28476. * | {@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. |
  28477. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. |
  28478. *
  28479. * @element ANY
  28480. * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the
  28481. * element is shown/hidden respectively.
  28482. *
  28483. * @example
  28484. * A simple example, animating the element's opacity:
  28485. *
  28486. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-simple">
  28487. <file name="index.html">
  28488. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  28489. <div class="check-element animate-show-hide" ng-show="checked">
  28490. I show up when your checkbox is checked.
  28491. </div>
  28492. </file>
  28493. <file name="animations.css">
  28494. .animate-show-hide.ng-hide {
  28495. opacity: 0;
  28496. }
  28497. .animate-show-hide.ng-hide-add,
  28498. .animate-show-hide.ng-hide-remove {
  28499. transition: all linear 0.5s;
  28500. }
  28501. .check-element {
  28502. border: 1px solid black;
  28503. opacity: 1;
  28504. padding: 10px;
  28505. }
  28506. </file>
  28507. <file name="protractor.js" type="protractor">
  28508. it('should check ngShow', function() {
  28509. var checkbox = element(by.model('checked'));
  28510. var checkElem = element(by.css('.check-element'));
  28511. expect(checkElem.isDisplayed()).toBe(false);
  28512. checkbox.click();
  28513. expect(checkElem.isDisplayed()).toBe(true);
  28514. });
  28515. </file>
  28516. </example>
  28517. *
  28518. * <hr />
  28519. * @example
  28520. * A more complex example, featuring different show/hide animations:
  28521. *
  28522. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-complex">
  28523. <file name="index.html">
  28524. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  28525. <div class="check-element funky-show-hide" ng-show="checked">
  28526. I show up when your checkbox is checked.
  28527. </div>
  28528. </file>
  28529. <file name="animations.css">
  28530. body {
  28531. overflow: hidden;
  28532. perspective: 1000px;
  28533. }
  28534. .funky-show-hide.ng-hide-add {
  28535. transform: rotateZ(0);
  28536. transform-origin: right;
  28537. transition: all 0.5s ease-in-out;
  28538. }
  28539. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  28540. transform: rotateZ(-135deg);
  28541. }
  28542. .funky-show-hide.ng-hide-remove {
  28543. transform: rotateY(90deg);
  28544. transform-origin: left;
  28545. transition: all 0.5s ease;
  28546. }
  28547. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  28548. transform: rotateY(0);
  28549. }
  28550. .check-element {
  28551. border: 1px solid black;
  28552. opacity: 1;
  28553. padding: 10px;
  28554. }
  28555. </file>
  28556. <file name="protractor.js" type="protractor">
  28557. it('should check ngShow', function() {
  28558. var checkbox = element(by.model('checked'));
  28559. var checkElem = element(by.css('.check-element'));
  28560. expect(checkElem.isDisplayed()).toBe(false);
  28561. checkbox.click();
  28562. expect(checkElem.isDisplayed()).toBe(true);
  28563. });
  28564. </file>
  28565. </example>
  28566. */
  28567. var ngShowDirective = ['$animate', function($animate) {
  28568. return {
  28569. restrict: 'A',
  28570. multiElement: true,
  28571. link: function(scope, element, attr) {
  28572. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  28573. // we're adding a temporary, animation-specific class for ng-hide since this way
  28574. // we can control when the element is actually displayed on screen without having
  28575. // to have a global/greedy CSS selector that breaks when other animations are run.
  28576. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  28577. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  28578. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  28579. });
  28580. });
  28581. }
  28582. };
  28583. }];
  28584. /**
  28585. * @ngdoc directive
  28586. * @name ngHide
  28587. * @multiElement
  28588. *
  28589. * @description
  28590. * The `ngHide` directive shows or hides the given HTML element based on the expression provided to
  28591. * the `ngHide` attribute.
  28592. *
  28593. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  28594. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  28595. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  28596. * {@link ng.directive:ngCsp ngCsp}).
  28597. *
  28598. * ```html
  28599. * <!-- when $scope.myValue is truthy (element is hidden) -->
  28600. * <div ng-hide="myValue" class="ng-hide"></div>
  28601. *
  28602. * <!-- when $scope.myValue is falsy (element is visible) -->
  28603. * <div ng-hide="myValue"></div>
  28604. * ```
  28605. *
  28606. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added
  28607. * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide`
  28608. * CSS class is removed from the element causing the element not to appear hidden.
  28609. *
  28610. * ## Why is `!important` used?
  28611. *
  28612. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  28613. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  28614. * simple as changing the display style on a HTML list item would make hidden elements appear
  28615. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  28616. *
  28617. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  28618. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  28619. * developer chooses to override the styling to change how to hide an element then it is just a
  28620. * matter of using `!important` in their own CSS code.
  28621. *
  28622. * ### Overriding `.ng-hide`
  28623. *
  28624. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  28625. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  28626. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  28627. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  28628. *
  28629. * ```css
  28630. * .ng-hide:not(.ng-hide-animate) {
  28631. * /&#42; These are just alternative ways of hiding an element &#42;/
  28632. * display: block!important;
  28633. * position: absolute;
  28634. * top: -9999px;
  28635. * left: -9999px;
  28636. * }
  28637. * ```
  28638. *
  28639. * By default you don't need to override in CSS anything and the animations will work around the
  28640. * display style.
  28641. *
  28642. * ## A note about animations with `ngHide`
  28643. *
  28644. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  28645. * directive expression is true and false. This system works like the animation system present with
  28646. * `ngClass` except that you must also include the `!important` flag to override the display
  28647. * property so that the elements are not actually hidden during the animation.
  28648. *
  28649. * ```css
  28650. * /&#42; A working example can be found at the bottom of this page. &#42;/
  28651. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28652. * transition: all 0.5s linear;
  28653. * }
  28654. *
  28655. * .my-element.ng-hide-add { ... }
  28656. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  28657. * .my-element.ng-hide-remove { ... }
  28658. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  28659. * ```
  28660. *
  28661. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  28662. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  28663. *
  28664. * @animations
  28665. * | Animation | Occurs |
  28666. * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------|
  28667. * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. |
  28668. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. |
  28669. *
  28670. *
  28671. * @element ANY
  28672. * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the
  28673. * element is hidden/shown respectively.
  28674. *
  28675. * @example
  28676. * A simple example, animating the element's opacity:
  28677. *
  28678. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-simple">
  28679. <file name="index.html">
  28680. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  28681. <div class="check-element animate-show-hide" ng-hide="checked">
  28682. I hide when your checkbox is checked.
  28683. </div>
  28684. </file>
  28685. <file name="animations.css">
  28686. .animate-show-hide.ng-hide {
  28687. opacity: 0;
  28688. }
  28689. .animate-show-hide.ng-hide-add,
  28690. .animate-show-hide.ng-hide-remove {
  28691. transition: all linear 0.5s;
  28692. }
  28693. .check-element {
  28694. border: 1px solid black;
  28695. opacity: 1;
  28696. padding: 10px;
  28697. }
  28698. </file>
  28699. <file name="protractor.js" type="protractor">
  28700. it('should check ngHide', function() {
  28701. var checkbox = element(by.model('checked'));
  28702. var checkElem = element(by.css('.check-element'));
  28703. expect(checkElem.isDisplayed()).toBe(true);
  28704. checkbox.click();
  28705. expect(checkElem.isDisplayed()).toBe(false);
  28706. });
  28707. </file>
  28708. </example>
  28709. *
  28710. * <hr />
  28711. * @example
  28712. * A more complex example, featuring different show/hide animations:
  28713. *
  28714. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-complex">
  28715. <file name="index.html">
  28716. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  28717. <div class="check-element funky-show-hide" ng-hide="checked">
  28718. I hide when your checkbox is checked.
  28719. </div>
  28720. </file>
  28721. <file name="animations.css">
  28722. body {
  28723. overflow: hidden;
  28724. perspective: 1000px;
  28725. }
  28726. .funky-show-hide.ng-hide-add {
  28727. transform: rotateZ(0);
  28728. transform-origin: right;
  28729. transition: all 0.5s ease-in-out;
  28730. }
  28731. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  28732. transform: rotateZ(-135deg);
  28733. }
  28734. .funky-show-hide.ng-hide-remove {
  28735. transform: rotateY(90deg);
  28736. transform-origin: left;
  28737. transition: all 0.5s ease;
  28738. }
  28739. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  28740. transform: rotateY(0);
  28741. }
  28742. .check-element {
  28743. border: 1px solid black;
  28744. opacity: 1;
  28745. padding: 10px;
  28746. }
  28747. </file>
  28748. <file name="protractor.js" type="protractor">
  28749. it('should check ngHide', function() {
  28750. var checkbox = element(by.model('checked'));
  28751. var checkElem = element(by.css('.check-element'));
  28752. expect(checkElem.isDisplayed()).toBe(true);
  28753. checkbox.click();
  28754. expect(checkElem.isDisplayed()).toBe(false);
  28755. });
  28756. </file>
  28757. </example>
  28758. */
  28759. var ngHideDirective = ['$animate', function($animate) {
  28760. return {
  28761. restrict: 'A',
  28762. multiElement: true,
  28763. link: function(scope, element, attr) {
  28764. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  28765. // The comment inside of the ngShowDirective explains why we add and
  28766. // remove a temporary class for the show/hide animation
  28767. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  28768. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  28769. });
  28770. });
  28771. }
  28772. };
  28773. }];
  28774. /**
  28775. * @ngdoc directive
  28776. * @name ngStyle
  28777. * @restrict AC
  28778. *
  28779. * @description
  28780. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  28781. *
  28782. * @knownIssue
  28783. * You should not use {@link guide/interpolation interpolation} in the value of the `style`
  28784. * attribute, when using the `ngStyle` directive on the same element.
  28785. * See {@link guide/interpolation#known-issues here} for more info.
  28786. *
  28787. * @element ANY
  28788. * @param {expression} ngStyle
  28789. *
  28790. * {@link guide/expression Expression} which evals to an
  28791. * object whose keys are CSS style names and values are corresponding values for those CSS
  28792. * keys.
  28793. *
  28794. * Since some CSS style names are not valid keys for an object, they must be quoted.
  28795. * See the 'background-color' style in the example below.
  28796. *
  28797. * @example
  28798. <example name="ng-style">
  28799. <file name="index.html">
  28800. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  28801. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  28802. <input type="button" value="clear" ng-click="myStyle={}">
  28803. <br/>
  28804. <span ng-style="myStyle">Sample Text</span>
  28805. <pre>myStyle={{myStyle}}</pre>
  28806. </file>
  28807. <file name="style.css">
  28808. span {
  28809. color: black;
  28810. }
  28811. </file>
  28812. <file name="protractor.js" type="protractor">
  28813. var colorSpan = element(by.css('span'));
  28814. it('should check ng-style', function() {
  28815. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  28816. element(by.css('input[value=\'set color\']')).click();
  28817. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  28818. element(by.css('input[value=clear]')).click();
  28819. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  28820. });
  28821. </file>
  28822. </example>
  28823. */
  28824. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  28825. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  28826. if (oldStyles && (newStyles !== oldStyles)) {
  28827. forEach(oldStyles, function(val, style) { element.css(style, '');});
  28828. }
  28829. if (newStyles) element.css(newStyles);
  28830. }, true);
  28831. });
  28832. /**
  28833. * @ngdoc directive
  28834. * @name ngSwitch
  28835. * @restrict EA
  28836. *
  28837. * @description
  28838. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  28839. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  28840. * as specified in the template.
  28841. *
  28842. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  28843. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  28844. * matches the value obtained from the evaluated expression. In other words, you define a container element
  28845. * (where you place the directive), place an expression on the **`on="..."` attribute**
  28846. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  28847. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  28848. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  28849. * attribute is displayed.
  28850. *
  28851. * <div class="alert alert-info">
  28852. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  28853. * as literal string values to match against.
  28854. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  28855. * value of the expression `$scope.someVal`.
  28856. * </div>
  28857. * @animations
  28858. * | Animation | Occurs |
  28859. * |----------------------------------|-------------------------------------|
  28860. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  28861. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  28862. *
  28863. * @usage
  28864. *
  28865. * ```
  28866. * <ANY ng-switch="expression">
  28867. * <ANY ng-switch-when="matchValue1">...</ANY>
  28868. * <ANY ng-switch-when="matchValue2">...</ANY>
  28869. * <ANY ng-switch-default>...</ANY>
  28870. * </ANY>
  28871. * ```
  28872. *
  28873. *
  28874. * @scope
  28875. * @priority 1200
  28876. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  28877. * On child elements add:
  28878. *
  28879. * * `ngSwitchWhen`: the case statement to match against. If match then this
  28880. * case will be displayed. If the same match appears multiple times, all the
  28881. * elements will be displayed. It is possible to associate multiple values to
  28882. * the same `ngSwitchWhen` by defining the optional attribute
  28883. * `ngSwitchWhenSeparator`. The separator will be used to split the value of
  28884. * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
  28885. * if any of the `ngSwitch` evaluates to any of these tokens.
  28886. * * `ngSwitchDefault`: the default case when no other case match. If there
  28887. * are multiple default cases, all of them will be displayed when no other
  28888. * case match.
  28889. *
  28890. *
  28891. * @example
  28892. <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
  28893. <file name="index.html">
  28894. <div ng-controller="ExampleController">
  28895. <select ng-model="selection" ng-options="item for item in items">
  28896. </select>
  28897. <code>selection={{selection}}</code>
  28898. <hr/>
  28899. <div class="animate-switch-container"
  28900. ng-switch on="selection">
  28901. <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
  28902. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  28903. <div class="animate-switch" ng-switch-default>default</div>
  28904. </div>
  28905. </div>
  28906. </file>
  28907. <file name="script.js">
  28908. angular.module('switchExample', ['ngAnimate'])
  28909. .controller('ExampleController', ['$scope', function($scope) {
  28910. $scope.items = ['settings', 'home', 'options', 'other'];
  28911. $scope.selection = $scope.items[0];
  28912. }]);
  28913. </file>
  28914. <file name="animations.css">
  28915. .animate-switch-container {
  28916. position:relative;
  28917. background:white;
  28918. border:1px solid black;
  28919. height:40px;
  28920. overflow:hidden;
  28921. }
  28922. .animate-switch {
  28923. padding:10px;
  28924. }
  28925. .animate-switch.ng-animate {
  28926. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  28927. position:absolute;
  28928. top:0;
  28929. left:0;
  28930. right:0;
  28931. bottom:0;
  28932. }
  28933. .animate-switch.ng-leave.ng-leave-active,
  28934. .animate-switch.ng-enter {
  28935. top:-50px;
  28936. }
  28937. .animate-switch.ng-leave,
  28938. .animate-switch.ng-enter.ng-enter-active {
  28939. top:0;
  28940. }
  28941. </file>
  28942. <file name="protractor.js" type="protractor">
  28943. var switchElem = element(by.css('[ng-switch]'));
  28944. var select = element(by.model('selection'));
  28945. it('should start in settings', function() {
  28946. expect(switchElem.getText()).toMatch(/Settings Div/);
  28947. });
  28948. it('should change to home', function() {
  28949. select.all(by.css('option')).get(1).click();
  28950. expect(switchElem.getText()).toMatch(/Home Span/);
  28951. });
  28952. it('should change to settings via "options"', function() {
  28953. select.all(by.css('option')).get(2).click();
  28954. expect(switchElem.getText()).toMatch(/Settings Div/);
  28955. });
  28956. it('should select default', function() {
  28957. select.all(by.css('option')).get(3).click();
  28958. expect(switchElem.getText()).toMatch(/default/);
  28959. });
  28960. </file>
  28961. </example>
  28962. */
  28963. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  28964. return {
  28965. require: 'ngSwitch',
  28966. // asks for $scope to fool the BC controller module
  28967. controller: ['$scope', function NgSwitchController() {
  28968. this.cases = {};
  28969. }],
  28970. link: function(scope, element, attr, ngSwitchController) {
  28971. var watchExpr = attr.ngSwitch || attr.on,
  28972. selectedTranscludes = [],
  28973. selectedElements = [],
  28974. previousLeaveAnimations = [],
  28975. selectedScopes = [];
  28976. var spliceFactory = function(array, index) {
  28977. return function(response) {
  28978. if (response !== false) array.splice(index, 1);
  28979. };
  28980. };
  28981. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  28982. var i, ii;
  28983. // Start with the last, in case the array is modified during the loop
  28984. while (previousLeaveAnimations.length) {
  28985. $animate.cancel(previousLeaveAnimations.pop());
  28986. }
  28987. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  28988. var selected = getBlockNodes(selectedElements[i].clone);
  28989. selectedScopes[i].$destroy();
  28990. var runner = previousLeaveAnimations[i] = $animate.leave(selected);
  28991. runner.done(spliceFactory(previousLeaveAnimations, i));
  28992. }
  28993. selectedElements.length = 0;
  28994. selectedScopes.length = 0;
  28995. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  28996. forEach(selectedTranscludes, function(selectedTransclude) {
  28997. selectedTransclude.transclude(function(caseElement, selectedScope) {
  28998. selectedScopes.push(selectedScope);
  28999. var anchor = selectedTransclude.element;
  29000. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  29001. var block = { clone: caseElement };
  29002. selectedElements.push(block);
  29003. $animate.enter(caseElement, anchor.parent(), anchor);
  29004. });
  29005. });
  29006. }
  29007. });
  29008. }
  29009. };
  29010. }];
  29011. var ngSwitchWhenDirective = ngDirective({
  29012. transclude: 'element',
  29013. priority: 1200,
  29014. require: '^ngSwitch',
  29015. multiElement: true,
  29016. link: function(scope, element, attrs, ctrl, $transclude) {
  29017. var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
  29018. // Filter duplicate cases
  29019. function(element, index, array) { return array[index - 1] !== element; }
  29020. );
  29021. forEach(cases, function(whenCase) {
  29022. ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
  29023. ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
  29024. });
  29025. }
  29026. });
  29027. var ngSwitchDefaultDirective = ngDirective({
  29028. transclude: 'element',
  29029. priority: 1200,
  29030. require: '^ngSwitch',
  29031. multiElement: true,
  29032. link: function(scope, element, attr, ctrl, $transclude) {
  29033. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  29034. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  29035. }
  29036. });
  29037. /**
  29038. * @ngdoc directive
  29039. * @name ngTransclude
  29040. * @restrict EAC
  29041. *
  29042. * @description
  29043. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  29044. *
  29045. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  29046. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  29047. *
  29048. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  29049. * content of this element will be removed before the transcluded content is inserted.
  29050. * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback
  29051. * content in the case that no transcluded content is provided.
  29052. *
  29053. * @element ANY
  29054. *
  29055. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  29056. * or its value is the same as the name of the attribute then the default slot is used.
  29057. *
  29058. * @example
  29059. * ### Basic transclusion
  29060. * This example demonstrates basic transclusion of content into a component directive.
  29061. * <example name="simpleTranscludeExample" module="transcludeExample">
  29062. * <file name="index.html">
  29063. * <script>
  29064. * angular.module('transcludeExample', [])
  29065. * .directive('pane', function(){
  29066. * return {
  29067. * restrict: 'E',
  29068. * transclude: true,
  29069. * scope: { title:'@' },
  29070. * template: '<div style="border: 1px solid black;">' +
  29071. * '<div style="background-color: gray">{{title}}</div>' +
  29072. * '<ng-transclude></ng-transclude>' +
  29073. * '</div>'
  29074. * };
  29075. * })
  29076. * .controller('ExampleController', ['$scope', function($scope) {
  29077. * $scope.title = 'Lorem Ipsum';
  29078. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  29079. * }]);
  29080. * </script>
  29081. * <div ng-controller="ExampleController">
  29082. * <input ng-model="title" aria-label="title"> <br/>
  29083. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  29084. * <pane title="{{title}}"><span>{{text}}</span></pane>
  29085. * </div>
  29086. * </file>
  29087. * <file name="protractor.js" type="protractor">
  29088. * it('should have transcluded', function() {
  29089. * var titleElement = element(by.model('title'));
  29090. * titleElement.clear();
  29091. * titleElement.sendKeys('TITLE');
  29092. * var textElement = element(by.model('text'));
  29093. * textElement.clear();
  29094. * textElement.sendKeys('TEXT');
  29095. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  29096. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  29097. * });
  29098. * </file>
  29099. * </example>
  29100. *
  29101. * @example
  29102. * ### Transclude fallback content
  29103. * This example shows how to use `NgTransclude` with fallback content, that
  29104. * is displayed if no transcluded content is provided.
  29105. *
  29106. * <example module="transcludeFallbackContentExample" name="ng-transclude">
  29107. * <file name="index.html">
  29108. * <script>
  29109. * angular.module('transcludeFallbackContentExample', [])
  29110. * .directive('myButton', function(){
  29111. * return {
  29112. * restrict: 'E',
  29113. * transclude: true,
  29114. * scope: true,
  29115. * template: '<button style="cursor: pointer;">' +
  29116. * '<ng-transclude>' +
  29117. * '<b style="color: red;">Button1</b>' +
  29118. * '</ng-transclude>' +
  29119. * '</button>'
  29120. * };
  29121. * });
  29122. * </script>
  29123. * <!-- fallback button content -->
  29124. * <my-button id="fallback"></my-button>
  29125. * <!-- modified button content -->
  29126. * <my-button id="modified">
  29127. * <i style="color: green;">Button2</i>
  29128. * </my-button>
  29129. * </file>
  29130. * <file name="protractor.js" type="protractor">
  29131. * it('should have different transclude element content', function() {
  29132. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  29133. * expect(element(by.id('modified')).getText()).toBe('Button2');
  29134. * });
  29135. * </file>
  29136. * </example>
  29137. *
  29138. * @example
  29139. * ### Multi-slot transclusion
  29140. * This example demonstrates using multi-slot transclusion in a component directive.
  29141. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  29142. * <file name="index.html">
  29143. * <style>
  29144. * .title, .footer {
  29145. * background-color: gray
  29146. * }
  29147. * </style>
  29148. * <div ng-controller="ExampleController">
  29149. * <input ng-model="title" aria-label="title"> <br/>
  29150. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  29151. * <pane>
  29152. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  29153. * <pane-body><p>{{text}}</p></pane-body>
  29154. * </pane>
  29155. * </div>
  29156. * </file>
  29157. * <file name="app.js">
  29158. * angular.module('multiSlotTranscludeExample', [])
  29159. * .directive('pane', function() {
  29160. * return {
  29161. * restrict: 'E',
  29162. * transclude: {
  29163. * 'title': '?paneTitle',
  29164. * 'body': 'paneBody',
  29165. * 'footer': '?paneFooter'
  29166. * },
  29167. * template: '<div style="border: 1px solid black;">' +
  29168. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  29169. * '<div ng-transclude="body"></div>' +
  29170. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  29171. * '</div>'
  29172. * };
  29173. * })
  29174. * .controller('ExampleController', ['$scope', function($scope) {
  29175. * $scope.title = 'Lorem Ipsum';
  29176. * $scope.link = 'https://google.com';
  29177. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  29178. * }]);
  29179. * </file>
  29180. * <file name="protractor.js" type="protractor">
  29181. * it('should have transcluded the title and the body', function() {
  29182. * var titleElement = element(by.model('title'));
  29183. * titleElement.clear();
  29184. * titleElement.sendKeys('TITLE');
  29185. * var textElement = element(by.model('text'));
  29186. * textElement.clear();
  29187. * textElement.sendKeys('TEXT');
  29188. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  29189. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  29190. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  29191. * });
  29192. * </file>
  29193. * </example>
  29194. */
  29195. var ngTranscludeMinErr = minErr('ngTransclude');
  29196. var ngTranscludeDirective = ['$compile', function($compile) {
  29197. return {
  29198. restrict: 'EAC',
  29199. terminal: true,
  29200. compile: function ngTranscludeCompile(tElement) {
  29201. // Remove and cache any original content to act as a fallback
  29202. var fallbackLinkFn = $compile(tElement.contents());
  29203. tElement.empty();
  29204. return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
  29205. if (!$transclude) {
  29206. throw ngTranscludeMinErr('orphan',
  29207. 'Illegal use of ngTransclude directive in the template! ' +
  29208. 'No parent directive that requires a transclusion found. ' +
  29209. 'Element: {0}',
  29210. startingTag($element));
  29211. }
  29212. // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
  29213. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  29214. $attrs.ngTransclude = '';
  29215. }
  29216. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  29217. // If the slot is required and no transclusion content is provided then this call will throw an error
  29218. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  29219. // If the slot is optional and no transclusion content is provided then use the fallback content
  29220. if (slotName && !$transclude.isSlotFilled(slotName)) {
  29221. useFallbackContent();
  29222. }
  29223. function ngTranscludeCloneAttachFn(clone, transcludedScope) {
  29224. if (clone.length && notWhitespace(clone)) {
  29225. $element.append(clone);
  29226. } else {
  29227. useFallbackContent();
  29228. // There is nothing linked against the transcluded scope since no content was available,
  29229. // so it should be safe to clean up the generated scope.
  29230. transcludedScope.$destroy();
  29231. }
  29232. }
  29233. function useFallbackContent() {
  29234. // Since this is the fallback content rather than the transcluded content,
  29235. // we link against the scope of this directive rather than the transcluded scope
  29236. fallbackLinkFn($scope, function(clone) {
  29237. $element.append(clone);
  29238. });
  29239. }
  29240. function notWhitespace(nodes) {
  29241. for (var i = 0, ii = nodes.length; i < ii; i++) {
  29242. var node = nodes[i];
  29243. if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) {
  29244. return true;
  29245. }
  29246. }
  29247. }
  29248. };
  29249. }
  29250. };
  29251. }];
  29252. /**
  29253. * @ngdoc directive
  29254. * @name script
  29255. * @restrict E
  29256. *
  29257. * @description
  29258. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  29259. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  29260. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  29261. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  29262. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  29263. *
  29264. * @param {string} type Must be set to `'text/ng-template'`.
  29265. * @param {string} id Cache name of the template.
  29266. *
  29267. * @example
  29268. <example name="script-tag">
  29269. <file name="index.html">
  29270. <script type="text/ng-template" id="/tpl.html">
  29271. Content of the template.
  29272. </script>
  29273. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  29274. <div id="tpl-content" ng-include src="currentTpl"></div>
  29275. </file>
  29276. <file name="protractor.js" type="protractor">
  29277. it('should load template defined inside script tag', function() {
  29278. element(by.css('#tpl-link')).click();
  29279. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  29280. });
  29281. </file>
  29282. </example>
  29283. */
  29284. var scriptDirective = ['$templateCache', function($templateCache) {
  29285. return {
  29286. restrict: 'E',
  29287. terminal: true,
  29288. compile: function(element, attr) {
  29289. if (attr.type === 'text/ng-template') {
  29290. var templateUrl = attr.id,
  29291. text = element[0].text;
  29292. $templateCache.put(templateUrl, text);
  29293. }
  29294. }
  29295. };
  29296. }];
  29297. /* exported selectDirective, optionDirective */
  29298. var noopNgModelController = { $setViewValue: noop, $render: noop };
  29299. function setOptionSelectedStatus(optionEl, value) {
  29300. optionEl.prop('selected', value); // needed for IE
  29301. /**
  29302. * When unselecting an option, setting the property to null / false should be enough
  29303. * However, screenreaders might react to the selected attribute instead, see
  29304. * https://github.com/angular/angular.js/issues/14419
  29305. * Note: "selected" is a boolean attr and will be removed when the "value" arg in attr() is false
  29306. * or null
  29307. */
  29308. optionEl.attr('selected', value);
  29309. }
  29310. /**
  29311. * @ngdoc type
  29312. * @name select.SelectController
  29313. * @description
  29314. * The controller for the `<select>` directive. This provides support for reading
  29315. * and writing the selected value(s) of the control and also coordinates dynamically
  29316. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  29317. */
  29318. var SelectController =
  29319. ['$element', '$scope', /** @this */ function($element, $scope) {
  29320. var self = this,
  29321. optionsMap = new NgMap();
  29322. self.selectValueMap = {}; // Keys are the hashed values, values the original values
  29323. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  29324. self.ngModelCtrl = noopNgModelController;
  29325. self.multiple = false;
  29326. // The "unknown" option is one that is prepended to the list if the viewValue
  29327. // does not match any of the options. When it is rendered the value of the unknown
  29328. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  29329. //
  29330. // We can't just jqLite('<option>') since jqLite is not smart enough
  29331. // to create it in <select> and IE barfs otherwise.
  29332. self.unknownOption = jqLite(window.document.createElement('option'));
  29333. // The empty option is an option with the value '' that te application developer can
  29334. // provide inside the select. When the model changes to a value that doesn't match an option,
  29335. // it is selected - so if an empty option is provided, no unknown option is generated.
  29336. // However, the empty option is not removed when the model matches an option. It is always selectable
  29337. // and indicates that a "null" selection has been made.
  29338. self.hasEmptyOption = false;
  29339. self.emptyOption = undefined;
  29340. self.renderUnknownOption = function(val) {
  29341. var unknownVal = self.generateUnknownOptionValue(val);
  29342. self.unknownOption.val(unknownVal);
  29343. $element.prepend(self.unknownOption);
  29344. setOptionSelectedStatus(self.unknownOption, true);
  29345. $element.val(unknownVal);
  29346. };
  29347. self.updateUnknownOption = function(val) {
  29348. var unknownVal = self.generateUnknownOptionValue(val);
  29349. self.unknownOption.val(unknownVal);
  29350. setOptionSelectedStatus(self.unknownOption, true);
  29351. $element.val(unknownVal);
  29352. };
  29353. self.generateUnknownOptionValue = function(val) {
  29354. return '? ' + hashKey(val) + ' ?';
  29355. };
  29356. self.removeUnknownOption = function() {
  29357. if (self.unknownOption.parent()) self.unknownOption.remove();
  29358. };
  29359. self.selectEmptyOption = function() {
  29360. if (self.emptyOption) {
  29361. $element.val('');
  29362. setOptionSelectedStatus(self.emptyOption, true);
  29363. }
  29364. };
  29365. self.unselectEmptyOption = function() {
  29366. if (self.hasEmptyOption) {
  29367. self.emptyOption.removeAttr('selected');
  29368. }
  29369. };
  29370. $scope.$on('$destroy', function() {
  29371. // disable unknown option so that we don't do work when the whole select is being destroyed
  29372. self.renderUnknownOption = noop;
  29373. });
  29374. // Read the value of the select control, the implementation of this changes depending
  29375. // upon whether the select can have multiple values and whether ngOptions is at work.
  29376. self.readValue = function readSingleValue() {
  29377. var val = $element.val();
  29378. // ngValue added option values are stored in the selectValueMap, normal interpolations are not
  29379. var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;
  29380. if (self.hasOption(realVal)) {
  29381. return realVal;
  29382. }
  29383. return null;
  29384. };
  29385. // Write the value to the select control, the implementation of this changes depending
  29386. // upon whether the select can have multiple values and whether ngOptions is at work.
  29387. self.writeValue = function writeSingleValue(value) {
  29388. // Make sure to remove the selected attribute from the previously selected option
  29389. // Otherwise, screen readers might get confused
  29390. var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];
  29391. if (currentlySelectedOption) setOptionSelectedStatus(jqLite(currentlySelectedOption), false);
  29392. if (self.hasOption(value)) {
  29393. self.removeUnknownOption();
  29394. var hashedVal = hashKey(value);
  29395. $element.val(hashedVal in self.selectValueMap ? hashedVal : value);
  29396. // Set selected attribute and property on selected option for screen readers
  29397. var selectedOption = $element[0].options[$element[0].selectedIndex];
  29398. setOptionSelectedStatus(jqLite(selectedOption), true);
  29399. } else {
  29400. if (value == null && self.emptyOption) {
  29401. self.removeUnknownOption();
  29402. self.selectEmptyOption();
  29403. } else if (self.unknownOption.parent().length) {
  29404. self.updateUnknownOption(value);
  29405. } else {
  29406. self.renderUnknownOption(value);
  29407. }
  29408. }
  29409. };
  29410. // Tell the select control that an option, with the given value, has been added
  29411. self.addOption = function(value, element) {
  29412. // Skip comment nodes, as they only pollute the `optionsMap`
  29413. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  29414. assertNotHasOwnProperty(value, '"option value"');
  29415. if (value === '') {
  29416. self.hasEmptyOption = true;
  29417. self.emptyOption = element;
  29418. }
  29419. var count = optionsMap.get(value) || 0;
  29420. optionsMap.set(value, count + 1);
  29421. // Only render at the end of a digest. This improves render performance when many options
  29422. // are added during a digest and ensures all relevant options are correctly marked as selected
  29423. scheduleRender();
  29424. };
  29425. // Tell the select control that an option, with the given value, has been removed
  29426. self.removeOption = function(value) {
  29427. var count = optionsMap.get(value);
  29428. if (count) {
  29429. if (count === 1) {
  29430. optionsMap.delete(value);
  29431. if (value === '') {
  29432. self.hasEmptyOption = false;
  29433. self.emptyOption = undefined;
  29434. }
  29435. } else {
  29436. optionsMap.set(value, count - 1);
  29437. }
  29438. }
  29439. };
  29440. // Check whether the select control has an option matching the given value
  29441. self.hasOption = function(value) {
  29442. return !!optionsMap.get(value);
  29443. };
  29444. var renderScheduled = false;
  29445. function scheduleRender() {
  29446. if (renderScheduled) return;
  29447. renderScheduled = true;
  29448. $scope.$$postDigest(function() {
  29449. renderScheduled = false;
  29450. self.ngModelCtrl.$render();
  29451. });
  29452. }
  29453. var updateScheduled = false;
  29454. function scheduleViewValueUpdate(renderAfter) {
  29455. if (updateScheduled) return;
  29456. updateScheduled = true;
  29457. $scope.$$postDigest(function() {
  29458. if ($scope.$$destroyed) return;
  29459. updateScheduled = false;
  29460. self.ngModelCtrl.$setViewValue(self.readValue());
  29461. if (renderAfter) self.ngModelCtrl.$render();
  29462. });
  29463. }
  29464. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  29465. if (optionAttrs.$attr.ngValue) {
  29466. // The value attribute is set by ngValue
  29467. var oldVal, hashedVal = NaN;
  29468. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29469. var removal;
  29470. var previouslySelected = optionElement.prop('selected');
  29471. if (isDefined(hashedVal)) {
  29472. self.removeOption(oldVal);
  29473. delete self.selectValueMap[hashedVal];
  29474. removal = true;
  29475. }
  29476. hashedVal = hashKey(newVal);
  29477. oldVal = newVal;
  29478. self.selectValueMap[hashedVal] = newVal;
  29479. self.addOption(newVal, optionElement);
  29480. // Set the attribute directly instead of using optionAttrs.$set - this stops the observer
  29481. // from firing a second time. Other $observers on value will also get the result of the
  29482. // ngValue expression, not the hashed value
  29483. optionElement.attr('value', hashedVal);
  29484. if (removal && previouslySelected) {
  29485. scheduleViewValueUpdate();
  29486. }
  29487. });
  29488. } else if (interpolateValueFn) {
  29489. // The value attribute is interpolated
  29490. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29491. // This method is overwritten in ngOptions and has side-effects!
  29492. self.readValue();
  29493. var removal;
  29494. var previouslySelected = optionElement.prop('selected');
  29495. if (isDefined(oldVal)) {
  29496. self.removeOption(oldVal);
  29497. removal = true;
  29498. }
  29499. oldVal = newVal;
  29500. self.addOption(newVal, optionElement);
  29501. if (removal && previouslySelected) {
  29502. scheduleViewValueUpdate();
  29503. }
  29504. });
  29505. } else if (interpolateTextFn) {
  29506. // The text content is interpolated
  29507. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  29508. optionAttrs.$set('value', newVal);
  29509. var previouslySelected = optionElement.prop('selected');
  29510. if (oldVal !== newVal) {
  29511. self.removeOption(oldVal);
  29512. }
  29513. self.addOption(newVal, optionElement);
  29514. if (oldVal && previouslySelected) {
  29515. scheduleViewValueUpdate();
  29516. }
  29517. });
  29518. } else {
  29519. // The value attribute is static
  29520. self.addOption(optionAttrs.value, optionElement);
  29521. }
  29522. optionAttrs.$observe('disabled', function(newVal) {
  29523. // Since model updates will also select disabled options (like ngOptions),
  29524. // we only have to handle options becoming disabled, not enabled
  29525. if (newVal === 'true' || newVal && optionElement.prop('selected')) {
  29526. if (self.multiple) {
  29527. scheduleViewValueUpdate(true);
  29528. } else {
  29529. self.ngModelCtrl.$setViewValue(null);
  29530. self.ngModelCtrl.$render();
  29531. }
  29532. }
  29533. });
  29534. optionElement.on('$destroy', function() {
  29535. var currentValue = self.readValue();
  29536. var removeValue = optionAttrs.value;
  29537. self.removeOption(removeValue);
  29538. scheduleRender();
  29539. if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
  29540. currentValue === removeValue
  29541. ) {
  29542. // When multiple (selected) options are destroyed at the same time, we don't want
  29543. // to run a model update for each of them. Instead, run a single update in the $$postDigest
  29544. scheduleViewValueUpdate(true);
  29545. }
  29546. });
  29547. };
  29548. }];
  29549. /**
  29550. * @ngdoc directive
  29551. * @name select
  29552. * @restrict E
  29553. *
  29554. * @description
  29555. * HTML `select` element with angular data-binding.
  29556. *
  29557. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  29558. * between the scope and the `<select>` control (including setting default values).
  29559. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  29560. * {@link ngOptions `ngOptions`} directives.
  29561. *
  29562. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  29563. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  29564. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  29565. * Value and textContent can be interpolated.
  29566. *
  29567. * ## Matching model and option values
  29568. *
  29569. * In general, the match between the model and an option is evaluated by strictly comparing the model
  29570. * value against the value of the available options.
  29571. *
  29572. * If you are setting the option value with the option's `value` attribute, or textContent, the
  29573. * value will always be a `string` which means that the model value must also be a string.
  29574. * Otherwise the `select` directive cannot match them correctly.
  29575. *
  29576. * To bind the model to a non-string value, you can use one of the following strategies:
  29577. * - the {@link ng.ngOptions `ngOptions`} directive
  29578. * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value})
  29579. * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be
  29580. * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example})
  29581. * - model $parsers / $formatters to convert the string value
  29582. * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example})
  29583. *
  29584. * If the viewValue of `ngModel` does not match any of the options, then the control
  29585. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  29586. *
  29587. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  29588. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  29589. * option. See example below for demonstration.
  29590. *
  29591. * ## Choosing between `ngRepeat` and `ngOptions`
  29592. *
  29593. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  29594. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits:
  29595. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  29596. * comprehension expression
  29597. * - reduced memory consumption by not creating a new scope for each repeated instance
  29598. * - increased render speed by creating the options in a documentFragment instead of individually
  29599. *
  29600. * Specifically, select with repeated options slows down significantly starting at 2000 options in
  29601. * Chrome and Internet Explorer / Edge.
  29602. *
  29603. *
  29604. * @param {string} ngModel Assignable angular expression to data-bind to.
  29605. * @param {string=} name Property name of the form under which the control is published.
  29606. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  29607. * bound to the model as an array.
  29608. * @param {string=} required Sets `required` validation error key if the value is not entered.
  29609. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  29610. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  29611. * when you want to data-bind to the required attribute.
  29612. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  29613. * interaction with the select element.
  29614. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  29615. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  29616. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  29617. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  29618. *
  29619. * @example
  29620. * ### Simple `select` elements with static options
  29621. *
  29622. * <example name="static-select" module="staticSelect">
  29623. * <file name="index.html">
  29624. * <div ng-controller="ExampleController">
  29625. * <form name="myForm">
  29626. * <label for="singleSelect"> Single select: </label><br>
  29627. * <select name="singleSelect" ng-model="data.singleSelect">
  29628. * <option value="option-1">Option 1</option>
  29629. * <option value="option-2">Option 2</option>
  29630. * </select><br>
  29631. *
  29632. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  29633. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  29634. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  29635. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  29636. * <option value="option-2">Option 2</option>
  29637. * </select><br>
  29638. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  29639. * <tt>singleSelect = {{data.singleSelect}}</tt>
  29640. *
  29641. * <hr>
  29642. * <label for="multipleSelect"> Multiple select: </label><br>
  29643. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  29644. * <option value="option-1">Option 1</option>
  29645. * <option value="option-2">Option 2</option>
  29646. * <option value="option-3">Option 3</option>
  29647. * </select><br>
  29648. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  29649. * </form>
  29650. * </div>
  29651. * </file>
  29652. * <file name="app.js">
  29653. * angular.module('staticSelect', [])
  29654. * .controller('ExampleController', ['$scope', function($scope) {
  29655. * $scope.data = {
  29656. * singleSelect: null,
  29657. * multipleSelect: [],
  29658. * option1: 'option-1'
  29659. * };
  29660. *
  29661. * $scope.forceUnknownOption = function() {
  29662. * $scope.data.singleSelect = 'nonsense';
  29663. * };
  29664. * }]);
  29665. * </file>
  29666. *</example>
  29667. *
  29668. * ### Using `ngRepeat` to generate `select` options
  29669. * <example name="select-ngrepeat" module="ngrepeatSelect">
  29670. * <file name="index.html">
  29671. * <div ng-controller="ExampleController">
  29672. * <form name="myForm">
  29673. * <label for="repeatSelect"> Repeat select: </label>
  29674. * <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  29675. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  29676. * </select>
  29677. * </form>
  29678. * <hr>
  29679. * <tt>model = {{data.model}}</tt><br/>
  29680. * </div>
  29681. * </file>
  29682. * <file name="app.js">
  29683. * angular.module('ngrepeatSelect', [])
  29684. * .controller('ExampleController', ['$scope', function($scope) {
  29685. * $scope.data = {
  29686. * model: null,
  29687. * availableOptions: [
  29688. * {id: '1', name: 'Option A'},
  29689. * {id: '2', name: 'Option B'},
  29690. * {id: '3', name: 'Option C'}
  29691. * ]
  29692. * };
  29693. * }]);
  29694. * </file>
  29695. *</example>
  29696. *
  29697. * ### Using `ngValue` to bind the model to an array of objects
  29698. * <example name="select-ngvalue" module="ngvalueSelect">
  29699. * <file name="index.html">
  29700. * <div ng-controller="ExampleController">
  29701. * <form name="myForm">
  29702. * <label for="ngvalueselect"> ngvalue select: </label>
  29703. * <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
  29704. * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
  29705. * </select>
  29706. * </form>
  29707. * <hr>
  29708. * <pre>model = {{data.model | json}}</pre><br/>
  29709. * </div>
  29710. * </file>
  29711. * <file name="app.js">
  29712. * angular.module('ngvalueSelect', [])
  29713. * .controller('ExampleController', ['$scope', function($scope) {
  29714. * $scope.data = {
  29715. * model: null,
  29716. * availableOptions: [
  29717. {value: 'myString', name: 'string'},
  29718. {value: 1, name: 'integer'},
  29719. {value: true, name: 'boolean'},
  29720. {value: null, name: 'null'},
  29721. {value: {prop: 'value'}, name: 'object'},
  29722. {value: ['a'], name: 'array'}
  29723. * ]
  29724. * };
  29725. * }]);
  29726. * </file>
  29727. *</example>
  29728. *
  29729. * ### Using `select` with `ngOptions` and setting a default value
  29730. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  29731. *
  29732. * <example name="select-with-default-values" module="defaultValueSelect">
  29733. * <file name="index.html">
  29734. * <div ng-controller="ExampleController">
  29735. * <form name="myForm">
  29736. * <label for="mySelect">Make a choice:</label>
  29737. * <select name="mySelect" id="mySelect"
  29738. * ng-options="option.name for option in data.availableOptions track by option.id"
  29739. * ng-model="data.selectedOption"></select>
  29740. * </form>
  29741. * <hr>
  29742. * <tt>option = {{data.selectedOption}}</tt><br/>
  29743. * </div>
  29744. * </file>
  29745. * <file name="app.js">
  29746. * angular.module('defaultValueSelect', [])
  29747. * .controller('ExampleController', ['$scope', function($scope) {
  29748. * $scope.data = {
  29749. * availableOptions: [
  29750. * {id: '1', name: 'Option A'},
  29751. * {id: '2', name: 'Option B'},
  29752. * {id: '3', name: 'Option C'}
  29753. * ],
  29754. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  29755. * };
  29756. * }]);
  29757. * </file>
  29758. *</example>
  29759. *
  29760. *
  29761. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  29762. *
  29763. * <example name="select-with-non-string-options" module="nonStringSelect">
  29764. * <file name="index.html">
  29765. * <select ng-model="model.id" convert-to-number>
  29766. * <option value="0">Zero</option>
  29767. * <option value="1">One</option>
  29768. * <option value="2">Two</option>
  29769. * </select>
  29770. * {{ model }}
  29771. * </file>
  29772. * <file name="app.js">
  29773. * angular.module('nonStringSelect', [])
  29774. * .run(function($rootScope) {
  29775. * $rootScope.model = { id: 2 };
  29776. * })
  29777. * .directive('convertToNumber', function() {
  29778. * return {
  29779. * require: 'ngModel',
  29780. * link: function(scope, element, attrs, ngModel) {
  29781. * ngModel.$parsers.push(function(val) {
  29782. * return parseInt(val, 10);
  29783. * });
  29784. * ngModel.$formatters.push(function(val) {
  29785. * return '' + val;
  29786. * });
  29787. * }
  29788. * };
  29789. * });
  29790. * </file>
  29791. * <file name="protractor.js" type="protractor">
  29792. * it('should initialize to model', function() {
  29793. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  29794. * });
  29795. * </file>
  29796. * </example>
  29797. *
  29798. */
  29799. var selectDirective = function() {
  29800. return {
  29801. restrict: 'E',
  29802. require: ['select', '?ngModel'],
  29803. controller: SelectController,
  29804. priority: 1,
  29805. link: {
  29806. pre: selectPreLink,
  29807. post: selectPostLink
  29808. }
  29809. };
  29810. function selectPreLink(scope, element, attr, ctrls) {
  29811. var selectCtrl = ctrls[0];
  29812. var ngModelCtrl = ctrls[1];
  29813. // if ngModel is not defined, we don't need to do anything but set the registerOption
  29814. // function to noop, so options don't get added internally
  29815. if (!ngModelCtrl) {
  29816. selectCtrl.registerOption = noop;
  29817. return;
  29818. }
  29819. selectCtrl.ngModelCtrl = ngModelCtrl;
  29820. // When the selected item(s) changes we delegate getting the value of the select control
  29821. // to the `readValue` method, which can be changed if the select can have multiple
  29822. // selected values or if the options are being generated by `ngOptions`
  29823. element.on('change', function() {
  29824. selectCtrl.removeUnknownOption();
  29825. scope.$apply(function() {
  29826. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  29827. });
  29828. });
  29829. // If the select allows multiple values then we need to modify how we read and write
  29830. // values from and to the control; also what it means for the value to be empty and
  29831. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  29832. // doesn't trigger rendering if only an item in the array changes.
  29833. if (attr.multiple) {
  29834. selectCtrl.multiple = true;
  29835. // Read value now needs to check each option to see if it is selected
  29836. selectCtrl.readValue = function readMultipleValue() {
  29837. var array = [];
  29838. forEach(element.find('option'), function(option) {
  29839. if (option.selected && !option.disabled) {
  29840. var val = option.value;
  29841. array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
  29842. }
  29843. });
  29844. return array;
  29845. };
  29846. // Write value now needs to set the selected property of each matching option
  29847. selectCtrl.writeValue = function writeMultipleValue(value) {
  29848. forEach(element.find('option'), function(option) {
  29849. var shouldBeSelected = !!value && (includes(value, option.value) ||
  29850. includes(value, selectCtrl.selectValueMap[option.value]));
  29851. var currentlySelected = option.selected;
  29852. // IE and Edge, adding options to the selection via shift+click/UP/DOWN,
  29853. // will de-select already selected options if "selected" on those options was set
  29854. // more than once (i.e. when the options were already selected)
  29855. // So we only modify the selected property if neccessary.
  29856. // Note: this behavior cannot be replicated via unit tests because it only shows in the
  29857. // actual user interface.
  29858. if (shouldBeSelected !== currentlySelected) {
  29859. setOptionSelectedStatus(jqLite(option), shouldBeSelected);
  29860. }
  29861. });
  29862. };
  29863. // we have to do it on each watch since ngModel watches reference, but
  29864. // we need to work of an array, so we need to see if anything was inserted/removed
  29865. var lastView, lastViewRef = NaN;
  29866. scope.$watch(function selectMultipleWatch() {
  29867. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  29868. lastView = shallowCopy(ngModelCtrl.$viewValue);
  29869. ngModelCtrl.$render();
  29870. }
  29871. lastViewRef = ngModelCtrl.$viewValue;
  29872. });
  29873. // If we are a multiple select then value is now a collection
  29874. // so the meaning of $isEmpty changes
  29875. ngModelCtrl.$isEmpty = function(value) {
  29876. return !value || value.length === 0;
  29877. };
  29878. }
  29879. }
  29880. function selectPostLink(scope, element, attrs, ctrls) {
  29881. // if ngModel is not defined, we don't need to do anything
  29882. var ngModelCtrl = ctrls[1];
  29883. if (!ngModelCtrl) return;
  29884. var selectCtrl = ctrls[0];
  29885. // We delegate rendering to the `writeValue` method, which can be changed
  29886. // if the select can have multiple selected values or if the options are being
  29887. // generated by `ngOptions`.
  29888. // This must be done in the postLink fn to prevent $render to be called before
  29889. // all nodes have been linked correctly.
  29890. ngModelCtrl.$render = function() {
  29891. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  29892. };
  29893. }
  29894. };
  29895. // The option directive is purely designed to communicate the existence (or lack of)
  29896. // of dynamically created (and destroyed) option elements to their containing select
  29897. // directive via its controller.
  29898. var optionDirective = ['$interpolate', function($interpolate) {
  29899. return {
  29900. restrict: 'E',
  29901. priority: 100,
  29902. compile: function(element, attr) {
  29903. var interpolateValueFn, interpolateTextFn;
  29904. if (isDefined(attr.ngValue)) {
  29905. // Will be handled by registerOption
  29906. } else if (isDefined(attr.value)) {
  29907. // If the value attribute is defined, check if it contains an interpolation
  29908. interpolateValueFn = $interpolate(attr.value, true);
  29909. } else {
  29910. // If the value attribute is not defined then we fall back to the
  29911. // text content of the option element, which may be interpolated
  29912. interpolateTextFn = $interpolate(element.text(), true);
  29913. if (!interpolateTextFn) {
  29914. attr.$set('value', element.text());
  29915. }
  29916. }
  29917. return function(scope, element, attr) {
  29918. // This is an optimization over using ^^ since we don't want to have to search
  29919. // all the way to the root of the DOM for every single option element
  29920. var selectCtrlName = '$selectController',
  29921. parent = element.parent(),
  29922. selectCtrl = parent.data(selectCtrlName) ||
  29923. parent.parent().data(selectCtrlName); // in case we are in optgroup
  29924. if (selectCtrl) {
  29925. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  29926. }
  29927. };
  29928. }
  29929. };
  29930. }];
  29931. /**
  29932. * @ngdoc directive
  29933. * @name ngRequired
  29934. * @restrict A
  29935. *
  29936. * @description
  29937. *
  29938. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29939. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  29940. * applied to custom controls.
  29941. *
  29942. * The directive sets the `required` attribute on the element if the Angular expression inside
  29943. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  29944. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  29945. * for more info.
  29946. *
  29947. * The validator will set the `required` error key to true if the `required` attribute is set and
  29948. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  29949. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  29950. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  29951. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  29952. *
  29953. * @example
  29954. * <example name="ngRequiredDirective" module="ngRequiredExample">
  29955. * <file name="index.html">
  29956. * <script>
  29957. * angular.module('ngRequiredExample', [])
  29958. * .controller('ExampleController', ['$scope', function($scope) {
  29959. * $scope.required = true;
  29960. * }]);
  29961. * </script>
  29962. * <div ng-controller="ExampleController">
  29963. * <form name="form">
  29964. * <label for="required">Toggle required: </label>
  29965. * <input type="checkbox" ng-model="required" id="required" />
  29966. * <br>
  29967. * <label for="input">This input must be filled if `required` is true: </label>
  29968. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  29969. * <hr>
  29970. * required error set? = <code>{{form.input.$error.required}}</code><br>
  29971. * model = <code>{{model}}</code>
  29972. * </form>
  29973. * </div>
  29974. * </file>
  29975. * <file name="protractor.js" type="protractor">
  29976. var required = element(by.binding('form.input.$error.required'));
  29977. var model = element(by.binding('model'));
  29978. var input = element(by.id('input'));
  29979. it('should set the required error', function() {
  29980. expect(required.getText()).toContain('true');
  29981. input.sendKeys('123');
  29982. expect(required.getText()).not.toContain('true');
  29983. expect(model.getText()).toContain('123');
  29984. });
  29985. * </file>
  29986. * </example>
  29987. */
  29988. var requiredDirective = function() {
  29989. return {
  29990. restrict: 'A',
  29991. require: '?ngModel',
  29992. link: function(scope, elm, attr, ctrl) {
  29993. if (!ctrl) return;
  29994. attr.required = true; // force truthy in case we are on non input element
  29995. ctrl.$validators.required = function(modelValue, viewValue) {
  29996. return !attr.required || !ctrl.$isEmpty(viewValue);
  29997. };
  29998. attr.$observe('required', function() {
  29999. ctrl.$validate();
  30000. });
  30001. }
  30002. };
  30003. };
  30004. /**
  30005. * @ngdoc directive
  30006. * @name ngPattern
  30007. *
  30008. * @description
  30009. *
  30010. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30011. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30012. *
  30013. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30014. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  30015. * `ngPattern` attribute value:
  30016. * * If the expression evaluates to a RegExp object, then this is used directly.
  30017. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  30018. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  30019. *
  30020. * <div class="alert alert-info">
  30021. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  30022. * start at the index of the last search's match, thus not taking the whole input value into
  30023. * account.
  30024. * </div>
  30025. *
  30026. * <div class="alert alert-info">
  30027. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  30028. * differences:
  30029. * <ol>
  30030. * <li>
  30031. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  30032. * not available.
  30033. * </li>
  30034. * <li>
  30035. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  30036. * interpolated.
  30037. * </li>
  30038. * </ol>
  30039. * </div>
  30040. *
  30041. * @example
  30042. * <example name="ngPatternDirective" module="ngPatternExample">
  30043. * <file name="index.html">
  30044. * <script>
  30045. * angular.module('ngPatternExample', [])
  30046. * .controller('ExampleController', ['$scope', function($scope) {
  30047. * $scope.regex = '\\d+';
  30048. * }]);
  30049. * </script>
  30050. * <div ng-controller="ExampleController">
  30051. * <form name="form">
  30052. * <label for="regex">Set a pattern (regex string): </label>
  30053. * <input type="text" ng-model="regex" id="regex" />
  30054. * <br>
  30055. * <label for="input">This input is restricted by the current pattern: </label>
  30056. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  30057. * <hr>
  30058. * input valid? = <code>{{form.input.$valid}}</code><br>
  30059. * model = <code>{{model}}</code>
  30060. * </form>
  30061. * </div>
  30062. * </file>
  30063. * <file name="protractor.js" type="protractor">
  30064. var model = element(by.binding('model'));
  30065. var input = element(by.id('input'));
  30066. it('should validate the input with the default pattern', function() {
  30067. input.sendKeys('aaa');
  30068. expect(model.getText()).not.toContain('aaa');
  30069. input.clear().then(function() {
  30070. input.sendKeys('123');
  30071. expect(model.getText()).toContain('123');
  30072. });
  30073. });
  30074. * </file>
  30075. * </example>
  30076. */
  30077. var patternDirective = function() {
  30078. return {
  30079. restrict: 'A',
  30080. require: '?ngModel',
  30081. link: function(scope, elm, attr, ctrl) {
  30082. if (!ctrl) return;
  30083. var regexp, patternExp = attr.ngPattern || attr.pattern;
  30084. attr.$observe('pattern', function(regex) {
  30085. if (isString(regex) && regex.length > 0) {
  30086. regex = new RegExp('^' + regex + '$');
  30087. }
  30088. if (regex && !regex.test) {
  30089. throw minErr('ngPattern')('noregexp',
  30090. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  30091. regex, startingTag(elm));
  30092. }
  30093. regexp = regex || undefined;
  30094. ctrl.$validate();
  30095. });
  30096. ctrl.$validators.pattern = function(modelValue, viewValue) {
  30097. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  30098. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  30099. };
  30100. }
  30101. };
  30102. };
  30103. /**
  30104. * @ngdoc directive
  30105. * @name ngMaxlength
  30106. *
  30107. * @description
  30108. *
  30109. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30110. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30111. *
  30112. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30113. * is longer than the integer obtained by evaluating the Angular expression given in the
  30114. * `ngMaxlength` attribute value.
  30115. *
  30116. * <div class="alert alert-info">
  30117. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  30118. * differences:
  30119. * <ol>
  30120. * <li>
  30121. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  30122. * validation is not available.
  30123. * </li>
  30124. * <li>
  30125. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  30126. * interpolated.
  30127. * </li>
  30128. * </ol>
  30129. * </div>
  30130. *
  30131. * @example
  30132. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  30133. * <file name="index.html">
  30134. * <script>
  30135. * angular.module('ngMaxlengthExample', [])
  30136. * .controller('ExampleController', ['$scope', function($scope) {
  30137. * $scope.maxlength = 5;
  30138. * }]);
  30139. * </script>
  30140. * <div ng-controller="ExampleController">
  30141. * <form name="form">
  30142. * <label for="maxlength">Set a maxlength: </label>
  30143. * <input type="number" ng-model="maxlength" id="maxlength" />
  30144. * <br>
  30145. * <label for="input">This input is restricted by the current maxlength: </label>
  30146. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  30147. * <hr>
  30148. * input valid? = <code>{{form.input.$valid}}</code><br>
  30149. * model = <code>{{model}}</code>
  30150. * </form>
  30151. * </div>
  30152. * </file>
  30153. * <file name="protractor.js" type="protractor">
  30154. var model = element(by.binding('model'));
  30155. var input = element(by.id('input'));
  30156. it('should validate the input with the default maxlength', function() {
  30157. input.sendKeys('abcdef');
  30158. expect(model.getText()).not.toContain('abcdef');
  30159. input.clear().then(function() {
  30160. input.sendKeys('abcde');
  30161. expect(model.getText()).toContain('abcde');
  30162. });
  30163. });
  30164. * </file>
  30165. * </example>
  30166. */
  30167. var maxlengthDirective = function() {
  30168. return {
  30169. restrict: 'A',
  30170. require: '?ngModel',
  30171. link: function(scope, elm, attr, ctrl) {
  30172. if (!ctrl) return;
  30173. var maxlength = -1;
  30174. attr.$observe('maxlength', function(value) {
  30175. var intVal = toInt(value);
  30176. maxlength = isNumberNaN(intVal) ? -1 : intVal;
  30177. ctrl.$validate();
  30178. });
  30179. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  30180. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  30181. };
  30182. }
  30183. };
  30184. };
  30185. /**
  30186. * @ngdoc directive
  30187. * @name ngMinlength
  30188. *
  30189. * @description
  30190. *
  30191. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30192. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30193. *
  30194. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30195. * is shorter than the integer obtained by evaluating the Angular expression given in the
  30196. * `ngMinlength` attribute value.
  30197. *
  30198. * <div class="alert alert-info">
  30199. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  30200. * differences:
  30201. * <ol>
  30202. * <li>
  30203. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  30204. * validation is not available.
  30205. * </li>
  30206. * <li>
  30207. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  30208. * interpolated.
  30209. * </li>
  30210. * </ol>
  30211. * </div>
  30212. *
  30213. * @example
  30214. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  30215. * <file name="index.html">
  30216. * <script>
  30217. * angular.module('ngMinlengthExample', [])
  30218. * .controller('ExampleController', ['$scope', function($scope) {
  30219. * $scope.minlength = 3;
  30220. * }]);
  30221. * </script>
  30222. * <div ng-controller="ExampleController">
  30223. * <form name="form">
  30224. * <label for="minlength">Set a minlength: </label>
  30225. * <input type="number" ng-model="minlength" id="minlength" />
  30226. * <br>
  30227. * <label for="input">This input is restricted by the current minlength: </label>
  30228. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  30229. * <hr>
  30230. * input valid? = <code>{{form.input.$valid}}</code><br>
  30231. * model = <code>{{model}}</code>
  30232. * </form>
  30233. * </div>
  30234. * </file>
  30235. * <file name="protractor.js" type="protractor">
  30236. var model = element(by.binding('model'));
  30237. var input = element(by.id('input'));
  30238. it('should validate the input with the default minlength', function() {
  30239. input.sendKeys('ab');
  30240. expect(model.getText()).not.toContain('ab');
  30241. input.sendKeys('abc');
  30242. expect(model.getText()).toContain('abc');
  30243. });
  30244. * </file>
  30245. * </example>
  30246. */
  30247. var minlengthDirective = function() {
  30248. return {
  30249. restrict: 'A',
  30250. require: '?ngModel',
  30251. link: function(scope, elm, attr, ctrl) {
  30252. if (!ctrl) return;
  30253. var minlength = 0;
  30254. attr.$observe('minlength', function(value) {
  30255. minlength = toInt(value) || 0;
  30256. ctrl.$validate();
  30257. });
  30258. ctrl.$validators.minlength = function(modelValue, viewValue) {
  30259. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  30260. };
  30261. }
  30262. };
  30263. };
  30264. if (window.angular.bootstrap) {
  30265. // AngularJS is already loaded, so we can return here...
  30266. if (window.console) {
  30267. console.log('WARNING: Tried to load angular more than once.');
  30268. }
  30269. return;
  30270. }
  30271. // try to bind to jquery now so that one can write jqLite(fn)
  30272. // but we will rebind on bootstrap again.
  30273. bindJQuery();
  30274. publishExternalAPI(angular);
  30275. angular.module("ngLocale", [], ["$provide", function($provide) {
  30276. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  30277. function getDecimals(n) {
  30278. n = n + '';
  30279. var i = n.indexOf('.');
  30280. return (i == -1) ? 0 : n.length - i - 1;
  30281. }
  30282. function getVF(n, opt_precision) {
  30283. var v = opt_precision;
  30284. if (undefined === v) {
  30285. v = Math.min(getDecimals(n), 3);
  30286. }
  30287. var base = Math.pow(10, v);
  30288. var f = ((n * base) | 0) % base;
  30289. return {v: v, f: f};
  30290. }
  30291. $provide.value("$locale", {
  30292. "DATETIME_FORMATS": {
  30293. "AMPMS": [
  30294. "AM",
  30295. "PM"
  30296. ],
  30297. "DAY": [
  30298. "Sunday",
  30299. "Monday",
  30300. "Tuesday",
  30301. "Wednesday",
  30302. "Thursday",
  30303. "Friday",
  30304. "Saturday"
  30305. ],
  30306. "ERANAMES": [
  30307. "Before Christ",
  30308. "Anno Domini"
  30309. ],
  30310. "ERAS": [
  30311. "BC",
  30312. "AD"
  30313. ],
  30314. "FIRSTDAYOFWEEK": 6,
  30315. "MONTH": [
  30316. "January",
  30317. "February",
  30318. "March",
  30319. "April",
  30320. "May",
  30321. "June",
  30322. "July",
  30323. "August",
  30324. "September",
  30325. "October",
  30326. "November",
  30327. "December"
  30328. ],
  30329. "SHORTDAY": [
  30330. "Sun",
  30331. "Mon",
  30332. "Tue",
  30333. "Wed",
  30334. "Thu",
  30335. "Fri",
  30336. "Sat"
  30337. ],
  30338. "SHORTMONTH": [
  30339. "Jan",
  30340. "Feb",
  30341. "Mar",
  30342. "Apr",
  30343. "May",
  30344. "Jun",
  30345. "Jul",
  30346. "Aug",
  30347. "Sep",
  30348. "Oct",
  30349. "Nov",
  30350. "Dec"
  30351. ],
  30352. "STANDALONEMONTH": [
  30353. "January",
  30354. "February",
  30355. "March",
  30356. "April",
  30357. "May",
  30358. "June",
  30359. "July",
  30360. "August",
  30361. "September",
  30362. "October",
  30363. "November",
  30364. "December"
  30365. ],
  30366. "WEEKENDRANGE": [
  30367. 5,
  30368. 6
  30369. ],
  30370. "fullDate": "EEEE, MMMM d, y",
  30371. "longDate": "MMMM d, y",
  30372. "medium": "MMM d, y h:mm:ss a",
  30373. "mediumDate": "MMM d, y",
  30374. "mediumTime": "h:mm:ss a",
  30375. "short": "M/d/yy h:mm a",
  30376. "shortDate": "M/d/yy",
  30377. "shortTime": "h:mm a"
  30378. },
  30379. "NUMBER_FORMATS": {
  30380. "CURRENCY_SYM": "$",
  30381. "DECIMAL_SEP": ".",
  30382. "GROUP_SEP": ",",
  30383. "PATTERNS": [
  30384. {
  30385. "gSize": 3,
  30386. "lgSize": 3,
  30387. "maxFrac": 3,
  30388. "minFrac": 0,
  30389. "minInt": 1,
  30390. "negPre": "-",
  30391. "negSuf": "",
  30392. "posPre": "",
  30393. "posSuf": ""
  30394. },
  30395. {
  30396. "gSize": 3,
  30397. "lgSize": 3,
  30398. "maxFrac": 2,
  30399. "minFrac": 2,
  30400. "minInt": 1,
  30401. "negPre": "-\u00a4",
  30402. "negSuf": "",
  30403. "posPre": "\u00a4",
  30404. "posSuf": ""
  30405. }
  30406. ]
  30407. },
  30408. "id": "en-us",
  30409. "localeID": "en_US",
  30410. "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;}
  30411. });
  30412. }]);
  30413. jqLite(function() {
  30414. angularInit(window.document, bootstrap);
  30415. });
  30416. })(window);
  30417. !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>');