angular.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889
  1. /**
  2. * @license AngularJS v1.6.6
  3. * (c) 2010-2017 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window) {'use strict';
  7. /* exported
  8. minErrConfig,
  9. errorHandlingConfig,
  10. isValidObjectMaxDepth
  11. */
  12. var minErrConfig = {
  13. objectMaxDepth: 5
  14. };
  15. /**
  16. * @ngdoc function
  17. * @name angular.errorHandlingConfig
  18. * @module ng
  19. * @kind function
  20. *
  21. * @description
  22. * Configure several aspects of error handling in AngularJS if used as a setter or return the
  23. * current configuration if used as a getter. The following options are supported:
  24. *
  25. * - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages.
  26. *
  27. * Omitted or undefined options will leave the corresponding configuration values unchanged.
  28. *
  29. * @param {Object=} config - The configuration object. May only contain the options that need to be
  30. * updated. Supported keys:
  31. *
  32. * * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a
  33. * non-positive or non-numeric value, removes the max depth limit.
  34. * Default: 5
  35. */
  36. function errorHandlingConfig(config) {
  37. if (isObject(config)) {
  38. if (isDefined(config.objectMaxDepth)) {
  39. minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN;
  40. }
  41. } else {
  42. return minErrConfig;
  43. }
  44. }
  45. /**
  46. * @private
  47. * @param {Number} maxDepth
  48. * @return {boolean}
  49. */
  50. function isValidObjectMaxDepth(maxDepth) {
  51. return isNumber(maxDepth) && maxDepth > 0;
  52. }
  53. /**
  54. * @description
  55. *
  56. * This object provides a utility for producing rich Error messages within
  57. * Angular. It can be called as follows:
  58. *
  59. * var exampleMinErr = minErr('example');
  60. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  61. *
  62. * The above creates an instance of minErr in the example namespace. The
  63. * resulting error will have a namespaced error code of example.one. The
  64. * resulting error will replace {0} with the value of foo, and {1} with the
  65. * value of bar. The object is not restricted in the number of arguments it can
  66. * take.
  67. *
  68. * If fewer arguments are specified than necessary for interpolation, the extra
  69. * interpolation markers will be preserved in the final string.
  70. *
  71. * Since data will be parsed statically during a build step, some restrictions
  72. * are applied with respect to how minErr instances are created and called.
  73. * Instances should have names of the form namespaceMinErr for a minErr created
  74. * using minErr('namespace') . Error codes, namespaces and template strings
  75. * should all be static strings, not variables or general expressions.
  76. *
  77. * @param {string} module The namespace to use for the new minErr instance.
  78. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  79. * error from returned function, for cases when a particular type of error is useful.
  80. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  81. */
  82. function minErr(module, ErrorConstructor) {
  83. ErrorConstructor = ErrorConstructor || Error;
  84. return function() {
  85. var code = arguments[0],
  86. template = arguments[1],
  87. message = '[' + (module ? module + ':' : '') + code + '] ',
  88. templateArgs = sliceArgs(arguments, 2).map(function(arg) {
  89. return toDebugString(arg, minErrConfig.objectMaxDepth);
  90. }),
  91. paramPrefix, i;
  92. message += template.replace(/\{\d+\}/g, function(match) {
  93. var index = +match.slice(1, -1);
  94. if (index < templateArgs.length) {
  95. return templateArgs[index];
  96. }
  97. return match;
  98. });
  99. message += '\nhttp://errors.angularjs.org/1.6.6/' +
  100. (module ? module + '/' : '') + code;
  101. for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  102. message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]);
  103. }
  104. return new ErrorConstructor(message);
  105. };
  106. }
  107. /* We need to tell ESLint what variables are being exported */
  108. /* exported
  109. angular,
  110. msie,
  111. jqLite,
  112. jQuery,
  113. slice,
  114. splice,
  115. push,
  116. toString,
  117. minErrConfig,
  118. errorHandlingConfig,
  119. isValidObjectMaxDepth,
  120. ngMinErr,
  121. angularModule,
  122. uid,
  123. REGEX_STRING_REGEXP,
  124. VALIDITY_STATE_PROPERTY,
  125. lowercase,
  126. uppercase,
  127. manualLowercase,
  128. manualUppercase,
  129. nodeName_,
  130. isArrayLike,
  131. forEach,
  132. forEachSorted,
  133. reverseParams,
  134. nextUid,
  135. setHashKey,
  136. extend,
  137. toInt,
  138. inherit,
  139. merge,
  140. noop,
  141. identity,
  142. valueFn,
  143. isUndefined,
  144. isDefined,
  145. isObject,
  146. isBlankObject,
  147. isString,
  148. isNumber,
  149. isNumberNaN,
  150. isDate,
  151. isError,
  152. isArray,
  153. isFunction,
  154. isRegExp,
  155. isWindow,
  156. isScope,
  157. isFile,
  158. isFormData,
  159. isBlob,
  160. isBoolean,
  161. isPromiseLike,
  162. trim,
  163. escapeForRegexp,
  164. isElement,
  165. makeMap,
  166. includes,
  167. arrayRemove,
  168. copy,
  169. simpleCompare,
  170. equals,
  171. csp,
  172. jq,
  173. concat,
  174. sliceArgs,
  175. bind,
  176. toJsonReplacer,
  177. toJson,
  178. fromJson,
  179. convertTimezoneToLocal,
  180. timezoneToOffset,
  181. startingTag,
  182. tryDecodeURIComponent,
  183. parseKeyValue,
  184. toKeyValue,
  185. encodeUriSegment,
  186. encodeUriQuery,
  187. angularInit,
  188. bootstrap,
  189. getTestability,
  190. snake_case,
  191. bindJQuery,
  192. assertArg,
  193. assertArgFn,
  194. assertNotHasOwnProperty,
  195. getter,
  196. getBlockNodes,
  197. hasOwnProperty,
  198. createMap,
  199. stringify,
  200. NODE_TYPE_ELEMENT,
  201. NODE_TYPE_ATTRIBUTE,
  202. NODE_TYPE_TEXT,
  203. NODE_TYPE_COMMENT,
  204. NODE_TYPE_DOCUMENT,
  205. NODE_TYPE_DOCUMENT_FRAGMENT
  206. */
  207. ////////////////////////////////////
  208. /**
  209. * @ngdoc module
  210. * @name ng
  211. * @module ng
  212. * @installation
  213. * @description
  214. *
  215. * # ng (core module)
  216. * The ng module is loaded by default when an AngularJS application is started. The module itself
  217. * contains the essential components for an AngularJS application to function. The table below
  218. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  219. * components available within this core module.
  220. *
  221. * <div doc-module-components="ng"></div>
  222. */
  223. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  224. // The name of a form control's ValidityState property.
  225. // This is used so that it's possible for internal tests to create mock ValidityStates.
  226. var VALIDITY_STATE_PROPERTY = 'validity';
  227. var hasOwnProperty = Object.prototype.hasOwnProperty;
  228. /**
  229. * @ngdoc function
  230. * @name angular.lowercase
  231. * @module ng
  232. * @kind function
  233. *
  234. * @deprecated
  235. * sinceVersion="1.5.0"
  236. * removeVersion="1.7.0"
  237. * Use [String.prototype.toLowerCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) instead.
  238. *
  239. * @description Converts the specified string to lowercase.
  240. * @param {string} string String to be converted to lowercase.
  241. * @returns {string} Lowercased string.
  242. */
  243. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  244. /**
  245. * @ngdoc function
  246. * @name angular.uppercase
  247. * @module ng
  248. * @kind function
  249. *
  250. * @deprecated
  251. * sinceVersion="1.5.0"
  252. * removeVersion="1.7.0"
  253. * Use [String.prototype.toUpperCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) instead.
  254. *
  255. * @description Converts the specified string to uppercase.
  256. * @param {string} string String to be converted to uppercase.
  257. * @returns {string} Uppercased string.
  258. */
  259. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  260. var manualLowercase = 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. var manualUppercase = function(s) {
  268. /* eslint-disable no-bitwise */
  269. return isString(s)
  270. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  271. : s;
  272. /* eslint-enable */
  273. };
  274. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  275. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  276. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  277. if ('i' !== 'I'.toLowerCase()) {
  278. lowercase = manualLowercase;
  279. uppercase = manualUppercase;
  280. }
  281. var
  282. msie, // holds major version number for IE, or NaN if UA is not IE.
  283. jqLite, // delay binding since jQuery could be loaded after us.
  284. jQuery, // delay binding
  285. slice = [].slice,
  286. splice = [].splice,
  287. push = [].push,
  288. toString = Object.prototype.toString,
  289. getPrototypeOf = Object.getPrototypeOf,
  290. ngMinErr = minErr('ng'),
  291. /** @name angular */
  292. angular = window.angular || (window.angular = {}),
  293. angularModule,
  294. uid = 0;
  295. // Support: IE 9-11 only
  296. /**
  297. * documentMode is an IE-only property
  298. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  299. */
  300. msie = window.document.documentMode;
  301. /**
  302. * @private
  303. * @param {*} obj
  304. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  305. * String ...)
  306. */
  307. function isArrayLike(obj) {
  308. // `null`, `undefined` and `window` are not array-like
  309. if (obj == null || isWindow(obj)) return false;
  310. // arrays, strings and jQuery/jqLite objects are array like
  311. // * jqLite is either the jQuery or jqLite constructor function
  312. // * we have to check the existence of jqLite first as this method is called
  313. // via the forEach method when constructing the jqLite object in the first place
  314. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  315. // Support: iOS 8.2 (not reproducible in simulator)
  316. // "length" in obj used to prevent JIT error (gh-11508)
  317. var length = 'length' in Object(obj) && obj.length;
  318. // NodeList objects (with `item` method) and
  319. // other objects with suitable length characteristics are array-like
  320. return isNumber(length) &&
  321. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');
  322. }
  323. /**
  324. * @ngdoc function
  325. * @name angular.forEach
  326. * @module ng
  327. * @kind function
  328. *
  329. * @description
  330. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  331. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  332. * is the value of an object property or an array element, `key` is the object property key or
  333. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  334. *
  335. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  336. * using the `hasOwnProperty` method.
  337. *
  338. * Unlike ES262's
  339. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  340. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  341. * return the value provided.
  342. *
  343. ```js
  344. var values = {name: 'misko', gender: 'male'};
  345. var log = [];
  346. angular.forEach(values, function(value, key) {
  347. this.push(key + ': ' + value);
  348. }, log);
  349. expect(log).toEqual(['name: misko', 'gender: male']);
  350. ```
  351. *
  352. * @param {Object|Array} obj Object to iterate over.
  353. * @param {Function} iterator Iterator function.
  354. * @param {Object=} context Object to become context (`this`) for the iterator function.
  355. * @returns {Object|Array} Reference to `obj`.
  356. */
  357. function forEach(obj, iterator, context) {
  358. var key, length;
  359. if (obj) {
  360. if (isFunction(obj)) {
  361. for (key in obj) {
  362. if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
  363. iterator.call(context, obj[key], key, obj);
  364. }
  365. }
  366. } else if (isArray(obj) || isArrayLike(obj)) {
  367. var isPrimitive = typeof obj !== 'object';
  368. for (key = 0, length = obj.length; key < length; key++) {
  369. if (isPrimitive || key in obj) {
  370. iterator.call(context, obj[key], key, obj);
  371. }
  372. }
  373. } else if (obj.forEach && obj.forEach !== forEach) {
  374. obj.forEach(iterator, context, obj);
  375. } else if (isBlankObject(obj)) {
  376. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  377. for (key in obj) {
  378. iterator.call(context, obj[key], key, obj);
  379. }
  380. } else if (typeof obj.hasOwnProperty === 'function') {
  381. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  382. for (key in obj) {
  383. if (obj.hasOwnProperty(key)) {
  384. iterator.call(context, obj[key], key, obj);
  385. }
  386. }
  387. } else {
  388. // Slow path for objects which do not have a method `hasOwnProperty`
  389. for (key in obj) {
  390. if (hasOwnProperty.call(obj, key)) {
  391. iterator.call(context, obj[key], key, obj);
  392. }
  393. }
  394. }
  395. }
  396. return obj;
  397. }
  398. function forEachSorted(obj, iterator, context) {
  399. var keys = Object.keys(obj).sort();
  400. for (var i = 0; i < keys.length; i++) {
  401. iterator.call(context, obj[keys[i]], keys[i]);
  402. }
  403. return keys;
  404. }
  405. /**
  406. * when using forEach the params are value, key, but it is often useful to have key, value.
  407. * @param {function(string, *)} iteratorFn
  408. * @returns {function(*, string)}
  409. */
  410. function reverseParams(iteratorFn) {
  411. return function(value, key) {iteratorFn(key, value);};
  412. }
  413. /**
  414. * A consistent way of creating unique IDs in angular.
  415. *
  416. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  417. * we hit number precision issues in JavaScript.
  418. *
  419. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  420. *
  421. * @returns {number} an unique alpha-numeric string
  422. */
  423. function nextUid() {
  424. return ++uid;
  425. }
  426. /**
  427. * Set or clear the hashkey for an object.
  428. * @param obj object
  429. * @param h the hashkey (!truthy to delete the hashkey)
  430. */
  431. function setHashKey(obj, h) {
  432. if (h) {
  433. obj.$$hashKey = h;
  434. } else {
  435. delete obj.$$hashKey;
  436. }
  437. }
  438. function baseExtend(dst, objs, deep) {
  439. var h = dst.$$hashKey;
  440. for (var i = 0, ii = objs.length; i < ii; ++i) {
  441. var obj = objs[i];
  442. if (!isObject(obj) && !isFunction(obj)) continue;
  443. var keys = Object.keys(obj);
  444. for (var j = 0, jj = keys.length; j < jj; j++) {
  445. var key = keys[j];
  446. var src = obj[key];
  447. if (deep && isObject(src)) {
  448. if (isDate(src)) {
  449. dst[key] = new Date(src.valueOf());
  450. } else if (isRegExp(src)) {
  451. dst[key] = new RegExp(src);
  452. } else if (src.nodeName) {
  453. dst[key] = src.cloneNode(true);
  454. } else if (isElement(src)) {
  455. dst[key] = src.clone();
  456. } else {
  457. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  458. baseExtend(dst[key], [src], true);
  459. }
  460. } else {
  461. dst[key] = src;
  462. }
  463. }
  464. }
  465. setHashKey(dst, h);
  466. return dst;
  467. }
  468. /**
  469. * @ngdoc function
  470. * @name angular.extend
  471. * @module ng
  472. * @kind function
  473. *
  474. * @description
  475. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  476. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  477. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  478. *
  479. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  480. * {@link angular.merge} for this.
  481. *
  482. * @param {Object} dst Destination object.
  483. * @param {...Object} src Source object(s).
  484. * @returns {Object} Reference to `dst`.
  485. */
  486. function extend(dst) {
  487. return baseExtend(dst, slice.call(arguments, 1), false);
  488. }
  489. /**
  490. * @ngdoc function
  491. * @name angular.merge
  492. * @module ng
  493. * @kind function
  494. *
  495. * @description
  496. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  497. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  498. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  499. *
  500. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  501. * objects, performing a deep copy.
  502. *
  503. * @deprecated
  504. * sinceVersion="1.6.5"
  505. * This function is deprecated, but will not be removed in the 1.x lifecycle.
  506. * There are edge cases (see {@link angular.merge#known-issues known issues}) that are not
  507. * supported by this function. We suggest
  508. * using [lodash's merge()](https://lodash.com/docs/4.17.4#merge) instead.
  509. *
  510. * @knownIssue
  511. * This is a list of (known) object types that are not handled correctly by this function:
  512. * - [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob)
  513. * - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream)
  514. * - [`CanvasGradient`](https://developer.mozilla.org/docs/Web/API/CanvasGradient)
  515. * - AngularJS {@link $rootScope.Scope scopes};
  516. *
  517. * @param {Object} dst Destination object.
  518. * @param {...Object} src Source object(s).
  519. * @returns {Object} Reference to `dst`.
  520. */
  521. function merge(dst) {
  522. return baseExtend(dst, slice.call(arguments, 1), true);
  523. }
  524. function toInt(str) {
  525. return parseInt(str, 10);
  526. }
  527. var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
  528. // eslint-disable-next-line no-self-compare
  529. return num !== num;
  530. };
  531. function inherit(parent, extra) {
  532. return extend(Object.create(parent), extra);
  533. }
  534. /**
  535. * @ngdoc function
  536. * @name angular.noop
  537. * @module ng
  538. * @kind function
  539. *
  540. * @description
  541. * A function that performs no operations. This function can be useful when writing code in the
  542. * functional style.
  543. ```js
  544. function foo(callback) {
  545. var result = calculateResult();
  546. (callback || angular.noop)(result);
  547. }
  548. ```
  549. */
  550. function noop() {}
  551. noop.$inject = [];
  552. /**
  553. * @ngdoc function
  554. * @name angular.identity
  555. * @module ng
  556. * @kind function
  557. *
  558. * @description
  559. * A function that returns its first argument. This function is useful when writing code in the
  560. * functional style.
  561. *
  562. ```js
  563. function transformer(transformationFn, value) {
  564. return (transformationFn || angular.identity)(value);
  565. };
  566. // E.g.
  567. function getResult(fn, input) {
  568. return (fn || angular.identity)(input);
  569. };
  570. getResult(function(n) { return n * 2; }, 21); // returns 42
  571. getResult(null, 21); // returns 21
  572. getResult(undefined, 21); // returns 21
  573. ```
  574. *
  575. * @param {*} value to be returned.
  576. * @returns {*} the value passed in.
  577. */
  578. function identity($) {return $;}
  579. identity.$inject = [];
  580. function valueFn(value) {return function valueRef() {return value;};}
  581. function hasCustomToString(obj) {
  582. return isFunction(obj.toString) && obj.toString !== toString;
  583. }
  584. /**
  585. * @ngdoc function
  586. * @name angular.isUndefined
  587. * @module ng
  588. * @kind function
  589. *
  590. * @description
  591. * Determines if a reference is undefined.
  592. *
  593. * @param {*} value Reference to check.
  594. * @returns {boolean} True if `value` is undefined.
  595. */
  596. function isUndefined(value) {return typeof value === 'undefined';}
  597. /**
  598. * @ngdoc function
  599. * @name angular.isDefined
  600. * @module ng
  601. * @kind function
  602. *
  603. * @description
  604. * Determines if a reference is defined.
  605. *
  606. * @param {*} value Reference to check.
  607. * @returns {boolean} True if `value` is defined.
  608. */
  609. function isDefined(value) {return typeof value !== 'undefined';}
  610. /**
  611. * @ngdoc function
  612. * @name angular.isObject
  613. * @module ng
  614. * @kind function
  615. *
  616. * @description
  617. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  618. * considered to be objects. Note that JavaScript arrays are objects.
  619. *
  620. * @param {*} value Reference to check.
  621. * @returns {boolean} True if `value` is an `Object` but not `null`.
  622. */
  623. function isObject(value) {
  624. // http://jsperf.com/isobject4
  625. return value !== null && typeof value === 'object';
  626. }
  627. /**
  628. * Determine if a value is an object with a null prototype
  629. *
  630. * @returns {boolean} True if `value` is an `Object` with a null prototype
  631. */
  632. function isBlankObject(value) {
  633. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  634. }
  635. /**
  636. * @ngdoc function
  637. * @name angular.isString
  638. * @module ng
  639. * @kind function
  640. *
  641. * @description
  642. * Determines if a reference is a `String`.
  643. *
  644. * @param {*} value Reference to check.
  645. * @returns {boolean} True if `value` is a `String`.
  646. */
  647. function isString(value) {return typeof value === 'string';}
  648. /**
  649. * @ngdoc function
  650. * @name angular.isNumber
  651. * @module ng
  652. * @kind function
  653. *
  654. * @description
  655. * Determines if a reference is a `Number`.
  656. *
  657. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  658. *
  659. * If you wish to exclude these then you can use the native
  660. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  661. * method.
  662. *
  663. * @param {*} value Reference to check.
  664. * @returns {boolean} True if `value` is a `Number`.
  665. */
  666. function isNumber(value) {return typeof value === 'number';}
  667. /**
  668. * @ngdoc function
  669. * @name angular.isDate
  670. * @module ng
  671. * @kind function
  672. *
  673. * @description
  674. * Determines if a value is a date.
  675. *
  676. * @param {*} value Reference to check.
  677. * @returns {boolean} True if `value` is a `Date`.
  678. */
  679. function isDate(value) {
  680. return toString.call(value) === '[object Date]';
  681. }
  682. /**
  683. * @ngdoc function
  684. * @name angular.isArray
  685. * @module ng
  686. * @kind function
  687. *
  688. * @description
  689. * Determines if a reference is an `Array`. Alias of Array.isArray.
  690. *
  691. * @param {*} value Reference to check.
  692. * @returns {boolean} True if `value` is an `Array`.
  693. */
  694. var isArray = Array.isArray;
  695. /**
  696. * @description
  697. * Determines if a reference is an `Error`.
  698. * Loosely based on https://www.npmjs.com/package/iserror
  699. *
  700. * @param {*} value Reference to check.
  701. * @returns {boolean} True if `value` is an `Error`.
  702. */
  703. function isError(value) {
  704. var tag = toString.call(value);
  705. switch (tag) {
  706. case '[object Error]': return true;
  707. case '[object Exception]': return true;
  708. case '[object DOMException]': return true;
  709. default: return value instanceof Error;
  710. }
  711. }
  712. /**
  713. * @ngdoc function
  714. * @name angular.isFunction
  715. * @module ng
  716. * @kind function
  717. *
  718. * @description
  719. * Determines if a reference is a `Function`.
  720. *
  721. * @param {*} value Reference to check.
  722. * @returns {boolean} True if `value` is a `Function`.
  723. */
  724. function isFunction(value) {return typeof value === 'function';}
  725. /**
  726. * Determines if a value is a regular expression object.
  727. *
  728. * @private
  729. * @param {*} value Reference to check.
  730. * @returns {boolean} True if `value` is a `RegExp`.
  731. */
  732. function isRegExp(value) {
  733. return toString.call(value) === '[object RegExp]';
  734. }
  735. /**
  736. * Checks if `obj` is a window object.
  737. *
  738. * @private
  739. * @param {*} obj Object to check
  740. * @returns {boolean} True if `obj` is a window obj.
  741. */
  742. function isWindow(obj) {
  743. return obj && obj.window === obj;
  744. }
  745. function isScope(obj) {
  746. return obj && obj.$evalAsync && obj.$watch;
  747. }
  748. function isFile(obj) {
  749. return toString.call(obj) === '[object File]';
  750. }
  751. function isFormData(obj) {
  752. return toString.call(obj) === '[object FormData]';
  753. }
  754. function isBlob(obj) {
  755. return toString.call(obj) === '[object Blob]';
  756. }
  757. function isBoolean(value) {
  758. return typeof value === 'boolean';
  759. }
  760. function isPromiseLike(obj) {
  761. return obj && isFunction(obj.then);
  762. }
  763. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
  764. function isTypedArray(value) {
  765. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  766. }
  767. function isArrayBuffer(obj) {
  768. return toString.call(obj) === '[object ArrayBuffer]';
  769. }
  770. var trim = function(value) {
  771. return isString(value) ? value.trim() : value;
  772. };
  773. // Copied from:
  774. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  775. // Prereq: s is a string.
  776. var escapeForRegexp = function(s) {
  777. return s
  778. .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
  779. // eslint-disable-next-line no-control-regex
  780. .replace(/\x08/g, '\\x08');
  781. };
  782. /**
  783. * @ngdoc function
  784. * @name angular.isElement
  785. * @module ng
  786. * @kind function
  787. *
  788. * @description
  789. * Determines if a reference is a DOM element (or wrapped jQuery element).
  790. *
  791. * @param {*} value Reference to check.
  792. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  793. */
  794. function isElement(node) {
  795. return !!(node &&
  796. (node.nodeName // We are a direct element.
  797. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  798. }
  799. /**
  800. * @param str 'key1,key2,...'
  801. * @returns {object} in the form of {key1:true, key2:true, ...}
  802. */
  803. function makeMap(str) {
  804. var obj = {}, items = str.split(','), i;
  805. for (i = 0; i < items.length; i++) {
  806. obj[items[i]] = true;
  807. }
  808. return obj;
  809. }
  810. function nodeName_(element) {
  811. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  812. }
  813. function includes(array, obj) {
  814. return Array.prototype.indexOf.call(array, obj) !== -1;
  815. }
  816. function arrayRemove(array, value) {
  817. var index = array.indexOf(value);
  818. if (index >= 0) {
  819. array.splice(index, 1);
  820. }
  821. return index;
  822. }
  823. /**
  824. * @ngdoc function
  825. * @name angular.copy
  826. * @module ng
  827. * @kind function
  828. *
  829. * @description
  830. * Creates a deep copy of `source`, which should be an object or an array.
  831. *
  832. * * If no destination is supplied, a copy of the object or array is created.
  833. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  834. * are deleted and then all elements/properties from the source are copied to it.
  835. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  836. * * If `source` is identical to `destination` an exception will be thrown.
  837. *
  838. * <br />
  839. * <div class="alert alert-warning">
  840. * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
  841. * and on `destination`) will be ignored.
  842. * </div>
  843. *
  844. * @param {*} source The source that will be used to make a copy.
  845. * Can be any type, including primitives, `null`, and `undefined`.
  846. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  847. * provided, must be of the same type as `source`.
  848. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  849. *
  850. * @example
  851. <example module="copyExample" name="angular-copy">
  852. <file name="index.html">
  853. <div ng-controller="ExampleController">
  854. <form novalidate class="simple-form">
  855. <label>Name: <input type="text" ng-model="user.name" /></label><br />
  856. <label>Age: <input type="number" ng-model="user.age" /></label><br />
  857. Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
  858. <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
  859. <button ng-click="reset()">RESET</button>
  860. <button ng-click="update(user)">SAVE</button>
  861. </form>
  862. <pre>form = {{user | json}}</pre>
  863. <pre>master = {{master | json}}</pre>
  864. </div>
  865. </file>
  866. <file name="script.js">
  867. // Module: copyExample
  868. angular.
  869. module('copyExample', []).
  870. controller('ExampleController', ['$scope', function($scope) {
  871. $scope.master = {};
  872. $scope.reset = function() {
  873. // Example with 1 argument
  874. $scope.user = angular.copy($scope.master);
  875. };
  876. $scope.update = function(user) {
  877. // Example with 2 arguments
  878. angular.copy(user, $scope.master);
  879. };
  880. $scope.reset();
  881. }]);
  882. </file>
  883. </example>
  884. */
  885. function copy(source, destination, maxDepth) {
  886. var stackSource = [];
  887. var stackDest = [];
  888. maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN;
  889. if (destination) {
  890. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  891. throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
  892. }
  893. if (source === destination) {
  894. throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
  895. }
  896. // Empty the destination object
  897. if (isArray(destination)) {
  898. destination.length = 0;
  899. } else {
  900. forEach(destination, function(value, key) {
  901. if (key !== '$$hashKey') {
  902. delete destination[key];
  903. }
  904. });
  905. }
  906. stackSource.push(source);
  907. stackDest.push(destination);
  908. return copyRecurse(source, destination, maxDepth);
  909. }
  910. return copyElement(source, maxDepth);
  911. function copyRecurse(source, destination, maxDepth) {
  912. maxDepth--;
  913. if (maxDepth < 0) {
  914. return '...';
  915. }
  916. var h = destination.$$hashKey;
  917. var key;
  918. if (isArray(source)) {
  919. for (var i = 0, ii = source.length; i < ii; i++) {
  920. destination.push(copyElement(source[i], maxDepth));
  921. }
  922. } else if (isBlankObject(source)) {
  923. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  924. for (key in source) {
  925. destination[key] = copyElement(source[key], maxDepth);
  926. }
  927. } else if (source && typeof source.hasOwnProperty === 'function') {
  928. // Slow path, which must rely on hasOwnProperty
  929. for (key in source) {
  930. if (source.hasOwnProperty(key)) {
  931. destination[key] = copyElement(source[key], maxDepth);
  932. }
  933. }
  934. } else {
  935. // Slowest path --- hasOwnProperty can't be called as a method
  936. for (key in source) {
  937. if (hasOwnProperty.call(source, key)) {
  938. destination[key] = copyElement(source[key], maxDepth);
  939. }
  940. }
  941. }
  942. setHashKey(destination, h);
  943. return destination;
  944. }
  945. function copyElement(source, maxDepth) {
  946. // Simple values
  947. if (!isObject(source)) {
  948. return source;
  949. }
  950. // Already copied values
  951. var index = stackSource.indexOf(source);
  952. if (index !== -1) {
  953. return stackDest[index];
  954. }
  955. if (isWindow(source) || isScope(source)) {
  956. throw ngMinErr('cpws',
  957. 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
  958. }
  959. var needsRecurse = false;
  960. var destination = copyType(source);
  961. if (destination === undefined) {
  962. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  963. needsRecurse = true;
  964. }
  965. stackSource.push(source);
  966. stackDest.push(destination);
  967. return needsRecurse
  968. ? copyRecurse(source, destination, maxDepth)
  969. : destination;
  970. }
  971. function copyType(source) {
  972. switch (toString.call(source)) {
  973. case '[object Int8Array]':
  974. case '[object Int16Array]':
  975. case '[object Int32Array]':
  976. case '[object Float32Array]':
  977. case '[object Float64Array]':
  978. case '[object Uint8Array]':
  979. case '[object Uint8ClampedArray]':
  980. case '[object Uint16Array]':
  981. case '[object Uint32Array]':
  982. return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
  983. case '[object ArrayBuffer]':
  984. // Support: IE10
  985. if (!source.slice) {
  986. // If we're in this case we know the environment supports ArrayBuffer
  987. /* eslint-disable no-undef */
  988. var copied = new ArrayBuffer(source.byteLength);
  989. new Uint8Array(copied).set(new Uint8Array(source));
  990. /* eslint-enable */
  991. return copied;
  992. }
  993. return source.slice(0);
  994. case '[object Boolean]':
  995. case '[object Number]':
  996. case '[object String]':
  997. case '[object Date]':
  998. return new source.constructor(source.valueOf());
  999. case '[object RegExp]':
  1000. var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
  1001. re.lastIndex = source.lastIndex;
  1002. return re;
  1003. case '[object Blob]':
  1004. return new source.constructor([source], {type: source.type});
  1005. }
  1006. if (isFunction(source.cloneNode)) {
  1007. return source.cloneNode(true);
  1008. }
  1009. }
  1010. }
  1011. // eslint-disable-next-line no-self-compare
  1012. function simpleCompare(a, b) { return a === b || (a !== a && b !== b); }
  1013. /**
  1014. * @ngdoc function
  1015. * @name angular.equals
  1016. * @module ng
  1017. * @kind function
  1018. *
  1019. * @description
  1020. * Determines if two objects or two values are equivalent. Supports value types, regular
  1021. * expressions, arrays and objects.
  1022. *
  1023. * Two objects or values are considered equivalent if at least one of the following is true:
  1024. *
  1025. * * Both objects or values pass `===` comparison.
  1026. * * Both objects or values are of the same type and all of their properties are equal by
  1027. * comparing them with `angular.equals`.
  1028. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  1029. * * Both values represent the same regular expression (In JavaScript,
  1030. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  1031. * representation matches).
  1032. *
  1033. * During a property comparison, properties of `function` type and properties with names
  1034. * that begin with `$` are ignored.
  1035. *
  1036. * Scope and DOMWindow objects are being compared only by identify (`===`).
  1037. *
  1038. * @param {*} o1 Object or value to compare.
  1039. * @param {*} o2 Object or value to compare.
  1040. * @returns {boolean} True if arguments are equal.
  1041. *
  1042. * @example
  1043. <example module="equalsExample" name="equalsExample">
  1044. <file name="index.html">
  1045. <div ng-controller="ExampleController">
  1046. <form novalidate>
  1047. <h3>User 1</h3>
  1048. Name: <input type="text" ng-model="user1.name">
  1049. Age: <input type="number" ng-model="user1.age">
  1050. <h3>User 2</h3>
  1051. Name: <input type="text" ng-model="user2.name">
  1052. Age: <input type="number" ng-model="user2.age">
  1053. <div>
  1054. <br/>
  1055. <input type="button" value="Compare" ng-click="compare()">
  1056. </div>
  1057. User 1: <pre>{{user1 | json}}</pre>
  1058. User 2: <pre>{{user2 | json}}</pre>
  1059. Equal: <pre>{{result}}</pre>
  1060. </form>
  1061. </div>
  1062. </file>
  1063. <file name="script.js">
  1064. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  1065. $scope.user1 = {};
  1066. $scope.user2 = {};
  1067. $scope.compare = function() {
  1068. $scope.result = angular.equals($scope.user1, $scope.user2);
  1069. };
  1070. }]);
  1071. </file>
  1072. </example>
  1073. */
  1074. function equals(o1, o2) {
  1075. if (o1 === o2) return true;
  1076. if (o1 === null || o2 === null) return false;
  1077. // eslint-disable-next-line no-self-compare
  1078. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  1079. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  1080. if (t1 === t2 && t1 === 'object') {
  1081. if (isArray(o1)) {
  1082. if (!isArray(o2)) return false;
  1083. if ((length = o1.length) === o2.length) {
  1084. for (key = 0; key < length; key++) {
  1085. if (!equals(o1[key], o2[key])) return false;
  1086. }
  1087. return true;
  1088. }
  1089. } else if (isDate(o1)) {
  1090. if (!isDate(o2)) return false;
  1091. return simpleCompare(o1.getTime(), o2.getTime());
  1092. } else if (isRegExp(o1)) {
  1093. if (!isRegExp(o2)) return false;
  1094. return o1.toString() === o2.toString();
  1095. } else {
  1096. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  1097. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  1098. keySet = createMap();
  1099. for (key in o1) {
  1100. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  1101. if (!equals(o1[key], o2[key])) return false;
  1102. keySet[key] = true;
  1103. }
  1104. for (key in o2) {
  1105. if (!(key in keySet) &&
  1106. key.charAt(0) !== '$' &&
  1107. isDefined(o2[key]) &&
  1108. !isFunction(o2[key])) return false;
  1109. }
  1110. return true;
  1111. }
  1112. }
  1113. return false;
  1114. }
  1115. var csp = function() {
  1116. if (!isDefined(csp.rules)) {
  1117. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  1118. window.document.querySelector('[data-ng-csp]'));
  1119. if (ngCspElement) {
  1120. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  1121. ngCspElement.getAttribute('data-ng-csp');
  1122. csp.rules = {
  1123. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  1124. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  1125. };
  1126. } else {
  1127. csp.rules = {
  1128. noUnsafeEval: noUnsafeEval(),
  1129. noInlineStyle: false
  1130. };
  1131. }
  1132. }
  1133. return csp.rules;
  1134. function noUnsafeEval() {
  1135. try {
  1136. // eslint-disable-next-line no-new, no-new-func
  1137. new Function('');
  1138. return false;
  1139. } catch (e) {
  1140. return true;
  1141. }
  1142. }
  1143. };
  1144. /**
  1145. * @ngdoc directive
  1146. * @module ng
  1147. * @name ngJq
  1148. *
  1149. * @element ANY
  1150. * @param {string=} ngJq the name of the library available under `window`
  1151. * to be used for angular.element
  1152. * @description
  1153. * Use this directive to force the angular.element library. This should be
  1154. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1155. * the jquery variable under window (eg. jQuery).
  1156. *
  1157. * Since angular looks for this directive when it is loaded (doesn't wait for the
  1158. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1159. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1160. * others ignored.
  1161. *
  1162. * @example
  1163. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1164. ```html
  1165. <!doctype html>
  1166. <html ng-app ng-jq>
  1167. ...
  1168. ...
  1169. </html>
  1170. ```
  1171. * @example
  1172. * This example shows how to use a jQuery based library of a different name.
  1173. * The library name must be available at the top most 'window'.
  1174. ```html
  1175. <!doctype html>
  1176. <html ng-app ng-jq="jQueryLib">
  1177. ...
  1178. ...
  1179. </html>
  1180. ```
  1181. */
  1182. var jq = function() {
  1183. if (isDefined(jq.name_)) return jq.name_;
  1184. var el;
  1185. var i, ii = ngAttrPrefixes.length, prefix, name;
  1186. for (i = 0; i < ii; ++i) {
  1187. prefix = ngAttrPrefixes[i];
  1188. el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
  1189. if (el) {
  1190. name = el.getAttribute(prefix + 'jq');
  1191. break;
  1192. }
  1193. }
  1194. return (jq.name_ = name);
  1195. };
  1196. function concat(array1, array2, index) {
  1197. return array1.concat(slice.call(array2, index));
  1198. }
  1199. function sliceArgs(args, startIndex) {
  1200. return slice.call(args, startIndex || 0);
  1201. }
  1202. /**
  1203. * @ngdoc function
  1204. * @name angular.bind
  1205. * @module ng
  1206. * @kind function
  1207. *
  1208. * @description
  1209. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1210. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1211. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1212. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1213. *
  1214. * @param {Object} self Context which `fn` should be evaluated in.
  1215. * @param {function()} fn Function to be bound.
  1216. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1217. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1218. */
  1219. function bind(self, fn) {
  1220. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1221. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1222. return curryArgs.length
  1223. ? function() {
  1224. return arguments.length
  1225. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1226. : fn.apply(self, curryArgs);
  1227. }
  1228. : function() {
  1229. return arguments.length
  1230. ? fn.apply(self, arguments)
  1231. : fn.call(self);
  1232. };
  1233. } else {
  1234. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1235. return fn;
  1236. }
  1237. }
  1238. function toJsonReplacer(key, value) {
  1239. var val = value;
  1240. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1241. val = undefined;
  1242. } else if (isWindow(value)) {
  1243. val = '$WINDOW';
  1244. } else if (value && window.document === value) {
  1245. val = '$DOCUMENT';
  1246. } else if (isScope(value)) {
  1247. val = '$SCOPE';
  1248. }
  1249. return val;
  1250. }
  1251. /**
  1252. * @ngdoc function
  1253. * @name angular.toJson
  1254. * @module ng
  1255. * @kind function
  1256. *
  1257. * @description
  1258. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1259. * stripped since angular uses this notation internally.
  1260. *
  1261. * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
  1262. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1263. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1264. * @returns {string|undefined} JSON-ified string representing `obj`.
  1265. * @knownIssue
  1266. *
  1267. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1268. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1269. * `Date.prototype.toJSON` method as follows:
  1270. *
  1271. * ```
  1272. * var _DatetoJSON = Date.prototype.toJSON;
  1273. * Date.prototype.toJSON = function() {
  1274. * try {
  1275. * return _DatetoJSON.call(this);
  1276. * } catch(e) {
  1277. * if (e instanceof RangeError) {
  1278. * return null;
  1279. * }
  1280. * throw e;
  1281. * }
  1282. * };
  1283. * ```
  1284. *
  1285. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1286. */
  1287. function toJson(obj, pretty) {
  1288. if (isUndefined(obj)) return undefined;
  1289. if (!isNumber(pretty)) {
  1290. pretty = pretty ? 2 : null;
  1291. }
  1292. return JSON.stringify(obj, toJsonReplacer, pretty);
  1293. }
  1294. /**
  1295. * @ngdoc function
  1296. * @name angular.fromJson
  1297. * @module ng
  1298. * @kind function
  1299. *
  1300. * @description
  1301. * Deserializes a JSON string.
  1302. *
  1303. * @param {string} json JSON string to deserialize.
  1304. * @returns {Object|Array|string|number} Deserialized JSON string.
  1305. */
  1306. function fromJson(json) {
  1307. return isString(json)
  1308. ? JSON.parse(json)
  1309. : json;
  1310. }
  1311. var ALL_COLONS = /:/g;
  1312. function timezoneToOffset(timezone, fallback) {
  1313. // Support: IE 9-11 only, Edge 13-15+
  1314. // IE/Edge do not "understand" colon (`:`) in timezone
  1315. timezone = timezone.replace(ALL_COLONS, '');
  1316. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1317. return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1318. }
  1319. function addDateMinutes(date, minutes) {
  1320. date = new Date(date.getTime());
  1321. date.setMinutes(date.getMinutes() + minutes);
  1322. return date;
  1323. }
  1324. function convertTimezoneToLocal(date, timezone, reverse) {
  1325. reverse = reverse ? -1 : 1;
  1326. var dateTimezoneOffset = date.getTimezoneOffset();
  1327. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1328. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1329. }
  1330. /**
  1331. * @returns {string} Returns the string representation of the element.
  1332. */
  1333. function startingTag(element) {
  1334. element = jqLite(element).clone().empty();
  1335. var elemHtml = jqLite('<div>').append(element).html();
  1336. try {
  1337. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1338. elemHtml.
  1339. match(/^(<[^>]+>)/)[1].
  1340. replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1341. } catch (e) {
  1342. return lowercase(elemHtml);
  1343. }
  1344. }
  1345. /////////////////////////////////////////////////
  1346. /**
  1347. * Tries to decode the URI component without throwing an exception.
  1348. *
  1349. * @private
  1350. * @param str value potential URI component to check.
  1351. * @returns {boolean} True if `value` can be decoded
  1352. * with the decodeURIComponent function.
  1353. */
  1354. function tryDecodeURIComponent(value) {
  1355. try {
  1356. return decodeURIComponent(value);
  1357. } catch (e) {
  1358. // Ignore any invalid uri component.
  1359. }
  1360. }
  1361. /**
  1362. * Parses an escaped url query string into key-value pairs.
  1363. * @returns {Object.<string,boolean|Array>}
  1364. */
  1365. function parseKeyValue(/**string*/keyValue) {
  1366. var obj = {};
  1367. forEach((keyValue || '').split('&'), function(keyValue) {
  1368. var splitPoint, key, val;
  1369. if (keyValue) {
  1370. key = keyValue = keyValue.replace(/\+/g,'%20');
  1371. splitPoint = keyValue.indexOf('=');
  1372. if (splitPoint !== -1) {
  1373. key = keyValue.substring(0, splitPoint);
  1374. val = keyValue.substring(splitPoint + 1);
  1375. }
  1376. key = tryDecodeURIComponent(key);
  1377. if (isDefined(key)) {
  1378. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1379. if (!hasOwnProperty.call(obj, key)) {
  1380. obj[key] = val;
  1381. } else if (isArray(obj[key])) {
  1382. obj[key].push(val);
  1383. } else {
  1384. obj[key] = [obj[key],val];
  1385. }
  1386. }
  1387. }
  1388. });
  1389. return obj;
  1390. }
  1391. function toKeyValue(obj) {
  1392. var parts = [];
  1393. forEach(obj, function(value, key) {
  1394. if (isArray(value)) {
  1395. forEach(value, function(arrayValue) {
  1396. parts.push(encodeUriQuery(key, true) +
  1397. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1398. });
  1399. } else {
  1400. parts.push(encodeUriQuery(key, true) +
  1401. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1402. }
  1403. });
  1404. return parts.length ? parts.join('&') : '';
  1405. }
  1406. /**
  1407. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1408. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1409. * segments:
  1410. * segment = *pchar
  1411. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1412. * pct-encoded = "%" HEXDIG HEXDIG
  1413. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1414. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1415. * / "*" / "+" / "," / ";" / "="
  1416. */
  1417. function encodeUriSegment(val) {
  1418. return encodeUriQuery(val, true).
  1419. replace(/%26/gi, '&').
  1420. replace(/%3D/gi, '=').
  1421. replace(/%2B/gi, '+');
  1422. }
  1423. /**
  1424. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1425. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1426. * encoded per http://tools.ietf.org/html/rfc3986:
  1427. * query = *( pchar / "/" / "?" )
  1428. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1429. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1430. * pct-encoded = "%" HEXDIG HEXDIG
  1431. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1432. * / "*" / "+" / "," / ";" / "="
  1433. */
  1434. function encodeUriQuery(val, pctEncodeSpaces) {
  1435. return encodeURIComponent(val).
  1436. replace(/%40/gi, '@').
  1437. replace(/%3A/gi, ':').
  1438. replace(/%24/g, '$').
  1439. replace(/%2C/gi, ',').
  1440. replace(/%3B/gi, ';').
  1441. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1442. }
  1443. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1444. function getNgAttribute(element, ngAttr) {
  1445. var attr, i, ii = ngAttrPrefixes.length;
  1446. for (i = 0; i < ii; ++i) {
  1447. attr = ngAttrPrefixes[i] + ngAttr;
  1448. if (isString(attr = element.getAttribute(attr))) {
  1449. return attr;
  1450. }
  1451. }
  1452. return null;
  1453. }
  1454. function allowAutoBootstrap(document) {
  1455. var script = document.currentScript;
  1456. if (!script) {
  1457. // Support: IE 9-11 only
  1458. // IE does not have `document.currentScript`
  1459. return true;
  1460. }
  1461. // If the `currentScript` property has been clobbered just return false, since this indicates a probable attack
  1462. if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) {
  1463. return false;
  1464. }
  1465. var attributes = script.attributes;
  1466. var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')];
  1467. return srcs.every(function(src) {
  1468. if (!src) {
  1469. return true;
  1470. }
  1471. if (!src.value) {
  1472. return false;
  1473. }
  1474. var link = document.createElement('a');
  1475. link.href = src.value;
  1476. if (document.location.origin === link.origin) {
  1477. // Same-origin resources are always allowed, even for non-whitelisted schemes.
  1478. return true;
  1479. }
  1480. // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
  1481. // This is to prevent angular.js bundled with browser extensions from being used to bypass the
  1482. // content security policy in web pages and other browser extensions.
  1483. switch (link.protocol) {
  1484. case 'http:':
  1485. case 'https:':
  1486. case 'ftp:':
  1487. case 'blob:':
  1488. case 'file:':
  1489. case 'data:':
  1490. return true;
  1491. default:
  1492. return false;
  1493. }
  1494. });
  1495. }
  1496. // Cached as it has to run during loading so that document.currentScript is available.
  1497. var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
  1498. /**
  1499. * @ngdoc directive
  1500. * @name ngApp
  1501. * @module ng
  1502. *
  1503. * @element ANY
  1504. * @param {angular.Module} ngApp an optional application
  1505. * {@link angular.module module} name to load.
  1506. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1507. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1508. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1509. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1510. * tracking down the root of these bugs.
  1511. *
  1512. * @description
  1513. *
  1514. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1515. * designates the **root element** of the application and is typically placed near the root element
  1516. * of the page - e.g. on the `<body>` or `<html>` tags.
  1517. *
  1518. * There are a few things to keep in mind when using `ngApp`:
  1519. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1520. * found in the document will be used to define the root element to auto-bootstrap as an
  1521. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1522. * {@link angular.bootstrap} instead.
  1523. * - AngularJS applications cannot be nested within each other.
  1524. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1525. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1526. * {@link ngRoute.ngView `ngView`}.
  1527. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1528. * causing animations to stop working and making the injector inaccessible from outside the app.
  1529. *
  1530. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1531. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1532. * should contain the application code needed or have dependencies on other modules that will
  1533. * contain the code. See {@link angular.module} for more information.
  1534. *
  1535. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1536. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1537. * would not be resolved to `3`.
  1538. *
  1539. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1540. *
  1541. <example module="ngAppDemo" name="ng-app">
  1542. <file name="index.html">
  1543. <div ng-controller="ngAppDemoController">
  1544. I can add: {{a}} + {{b}} = {{ a+b }}
  1545. </div>
  1546. </file>
  1547. <file name="script.js">
  1548. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1549. $scope.a = 1;
  1550. $scope.b = 2;
  1551. });
  1552. </file>
  1553. </example>
  1554. *
  1555. * Using `ngStrictDi`, you would see something like this:
  1556. *
  1557. <example ng-app-included="true" name="strict-di">
  1558. <file name="index.html">
  1559. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1560. <div ng-controller="GoodController1">
  1561. I can add: {{a}} + {{b}} = {{ a+b }}
  1562. <p>This renders because the controller does not fail to
  1563. instantiate, by using explicit annotation style (see
  1564. script.js for details)
  1565. </p>
  1566. </div>
  1567. <div ng-controller="GoodController2">
  1568. Name: <input ng-model="name"><br />
  1569. Hello, {{name}}!
  1570. <p>This renders because the controller does not fail to
  1571. instantiate, by using explicit annotation style
  1572. (see script.js for details)
  1573. </p>
  1574. </div>
  1575. <div ng-controller="BadController">
  1576. I can add: {{a}} + {{b}} = {{ a+b }}
  1577. <p>The controller could not be instantiated, due to relying
  1578. on automatic function annotations (which are disabled in
  1579. strict mode). As such, the content of this section is not
  1580. interpolated, and there should be an error in your web console.
  1581. </p>
  1582. </div>
  1583. </div>
  1584. </file>
  1585. <file name="script.js">
  1586. angular.module('ngAppStrictDemo', [])
  1587. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1588. // rather than an explicit annotation
  1589. .controller('BadController', function($scope) {
  1590. $scope.a = 1;
  1591. $scope.b = 2;
  1592. })
  1593. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1594. // due to using explicit annotations using the array style and $inject property, respectively.
  1595. .controller('GoodController1', ['$scope', function($scope) {
  1596. $scope.a = 1;
  1597. $scope.b = 2;
  1598. }])
  1599. .controller('GoodController2', GoodController2);
  1600. function GoodController2($scope) {
  1601. $scope.name = 'World';
  1602. }
  1603. GoodController2.$inject = ['$scope'];
  1604. </file>
  1605. <file name="style.css">
  1606. div[ng-controller] {
  1607. margin-bottom: 1em;
  1608. -webkit-border-radius: 4px;
  1609. border-radius: 4px;
  1610. border: 1px solid;
  1611. padding: .5em;
  1612. }
  1613. div[ng-controller^=Good] {
  1614. border-color: #d6e9c6;
  1615. background-color: #dff0d8;
  1616. color: #3c763d;
  1617. }
  1618. div[ng-controller^=Bad] {
  1619. border-color: #ebccd1;
  1620. background-color: #f2dede;
  1621. color: #a94442;
  1622. margin-bottom: 0;
  1623. }
  1624. </file>
  1625. </example>
  1626. */
  1627. function angularInit(element, bootstrap) {
  1628. var appElement,
  1629. module,
  1630. config = {};
  1631. // The element `element` has priority over any other element.
  1632. forEach(ngAttrPrefixes, function(prefix) {
  1633. var name = prefix + 'app';
  1634. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1635. appElement = element;
  1636. module = element.getAttribute(name);
  1637. }
  1638. });
  1639. forEach(ngAttrPrefixes, function(prefix) {
  1640. var name = prefix + 'app';
  1641. var candidate;
  1642. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1643. appElement = candidate;
  1644. module = candidate.getAttribute(name);
  1645. }
  1646. });
  1647. if (appElement) {
  1648. if (!isAutoBootstrapAllowed) {
  1649. window.console.error('Angular: disabling automatic bootstrap. <script> protocol indicates ' +
  1650. 'an extension, document.location.href does not match.');
  1651. return;
  1652. }
  1653. config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
  1654. bootstrap(appElement, module ? [module] : [], config);
  1655. }
  1656. }
  1657. /**
  1658. * @ngdoc function
  1659. * @name angular.bootstrap
  1660. * @module ng
  1661. * @description
  1662. * Use this function to manually start up angular application.
  1663. *
  1664. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1665. *
  1666. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1667. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1668. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1669. * multiple instances of Angular try to work on the DOM.
  1670. *
  1671. * <div class="alert alert-warning">
  1672. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1673. * They must use {@link ng.directive:ngApp ngApp}.
  1674. * </div>
  1675. *
  1676. * <div class="alert alert-warning">
  1677. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1678. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1679. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1680. * causing animations to stop working and making the injector inaccessible from outside the app.
  1681. * </div>
  1682. *
  1683. * ```html
  1684. * <!doctype html>
  1685. * <html>
  1686. * <body>
  1687. * <div ng-controller="WelcomeController">
  1688. * {{greeting}}
  1689. * </div>
  1690. *
  1691. * <script src="angular.js"></script>
  1692. * <script>
  1693. * var app = angular.module('demo', [])
  1694. * .controller('WelcomeController', function($scope) {
  1695. * $scope.greeting = 'Welcome!';
  1696. * });
  1697. * angular.bootstrap(document, ['demo']);
  1698. * </script>
  1699. * </body>
  1700. * </html>
  1701. * ```
  1702. *
  1703. * @param {DOMElement} element DOM element which is the root of angular application.
  1704. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1705. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1706. * function that will be invoked by the injector as a `config` block.
  1707. * See: {@link angular.module modules}
  1708. * @param {Object=} config an object for defining configuration options for the application. The
  1709. * following keys are supported:
  1710. *
  1711. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1712. * assist in finding bugs which break minified code. Defaults to `false`.
  1713. *
  1714. * @returns {auto.$injector} Returns the newly created injector for this app.
  1715. */
  1716. function bootstrap(element, modules, config) {
  1717. if (!isObject(config)) config = {};
  1718. var defaultConfig = {
  1719. strictDi: false
  1720. };
  1721. config = extend(defaultConfig, config);
  1722. var doBootstrap = function() {
  1723. element = jqLite(element);
  1724. if (element.injector()) {
  1725. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1726. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1727. throw ngMinErr(
  1728. 'btstrpd',
  1729. 'App already bootstrapped with this element \'{0}\'',
  1730. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1731. }
  1732. modules = modules || [];
  1733. modules.unshift(['$provide', function($provide) {
  1734. $provide.value('$rootElement', element);
  1735. }]);
  1736. if (config.debugInfoEnabled) {
  1737. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1738. modules.push(['$compileProvider', function($compileProvider) {
  1739. $compileProvider.debugInfoEnabled(true);
  1740. }]);
  1741. }
  1742. modules.unshift('ng');
  1743. var injector = createInjector(modules, config.strictDi);
  1744. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1745. function bootstrapApply(scope, element, compile, injector) {
  1746. scope.$apply(function() {
  1747. element.data('$injector', injector);
  1748. compile(element)(scope);
  1749. });
  1750. }]
  1751. );
  1752. return injector;
  1753. };
  1754. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1755. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1756. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1757. config.debugInfoEnabled = true;
  1758. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1759. }
  1760. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1761. return doBootstrap();
  1762. }
  1763. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1764. angular.resumeBootstrap = function(extraModules) {
  1765. forEach(extraModules, function(module) {
  1766. modules.push(module);
  1767. });
  1768. return doBootstrap();
  1769. };
  1770. if (isFunction(angular.resumeDeferredBootstrap)) {
  1771. angular.resumeDeferredBootstrap();
  1772. }
  1773. }
  1774. /**
  1775. * @ngdoc function
  1776. * @name angular.reloadWithDebugInfo
  1777. * @module ng
  1778. * @description
  1779. * Use this function to reload the current application with debug information turned on.
  1780. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1781. *
  1782. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1783. */
  1784. function reloadWithDebugInfo() {
  1785. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1786. window.location.reload();
  1787. }
  1788. /**
  1789. * @name angular.getTestability
  1790. * @module ng
  1791. * @description
  1792. * Get the testability service for the instance of Angular on the given
  1793. * element.
  1794. * @param {DOMElement} element DOM element which is the root of angular application.
  1795. */
  1796. function getTestability(rootElement) {
  1797. var injector = angular.element(rootElement).injector();
  1798. if (!injector) {
  1799. throw ngMinErr('test',
  1800. 'no injector found for element argument to getTestability');
  1801. }
  1802. return injector.get('$$testability');
  1803. }
  1804. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1805. function snake_case(name, separator) {
  1806. separator = separator || '_';
  1807. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1808. return (pos ? separator : '') + letter.toLowerCase();
  1809. });
  1810. }
  1811. var bindJQueryFired = false;
  1812. function bindJQuery() {
  1813. var originalCleanData;
  1814. if (bindJQueryFired) {
  1815. return;
  1816. }
  1817. // bind to jQuery if present;
  1818. var jqName = jq();
  1819. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1820. !jqName ? undefined : // use jqLite
  1821. window[jqName]; // use jQuery specified by `ngJq`
  1822. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1823. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1824. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1825. // versions. It will not work for sure with jQuery <1.7, though.
  1826. if (jQuery && jQuery.fn.on) {
  1827. jqLite = jQuery;
  1828. extend(jQuery.fn, {
  1829. scope: JQLitePrototype.scope,
  1830. isolateScope: JQLitePrototype.isolateScope,
  1831. controller: /** @type {?} */ (JQLitePrototype).controller,
  1832. injector: JQLitePrototype.injector,
  1833. inheritedData: JQLitePrototype.inheritedData
  1834. });
  1835. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1836. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1837. // the $destroy event on all removed nodes.
  1838. originalCleanData = jQuery.cleanData;
  1839. jQuery.cleanData = function(elems) {
  1840. var events;
  1841. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1842. events = jQuery._data(elem, 'events');
  1843. if (events && events.$destroy) {
  1844. jQuery(elem).triggerHandler('$destroy');
  1845. }
  1846. }
  1847. originalCleanData(elems);
  1848. };
  1849. } else {
  1850. jqLite = JQLite;
  1851. }
  1852. angular.element = jqLite;
  1853. // Prevent double-proxying.
  1854. bindJQueryFired = true;
  1855. }
  1856. /**
  1857. * throw error if the argument is falsy.
  1858. */
  1859. function assertArg(arg, name, reason) {
  1860. if (!arg) {
  1861. throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
  1862. }
  1863. return arg;
  1864. }
  1865. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1866. if (acceptArrayAnnotation && isArray(arg)) {
  1867. arg = arg[arg.length - 1];
  1868. }
  1869. assertArg(isFunction(arg), name, 'not a function, got ' +
  1870. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1871. return arg;
  1872. }
  1873. /**
  1874. * throw error if the name given is hasOwnProperty
  1875. * @param {String} name the name to test
  1876. * @param {String} context the context in which the name is used, such as module or directive
  1877. */
  1878. function assertNotHasOwnProperty(name, context) {
  1879. if (name === 'hasOwnProperty') {
  1880. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1881. }
  1882. }
  1883. /**
  1884. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1885. * @param {Object} obj starting object
  1886. * @param {String} path path to traverse
  1887. * @param {boolean} [bindFnToScope=true]
  1888. * @returns {Object} value as accessible by path
  1889. */
  1890. //TODO(misko): this function needs to be removed
  1891. function getter(obj, path, bindFnToScope) {
  1892. if (!path) return obj;
  1893. var keys = path.split('.');
  1894. var key;
  1895. var lastInstance = obj;
  1896. var len = keys.length;
  1897. for (var i = 0; i < len; i++) {
  1898. key = keys[i];
  1899. if (obj) {
  1900. obj = (lastInstance = obj)[key];
  1901. }
  1902. }
  1903. if (!bindFnToScope && isFunction(obj)) {
  1904. return bind(lastInstance, obj);
  1905. }
  1906. return obj;
  1907. }
  1908. /**
  1909. * Return the DOM siblings between the first and last node in the given array.
  1910. * @param {Array} array like object
  1911. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1912. */
  1913. function getBlockNodes(nodes) {
  1914. // TODO(perf): update `nodes` instead of creating a new object?
  1915. var node = nodes[0];
  1916. var endNode = nodes[nodes.length - 1];
  1917. var blockNodes;
  1918. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1919. if (blockNodes || nodes[i] !== node) {
  1920. if (!blockNodes) {
  1921. blockNodes = jqLite(slice.call(nodes, 0, i));
  1922. }
  1923. blockNodes.push(node);
  1924. }
  1925. }
  1926. return blockNodes || nodes;
  1927. }
  1928. /**
  1929. * Creates a new object without a prototype. This object is useful for lookup without having to
  1930. * guard against prototypically inherited properties via hasOwnProperty.
  1931. *
  1932. * Related micro-benchmarks:
  1933. * - http://jsperf.com/object-create2
  1934. * - http://jsperf.com/proto-map-lookup/2
  1935. * - http://jsperf.com/for-in-vs-object-keys2
  1936. *
  1937. * @returns {Object}
  1938. */
  1939. function createMap() {
  1940. return Object.create(null);
  1941. }
  1942. function stringify(value) {
  1943. if (value == null) { // null || undefined
  1944. return '';
  1945. }
  1946. switch (typeof value) {
  1947. case 'string':
  1948. break;
  1949. case 'number':
  1950. value = '' + value;
  1951. break;
  1952. default:
  1953. if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
  1954. value = value.toString();
  1955. } else {
  1956. value = toJson(value);
  1957. }
  1958. }
  1959. return value;
  1960. }
  1961. var NODE_TYPE_ELEMENT = 1;
  1962. var NODE_TYPE_ATTRIBUTE = 2;
  1963. var NODE_TYPE_TEXT = 3;
  1964. var NODE_TYPE_COMMENT = 8;
  1965. var NODE_TYPE_DOCUMENT = 9;
  1966. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1967. /**
  1968. * @ngdoc type
  1969. * @name angular.Module
  1970. * @module ng
  1971. * @description
  1972. *
  1973. * Interface for configuring angular {@link angular.module modules}.
  1974. */
  1975. function setupModuleLoader(window) {
  1976. var $injectorMinErr = minErr('$injector');
  1977. var ngMinErr = minErr('ng');
  1978. function ensure(obj, name, factory) {
  1979. return obj[name] || (obj[name] = factory());
  1980. }
  1981. var angular = ensure(window, 'angular', Object);
  1982. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1983. angular.$$minErr = angular.$$minErr || minErr;
  1984. return ensure(angular, 'module', function() {
  1985. /** @type {Object.<string, angular.Module>} */
  1986. var modules = {};
  1987. /**
  1988. * @ngdoc function
  1989. * @name angular.module
  1990. * @module ng
  1991. * @description
  1992. *
  1993. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1994. * modules.
  1995. * All modules (angular core or 3rd party) that should be available to an application must be
  1996. * registered using this mechanism.
  1997. *
  1998. * Passing one argument retrieves an existing {@link angular.Module},
  1999. * whereas passing more than one argument creates a new {@link angular.Module}
  2000. *
  2001. *
  2002. * # Module
  2003. *
  2004. * A module is a collection of services, directives, controllers, filters, and configuration information.
  2005. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  2006. *
  2007. * ```js
  2008. * // Create a new module
  2009. * var myModule = angular.module('myModule', []);
  2010. *
  2011. * // register a new service
  2012. * myModule.value('appName', 'MyCoolApp');
  2013. *
  2014. * // configure existing services inside initialization blocks.
  2015. * myModule.config(['$locationProvider', function($locationProvider) {
  2016. * // Configure existing providers
  2017. * $locationProvider.hashPrefix('!');
  2018. * }]);
  2019. * ```
  2020. *
  2021. * Then you can create an injector and load your modules like this:
  2022. *
  2023. * ```js
  2024. * var injector = angular.injector(['ng', 'myModule'])
  2025. * ```
  2026. *
  2027. * However it's more likely that you'll just use
  2028. * {@link ng.directive:ngApp ngApp} or
  2029. * {@link angular.bootstrap} to simplify this process for you.
  2030. *
  2031. * @param {!string} name The name of the module to create or retrieve.
  2032. * @param {!Array.<string>=} requires If specified then new module is being created. If
  2033. * unspecified then the module is being retrieved for further configuration.
  2034. * @param {Function=} configFn Optional configuration function for the module. Same as
  2035. * {@link angular.Module#config Module#config()}.
  2036. * @returns {angular.Module} new module with the {@link angular.Module} api.
  2037. */
  2038. return function module(name, requires, configFn) {
  2039. var info = {};
  2040. var assertNotHasOwnProperty = function(name, context) {
  2041. if (name === 'hasOwnProperty') {
  2042. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  2043. }
  2044. };
  2045. assertNotHasOwnProperty(name, 'module');
  2046. if (requires && modules.hasOwnProperty(name)) {
  2047. modules[name] = null;
  2048. }
  2049. return ensure(modules, name, function() {
  2050. if (!requires) {
  2051. throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
  2052. 'the module name or forgot to load it. If registering a module ensure that you ' +
  2053. 'specify the dependencies as the second argument.', name);
  2054. }
  2055. /** @type {!Array.<Array.<*>>} */
  2056. var invokeQueue = [];
  2057. /** @type {!Array.<Function>} */
  2058. var configBlocks = [];
  2059. /** @type {!Array.<Function>} */
  2060. var runBlocks = [];
  2061. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  2062. /** @type {angular.Module} */
  2063. var moduleInstance = {
  2064. // Private state
  2065. _invokeQueue: invokeQueue,
  2066. _configBlocks: configBlocks,
  2067. _runBlocks: runBlocks,
  2068. /**
  2069. * @ngdoc method
  2070. * @name angular.Module#info
  2071. * @module ng
  2072. *
  2073. * @param {Object=} info Information about the module
  2074. * @returns {Object|Module} The current info object for this module if called as a getter,
  2075. * or `this` if called as a setter.
  2076. *
  2077. * @description
  2078. * Read and write custom information about this module.
  2079. * For example you could put the version of the module in here.
  2080. *
  2081. * ```js
  2082. * angular.module('myModule', []).info({ version: '1.0.0' });
  2083. * ```
  2084. *
  2085. * The version could then be read back out by accessing the module elsewhere:
  2086. *
  2087. * ```
  2088. * var version = angular.module('myModule').info().version;
  2089. * ```
  2090. *
  2091. * You can also retrieve this information during runtime via the
  2092. * {@link $injector#modules `$injector.modules`} property:
  2093. *
  2094. * ```js
  2095. * var version = $injector.modules['myModule'].info().version;
  2096. * ```
  2097. */
  2098. info: function(value) {
  2099. if (isDefined(value)) {
  2100. if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value');
  2101. info = value;
  2102. return this;
  2103. }
  2104. return info;
  2105. },
  2106. /**
  2107. * @ngdoc property
  2108. * @name angular.Module#requires
  2109. * @module ng
  2110. *
  2111. * @description
  2112. * Holds the list of modules which the injector will load before the current module is
  2113. * loaded.
  2114. */
  2115. requires: requires,
  2116. /**
  2117. * @ngdoc property
  2118. * @name angular.Module#name
  2119. * @module ng
  2120. *
  2121. * @description
  2122. * Name of the module.
  2123. */
  2124. name: name,
  2125. /**
  2126. * @ngdoc method
  2127. * @name angular.Module#provider
  2128. * @module ng
  2129. * @param {string} name service name
  2130. * @param {Function} providerType Construction function for creating new instance of the
  2131. * service.
  2132. * @description
  2133. * See {@link auto.$provide#provider $provide.provider()}.
  2134. */
  2135. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  2136. /**
  2137. * @ngdoc method
  2138. * @name angular.Module#factory
  2139. * @module ng
  2140. * @param {string} name service name
  2141. * @param {Function} providerFunction Function for creating new instance of the service.
  2142. * @description
  2143. * See {@link auto.$provide#factory $provide.factory()}.
  2144. */
  2145. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  2146. /**
  2147. * @ngdoc method
  2148. * @name angular.Module#service
  2149. * @module ng
  2150. * @param {string} name service name
  2151. * @param {Function} constructor A constructor function that will be instantiated.
  2152. * @description
  2153. * See {@link auto.$provide#service $provide.service()}.
  2154. */
  2155. service: invokeLaterAndSetModuleName('$provide', 'service'),
  2156. /**
  2157. * @ngdoc method
  2158. * @name angular.Module#value
  2159. * @module ng
  2160. * @param {string} name service name
  2161. * @param {*} object Service instance object.
  2162. * @description
  2163. * See {@link auto.$provide#value $provide.value()}.
  2164. */
  2165. value: invokeLater('$provide', 'value'),
  2166. /**
  2167. * @ngdoc method
  2168. * @name angular.Module#constant
  2169. * @module ng
  2170. * @param {string} name constant name
  2171. * @param {*} object Constant value.
  2172. * @description
  2173. * Because the constants are fixed, they get applied before other provide methods.
  2174. * See {@link auto.$provide#constant $provide.constant()}.
  2175. */
  2176. constant: invokeLater('$provide', 'constant', 'unshift'),
  2177. /**
  2178. * @ngdoc method
  2179. * @name angular.Module#decorator
  2180. * @module ng
  2181. * @param {string} name The name of the service to decorate.
  2182. * @param {Function} decorFn This function will be invoked when the service needs to be
  2183. * instantiated and should return the decorated service instance.
  2184. * @description
  2185. * See {@link auto.$provide#decorator $provide.decorator()}.
  2186. */
  2187. decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
  2188. /**
  2189. * @ngdoc method
  2190. * @name angular.Module#animation
  2191. * @module ng
  2192. * @param {string} name animation name
  2193. * @param {Function} animationFactory Factory function for creating new instance of an
  2194. * animation.
  2195. * @description
  2196. *
  2197. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  2198. *
  2199. *
  2200. * Defines an animation hook that can be later used with
  2201. * {@link $animate $animate} service and directives that use this service.
  2202. *
  2203. * ```js
  2204. * module.animation('.animation-name', function($inject1, $inject2) {
  2205. * return {
  2206. * eventName : function(element, done) {
  2207. * //code to run the animation
  2208. * //once complete, then run done()
  2209. * return function cancellationFunction(element) {
  2210. * //code to cancel the animation
  2211. * }
  2212. * }
  2213. * }
  2214. * })
  2215. * ```
  2216. *
  2217. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  2218. * {@link ngAnimate ngAnimate module} for more information.
  2219. */
  2220. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  2221. /**
  2222. * @ngdoc method
  2223. * @name angular.Module#filter
  2224. * @module ng
  2225. * @param {string} name Filter name - this must be a valid angular expression identifier
  2226. * @param {Function} filterFactory Factory function for creating new instance of filter.
  2227. * @description
  2228. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  2229. *
  2230. * <div class="alert alert-warning">
  2231. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  2232. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  2233. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  2234. * (`myapp_subsection_filterx`).
  2235. * </div>
  2236. */
  2237. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  2238. /**
  2239. * @ngdoc method
  2240. * @name angular.Module#controller
  2241. * @module ng
  2242. * @param {string|Object} name Controller name, or an object map of controllers where the
  2243. * keys are the names and the values are the constructors.
  2244. * @param {Function} constructor Controller constructor function.
  2245. * @description
  2246. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2247. */
  2248. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2249. /**
  2250. * @ngdoc method
  2251. * @name angular.Module#directive
  2252. * @module ng
  2253. * @param {string|Object} name Directive name, or an object map of directives where the
  2254. * keys are the names and the values are the factories.
  2255. * @param {Function} directiveFactory Factory function for creating new instance of
  2256. * directives.
  2257. * @description
  2258. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2259. */
  2260. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2261. /**
  2262. * @ngdoc method
  2263. * @name angular.Module#component
  2264. * @module ng
  2265. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  2266. * @param {Object} options Component definition object (a simplified
  2267. * {@link ng.$compile#directive-definition-object directive definition object})
  2268. *
  2269. * @description
  2270. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2271. */
  2272. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2273. /**
  2274. * @ngdoc method
  2275. * @name angular.Module#config
  2276. * @module ng
  2277. * @param {Function} configFn Execute this function on module load. Useful for service
  2278. * configuration.
  2279. * @description
  2280. * Use this method to register work which needs to be performed on module loading.
  2281. * For more about how to configure services, see
  2282. * {@link providers#provider-recipe Provider Recipe}.
  2283. */
  2284. config: config,
  2285. /**
  2286. * @ngdoc method
  2287. * @name angular.Module#run
  2288. * @module ng
  2289. * @param {Function} initializationFn Execute this function after injector creation.
  2290. * Useful for application initialization.
  2291. * @description
  2292. * Use this method to register work which should be performed when the injector is done
  2293. * loading all modules.
  2294. */
  2295. run: function(block) {
  2296. runBlocks.push(block);
  2297. return this;
  2298. }
  2299. };
  2300. if (configFn) {
  2301. config(configFn);
  2302. }
  2303. return moduleInstance;
  2304. /**
  2305. * @param {string} provider
  2306. * @param {string} method
  2307. * @param {String=} insertMethod
  2308. * @returns {angular.Module}
  2309. */
  2310. function invokeLater(provider, method, insertMethod, queue) {
  2311. if (!queue) queue = invokeQueue;
  2312. return function() {
  2313. queue[insertMethod || 'push']([provider, method, arguments]);
  2314. return moduleInstance;
  2315. };
  2316. }
  2317. /**
  2318. * @param {string} provider
  2319. * @param {string} method
  2320. * @returns {angular.Module}
  2321. */
  2322. function invokeLaterAndSetModuleName(provider, method, queue) {
  2323. if (!queue) queue = invokeQueue;
  2324. return function(recipeName, factoryFunction) {
  2325. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2326. queue.push([provider, method, arguments]);
  2327. return moduleInstance;
  2328. };
  2329. }
  2330. });
  2331. };
  2332. });
  2333. }
  2334. /* global shallowCopy: true */
  2335. /**
  2336. * Creates a shallow copy of an object, an array or a primitive.
  2337. *
  2338. * Assumes that there are no proto properties for objects.
  2339. */
  2340. function shallowCopy(src, dst) {
  2341. if (isArray(src)) {
  2342. dst = dst || [];
  2343. for (var i = 0, ii = src.length; i < ii; i++) {
  2344. dst[i] = src[i];
  2345. }
  2346. } else if (isObject(src)) {
  2347. dst = dst || {};
  2348. for (var key in src) {
  2349. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2350. dst[key] = src[key];
  2351. }
  2352. }
  2353. }
  2354. return dst || src;
  2355. }
  2356. /* exported toDebugString */
  2357. function serializeObject(obj, maxDepth) {
  2358. var seen = [];
  2359. // There is no direct way to stringify object until reaching a specific depth
  2360. // and a very deep object can cause a performance issue, so we copy the object
  2361. // based on this specific depth and then stringify it.
  2362. if (isValidObjectMaxDepth(maxDepth)) {
  2363. // This file is also included in `angular-loader`, so `copy()` might not always be available in
  2364. // the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed.
  2365. obj = angular.copy(obj, null, maxDepth);
  2366. }
  2367. return JSON.stringify(obj, function(key, val) {
  2368. val = toJsonReplacer(key, val);
  2369. if (isObject(val)) {
  2370. if (seen.indexOf(val) >= 0) return '...';
  2371. seen.push(val);
  2372. }
  2373. return val;
  2374. });
  2375. }
  2376. function toDebugString(obj, maxDepth) {
  2377. if (typeof obj === 'function') {
  2378. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2379. } else if (isUndefined(obj)) {
  2380. return 'undefined';
  2381. } else if (typeof obj !== 'string') {
  2382. return serializeObject(obj, maxDepth);
  2383. }
  2384. return obj;
  2385. }
  2386. /* global angularModule: true,
  2387. version: true,
  2388. $CompileProvider,
  2389. htmlAnchorDirective,
  2390. inputDirective,
  2391. inputDirective,
  2392. formDirective,
  2393. scriptDirective,
  2394. selectDirective,
  2395. optionDirective,
  2396. ngBindDirective,
  2397. ngBindHtmlDirective,
  2398. ngBindTemplateDirective,
  2399. ngClassDirective,
  2400. ngClassEvenDirective,
  2401. ngClassOddDirective,
  2402. ngCloakDirective,
  2403. ngControllerDirective,
  2404. ngFormDirective,
  2405. ngHideDirective,
  2406. ngIfDirective,
  2407. ngIncludeDirective,
  2408. ngIncludeFillContentDirective,
  2409. ngInitDirective,
  2410. ngNonBindableDirective,
  2411. ngPluralizeDirective,
  2412. ngRepeatDirective,
  2413. ngShowDirective,
  2414. ngStyleDirective,
  2415. ngSwitchDirective,
  2416. ngSwitchWhenDirective,
  2417. ngSwitchDefaultDirective,
  2418. ngOptionsDirective,
  2419. ngTranscludeDirective,
  2420. ngModelDirective,
  2421. ngListDirective,
  2422. ngChangeDirective,
  2423. patternDirective,
  2424. patternDirective,
  2425. requiredDirective,
  2426. requiredDirective,
  2427. minlengthDirective,
  2428. minlengthDirective,
  2429. maxlengthDirective,
  2430. maxlengthDirective,
  2431. ngValueDirective,
  2432. ngModelOptionsDirective,
  2433. ngAttributeAliasDirectives,
  2434. ngEventDirectives,
  2435. $AnchorScrollProvider,
  2436. $AnimateProvider,
  2437. $CoreAnimateCssProvider,
  2438. $$CoreAnimateJsProvider,
  2439. $$CoreAnimateQueueProvider,
  2440. $$AnimateRunnerFactoryProvider,
  2441. $$AnimateAsyncRunFactoryProvider,
  2442. $BrowserProvider,
  2443. $CacheFactoryProvider,
  2444. $ControllerProvider,
  2445. $DateProvider,
  2446. $DocumentProvider,
  2447. $$IsDocumentHiddenProvider,
  2448. $ExceptionHandlerProvider,
  2449. $FilterProvider,
  2450. $$ForceReflowProvider,
  2451. $InterpolateProvider,
  2452. $IntervalProvider,
  2453. $HttpProvider,
  2454. $HttpParamSerializerProvider,
  2455. $HttpParamSerializerJQLikeProvider,
  2456. $HttpBackendProvider,
  2457. $xhrFactoryProvider,
  2458. $jsonpCallbacksProvider,
  2459. $LocationProvider,
  2460. $LogProvider,
  2461. $$MapProvider,
  2462. $ParseProvider,
  2463. $RootScopeProvider,
  2464. $QProvider,
  2465. $$QProvider,
  2466. $$SanitizeUriProvider,
  2467. $SceProvider,
  2468. $SceDelegateProvider,
  2469. $SnifferProvider,
  2470. $TemplateCacheProvider,
  2471. $TemplateRequestProvider,
  2472. $$TestabilityProvider,
  2473. $TimeoutProvider,
  2474. $$RAFProvider,
  2475. $WindowProvider,
  2476. $$jqLiteProvider,
  2477. $$CookieReaderProvider
  2478. */
  2479. /**
  2480. * @ngdoc object
  2481. * @name angular.version
  2482. * @module ng
  2483. * @description
  2484. * An object that contains information about the current AngularJS version.
  2485. *
  2486. * This object has the following properties:
  2487. *
  2488. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2489. * - `major` – `{number}` – Major version number, such as "0".
  2490. * - `minor` – `{number}` – Minor version number, such as "9".
  2491. * - `dot` – `{number}` – Dot version number, such as "18".
  2492. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2493. */
  2494. var version = {
  2495. // These placeholder strings will be replaced by grunt's `build` task.
  2496. // They need to be double- or single-quoted.
  2497. full: '1.6.6',
  2498. major: 1,
  2499. minor: 6,
  2500. dot: 6,
  2501. codeName: 'interdimensional-cable'
  2502. };
  2503. function publishExternalAPI(angular) {
  2504. extend(angular, {
  2505. 'errorHandlingConfig': errorHandlingConfig,
  2506. 'bootstrap': bootstrap,
  2507. 'copy': copy,
  2508. 'extend': extend,
  2509. 'merge': merge,
  2510. 'equals': equals,
  2511. 'element': jqLite,
  2512. 'forEach': forEach,
  2513. 'injector': createInjector,
  2514. 'noop': noop,
  2515. 'bind': bind,
  2516. 'toJson': toJson,
  2517. 'fromJson': fromJson,
  2518. 'identity': identity,
  2519. 'isUndefined': isUndefined,
  2520. 'isDefined': isDefined,
  2521. 'isString': isString,
  2522. 'isFunction': isFunction,
  2523. 'isObject': isObject,
  2524. 'isNumber': isNumber,
  2525. 'isElement': isElement,
  2526. 'isArray': isArray,
  2527. 'version': version,
  2528. 'isDate': isDate,
  2529. 'lowercase': lowercase,
  2530. 'uppercase': uppercase,
  2531. 'callbacks': {$$counter: 0},
  2532. 'getTestability': getTestability,
  2533. 'reloadWithDebugInfo': reloadWithDebugInfo,
  2534. '$$minErr': minErr,
  2535. '$$csp': csp,
  2536. '$$encodeUriSegment': encodeUriSegment,
  2537. '$$encodeUriQuery': encodeUriQuery,
  2538. '$$stringify': stringify
  2539. });
  2540. angularModule = setupModuleLoader(window);
  2541. angularModule('ng', ['ngLocale'], ['$provide',
  2542. function ngModule($provide) {
  2543. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2544. $provide.provider({
  2545. $$sanitizeUri: $$SanitizeUriProvider
  2546. });
  2547. $provide.provider('$compile', $CompileProvider).
  2548. directive({
  2549. a: htmlAnchorDirective,
  2550. input: inputDirective,
  2551. textarea: inputDirective,
  2552. form: formDirective,
  2553. script: scriptDirective,
  2554. select: selectDirective,
  2555. option: optionDirective,
  2556. ngBind: ngBindDirective,
  2557. ngBindHtml: ngBindHtmlDirective,
  2558. ngBindTemplate: ngBindTemplateDirective,
  2559. ngClass: ngClassDirective,
  2560. ngClassEven: ngClassEvenDirective,
  2561. ngClassOdd: ngClassOddDirective,
  2562. ngCloak: ngCloakDirective,
  2563. ngController: ngControllerDirective,
  2564. ngForm: ngFormDirective,
  2565. ngHide: ngHideDirective,
  2566. ngIf: ngIfDirective,
  2567. ngInclude: ngIncludeDirective,
  2568. ngInit: ngInitDirective,
  2569. ngNonBindable: ngNonBindableDirective,
  2570. ngPluralize: ngPluralizeDirective,
  2571. ngRepeat: ngRepeatDirective,
  2572. ngShow: ngShowDirective,
  2573. ngStyle: ngStyleDirective,
  2574. ngSwitch: ngSwitchDirective,
  2575. ngSwitchWhen: ngSwitchWhenDirective,
  2576. ngSwitchDefault: ngSwitchDefaultDirective,
  2577. ngOptions: ngOptionsDirective,
  2578. ngTransclude: ngTranscludeDirective,
  2579. ngModel: ngModelDirective,
  2580. ngList: ngListDirective,
  2581. ngChange: ngChangeDirective,
  2582. pattern: patternDirective,
  2583. ngPattern: patternDirective,
  2584. required: requiredDirective,
  2585. ngRequired: requiredDirective,
  2586. minlength: minlengthDirective,
  2587. ngMinlength: minlengthDirective,
  2588. maxlength: maxlengthDirective,
  2589. ngMaxlength: maxlengthDirective,
  2590. ngValue: ngValueDirective,
  2591. ngModelOptions: ngModelOptionsDirective
  2592. }).
  2593. directive({
  2594. ngInclude: ngIncludeFillContentDirective
  2595. }).
  2596. directive(ngAttributeAliasDirectives).
  2597. directive(ngEventDirectives);
  2598. $provide.provider({
  2599. $anchorScroll: $AnchorScrollProvider,
  2600. $animate: $AnimateProvider,
  2601. $animateCss: $CoreAnimateCssProvider,
  2602. $$animateJs: $$CoreAnimateJsProvider,
  2603. $$animateQueue: $$CoreAnimateQueueProvider,
  2604. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2605. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2606. $browser: $BrowserProvider,
  2607. $cacheFactory: $CacheFactoryProvider,
  2608. $controller: $ControllerProvider,
  2609. $document: $DocumentProvider,
  2610. $$isDocumentHidden: $$IsDocumentHiddenProvider,
  2611. $exceptionHandler: $ExceptionHandlerProvider,
  2612. $filter: $FilterProvider,
  2613. $$forceReflow: $$ForceReflowProvider,
  2614. $interpolate: $InterpolateProvider,
  2615. $interval: $IntervalProvider,
  2616. $http: $HttpProvider,
  2617. $httpParamSerializer: $HttpParamSerializerProvider,
  2618. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2619. $httpBackend: $HttpBackendProvider,
  2620. $xhrFactory: $xhrFactoryProvider,
  2621. $jsonpCallbacks: $jsonpCallbacksProvider,
  2622. $location: $LocationProvider,
  2623. $log: $LogProvider,
  2624. $parse: $ParseProvider,
  2625. $rootScope: $RootScopeProvider,
  2626. $q: $QProvider,
  2627. $$q: $$QProvider,
  2628. $sce: $SceProvider,
  2629. $sceDelegate: $SceDelegateProvider,
  2630. $sniffer: $SnifferProvider,
  2631. $templateCache: $TemplateCacheProvider,
  2632. $templateRequest: $TemplateRequestProvider,
  2633. $$testability: $$TestabilityProvider,
  2634. $timeout: $TimeoutProvider,
  2635. $window: $WindowProvider,
  2636. $$rAF: $$RAFProvider,
  2637. $$jqLite: $$jqLiteProvider,
  2638. $$Map: $$MapProvider,
  2639. $$cookieReader: $$CookieReaderProvider
  2640. });
  2641. }
  2642. ])
  2643. .info({ angularVersion: '1.6.6' });
  2644. }
  2645. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2646. * Any commits to this file should be reviewed with security in mind. *
  2647. * Changes to this file can potentially create security vulnerabilities. *
  2648. * An approval from 2 Core members with history of modifying *
  2649. * this file is required. *
  2650. * *
  2651. * Does the change somehow allow for arbitrary javascript to be executed? *
  2652. * Or allows for someone to change the prototype of built-in objects? *
  2653. * Or gives undesired access to variables likes document or window? *
  2654. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2655. /* global
  2656. JQLitePrototype: true,
  2657. BOOLEAN_ATTR: true,
  2658. ALIASED_ATTR: true
  2659. */
  2660. //////////////////////////////////
  2661. //JQLite
  2662. //////////////////////////////////
  2663. /**
  2664. * @ngdoc function
  2665. * @name angular.element
  2666. * @module ng
  2667. * @kind function
  2668. *
  2669. * @description
  2670. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2671. *
  2672. * If jQuery is available, `angular.element` is an alias for the
  2673. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2674. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2675. *
  2676. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2677. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2678. * commonly needed functionality with the goal of having a very small footprint.
  2679. *
  2680. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2681. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2682. * specific version of jQuery if multiple versions exist on the page.
  2683. *
  2684. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2685. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2686. *
  2687. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2688. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2689. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2690. *
  2691. * ## Angular's jqLite
  2692. * jqLite provides only the following jQuery methods:
  2693. *
  2694. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2695. * - [`after()`](http://api.jquery.com/after/)
  2696. * - [`append()`](http://api.jquery.com/append/)
  2697. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2698. * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
  2699. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2700. * - [`clone()`](http://api.jquery.com/clone/)
  2701. * - [`contents()`](http://api.jquery.com/contents/)
  2702. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2703. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2704. * - [`data()`](http://api.jquery.com/data/)
  2705. * - [`detach()`](http://api.jquery.com/detach/)
  2706. * - [`empty()`](http://api.jquery.com/empty/)
  2707. * - [`eq()`](http://api.jquery.com/eq/)
  2708. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2709. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2710. * - [`html()`](http://api.jquery.com/html/)
  2711. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2712. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2713. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2714. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2715. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2716. * - [`prepend()`](http://api.jquery.com/prepend/)
  2717. * - [`prop()`](http://api.jquery.com/prop/)
  2718. * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
  2719. * - [`remove()`](http://api.jquery.com/remove/)
  2720. * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
  2721. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2722. * - [`removeData()`](http://api.jquery.com/removeData/)
  2723. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2724. * - [`text()`](http://api.jquery.com/text/)
  2725. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2726. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2727. * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
  2728. * - [`val()`](http://api.jquery.com/val/)
  2729. * - [`wrap()`](http://api.jquery.com/wrap/)
  2730. *
  2731. * ## jQuery/jqLite Extras
  2732. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2733. *
  2734. * ### Events
  2735. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2736. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2737. * element before it is removed.
  2738. *
  2739. * ### Methods
  2740. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2741. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2742. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2743. * `'ngModel'`).
  2744. * - `injector()` - retrieves the injector of the current element or its parent.
  2745. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2746. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2747. * be enabled.
  2748. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2749. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2750. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2751. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2752. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2753. * parent element is reached.
  2754. *
  2755. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2756. * https://github.com/angular/angular.js/issues/14251 for more information.
  2757. *
  2758. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2759. * @returns {Object} jQuery object.
  2760. */
  2761. JQLite.expando = 'ng339';
  2762. var jqCache = JQLite.cache = {},
  2763. jqId = 1;
  2764. /*
  2765. * !!! This is an undocumented "private" function !!!
  2766. */
  2767. JQLite._data = function(node) {
  2768. //jQuery always returns an object on cache miss
  2769. return this.cache[node[this.expando]] || {};
  2770. };
  2771. function jqNextId() { return ++jqId; }
  2772. var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
  2773. var MS_HACK_REGEXP = /^-ms-/;
  2774. var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
  2775. var jqLiteMinErr = minErr('jqLite');
  2776. /**
  2777. * Converts kebab-case to camelCase.
  2778. * There is also a special case for the ms prefix starting with a lowercase letter.
  2779. * @param name Name to normalize
  2780. */
  2781. function cssKebabToCamel(name) {
  2782. return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
  2783. }
  2784. function fnCamelCaseReplace(all, letter) {
  2785. return letter.toUpperCase();
  2786. }
  2787. /**
  2788. * Converts kebab-case to camelCase.
  2789. * @param name Name to normalize
  2790. */
  2791. function kebabToCamel(name) {
  2792. return name
  2793. .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
  2794. }
  2795. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2796. var HTML_REGEXP = /<|&#?\w+;/;
  2797. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2798. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2799. var wrapMap = {
  2800. 'option': [1, '<select multiple="multiple">', '</select>'],
  2801. 'thead': [1, '<table>', '</table>'],
  2802. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2803. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2804. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2805. '_default': [0, '', '']
  2806. };
  2807. wrapMap.optgroup = wrapMap.option;
  2808. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2809. wrapMap.th = wrapMap.td;
  2810. function jqLiteIsTextNode(html) {
  2811. return !HTML_REGEXP.test(html);
  2812. }
  2813. function jqLiteAcceptsData(node) {
  2814. // The window object can accept data but has no nodeType
  2815. // Otherwise we are only interested in elements (1) and documents (9)
  2816. var nodeType = node.nodeType;
  2817. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2818. }
  2819. function jqLiteHasData(node) {
  2820. for (var key in jqCache[node.ng339]) {
  2821. return true;
  2822. }
  2823. return false;
  2824. }
  2825. function jqLiteBuildFragment(html, context) {
  2826. var tmp, tag, wrap,
  2827. fragment = context.createDocumentFragment(),
  2828. nodes = [], i;
  2829. if (jqLiteIsTextNode(html)) {
  2830. // Convert non-html into a text node
  2831. nodes.push(context.createTextNode(html));
  2832. } else {
  2833. // Convert html into DOM nodes
  2834. tmp = fragment.appendChild(context.createElement('div'));
  2835. tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
  2836. wrap = wrapMap[tag] || wrapMap._default;
  2837. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
  2838. // Descend through wrappers to the right content
  2839. i = wrap[0];
  2840. while (i--) {
  2841. tmp = tmp.lastChild;
  2842. }
  2843. nodes = concat(nodes, tmp.childNodes);
  2844. tmp = fragment.firstChild;
  2845. tmp.textContent = '';
  2846. }
  2847. // Remove wrapper from fragment
  2848. fragment.textContent = '';
  2849. fragment.innerHTML = ''; // Clear inner HTML
  2850. forEach(nodes, function(node) {
  2851. fragment.appendChild(node);
  2852. });
  2853. return fragment;
  2854. }
  2855. function jqLiteParseHTML(html, context) {
  2856. context = context || window.document;
  2857. var parsed;
  2858. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2859. return [context.createElement(parsed[1])];
  2860. }
  2861. if ((parsed = jqLiteBuildFragment(html, context))) {
  2862. return parsed.childNodes;
  2863. }
  2864. return [];
  2865. }
  2866. function jqLiteWrapNode(node, wrapper) {
  2867. var parent = node.parentNode;
  2868. if (parent) {
  2869. parent.replaceChild(wrapper, node);
  2870. }
  2871. wrapper.appendChild(node);
  2872. }
  2873. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2874. var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
  2875. // eslint-disable-next-line no-bitwise
  2876. return !!(this.compareDocumentPosition(arg) & 16);
  2877. };
  2878. /////////////////////////////////////////////
  2879. function JQLite(element) {
  2880. if (element instanceof JQLite) {
  2881. return element;
  2882. }
  2883. var argIsString;
  2884. if (isString(element)) {
  2885. element = trim(element);
  2886. argIsString = true;
  2887. }
  2888. if (!(this instanceof JQLite)) {
  2889. if (argIsString && element.charAt(0) !== '<') {
  2890. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2891. }
  2892. return new JQLite(element);
  2893. }
  2894. if (argIsString) {
  2895. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2896. } else if (isFunction(element)) {
  2897. jqLiteReady(element);
  2898. } else {
  2899. jqLiteAddNodes(this, element);
  2900. }
  2901. }
  2902. function jqLiteClone(element) {
  2903. return element.cloneNode(true);
  2904. }
  2905. function jqLiteDealoc(element, onlyDescendants) {
  2906. if (!onlyDescendants && jqLiteAcceptsData(element)) jqLite.cleanData([element]);
  2907. if (element.querySelectorAll) {
  2908. jqLite.cleanData(element.querySelectorAll('*'));
  2909. }
  2910. }
  2911. function jqLiteOff(element, type, fn, unsupported) {
  2912. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2913. var expandoStore = jqLiteExpandoStore(element);
  2914. var events = expandoStore && expandoStore.events;
  2915. var handle = expandoStore && expandoStore.handle;
  2916. if (!handle) return; //no listeners registered
  2917. if (!type) {
  2918. for (type in events) {
  2919. if (type !== '$destroy') {
  2920. element.removeEventListener(type, handle);
  2921. }
  2922. delete events[type];
  2923. }
  2924. } else {
  2925. var removeHandler = function(type) {
  2926. var listenerFns = events[type];
  2927. if (isDefined(fn)) {
  2928. arrayRemove(listenerFns || [], fn);
  2929. }
  2930. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2931. element.removeEventListener(type, handle);
  2932. delete events[type];
  2933. }
  2934. };
  2935. forEach(type.split(' '), function(type) {
  2936. removeHandler(type);
  2937. if (MOUSE_EVENT_MAP[type]) {
  2938. removeHandler(MOUSE_EVENT_MAP[type]);
  2939. }
  2940. });
  2941. }
  2942. }
  2943. function jqLiteRemoveData(element, name) {
  2944. var expandoId = element.ng339;
  2945. var expandoStore = expandoId && jqCache[expandoId];
  2946. if (expandoStore) {
  2947. if (name) {
  2948. delete expandoStore.data[name];
  2949. return;
  2950. }
  2951. if (expandoStore.handle) {
  2952. if (expandoStore.events.$destroy) {
  2953. expandoStore.handle({}, '$destroy');
  2954. }
  2955. jqLiteOff(element);
  2956. }
  2957. delete jqCache[expandoId];
  2958. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2959. }
  2960. }
  2961. function jqLiteExpandoStore(element, createIfNecessary) {
  2962. var expandoId = element.ng339,
  2963. expandoStore = expandoId && jqCache[expandoId];
  2964. if (createIfNecessary && !expandoStore) {
  2965. element.ng339 = expandoId = jqNextId();
  2966. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2967. }
  2968. return expandoStore;
  2969. }
  2970. function jqLiteData(element, key, value) {
  2971. if (jqLiteAcceptsData(element)) {
  2972. var prop;
  2973. var isSimpleSetter = isDefined(value);
  2974. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2975. var massGetter = !key;
  2976. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2977. var data = expandoStore && expandoStore.data;
  2978. if (isSimpleSetter) { // data('key', value)
  2979. data[kebabToCamel(key)] = value;
  2980. } else {
  2981. if (massGetter) { // data()
  2982. return data;
  2983. } else {
  2984. if (isSimpleGetter) { // data('key')
  2985. // don't force creation of expandoStore if it doesn't exist yet
  2986. return data && data[kebabToCamel(key)];
  2987. } else { // mass-setter: data({key1: val1, key2: val2})
  2988. for (prop in key) {
  2989. data[kebabToCamel(prop)] = key[prop];
  2990. }
  2991. }
  2992. }
  2993. }
  2994. }
  2995. }
  2996. function jqLiteHasClass(element, selector) {
  2997. if (!element.getAttribute) return false;
  2998. return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
  2999. indexOf(' ' + selector + ' ') > -1);
  3000. }
  3001. function jqLiteRemoveClass(element, cssClasses) {
  3002. if (cssClasses && element.setAttribute) {
  3003. forEach(cssClasses.split(' '), function(cssClass) {
  3004. element.setAttribute('class', trim(
  3005. (' ' + (element.getAttribute('class') || '') + ' ')
  3006. .replace(/[\n\t]/g, ' ')
  3007. .replace(' ' + trim(cssClass) + ' ', ' '))
  3008. );
  3009. });
  3010. }
  3011. }
  3012. function jqLiteAddClass(element, cssClasses) {
  3013. if (cssClasses && element.setAttribute) {
  3014. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  3015. .replace(/[\n\t]/g, ' ');
  3016. forEach(cssClasses.split(' '), function(cssClass) {
  3017. cssClass = trim(cssClass);
  3018. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  3019. existingClasses += cssClass + ' ';
  3020. }
  3021. });
  3022. element.setAttribute('class', trim(existingClasses));
  3023. }
  3024. }
  3025. function jqLiteAddNodes(root, elements) {
  3026. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  3027. if (elements) {
  3028. // if a Node (the most common case)
  3029. if (elements.nodeType) {
  3030. root[root.length++] = elements;
  3031. } else {
  3032. var length = elements.length;
  3033. // if an Array or NodeList and not a Window
  3034. if (typeof length === 'number' && elements.window !== elements) {
  3035. if (length) {
  3036. for (var i = 0; i < length; i++) {
  3037. root[root.length++] = elements[i];
  3038. }
  3039. }
  3040. } else {
  3041. root[root.length++] = elements;
  3042. }
  3043. }
  3044. }
  3045. }
  3046. function jqLiteController(element, name) {
  3047. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  3048. }
  3049. function jqLiteInheritedData(element, name, value) {
  3050. // if element is the document object work with the html element instead
  3051. // this makes $(document).scope() possible
  3052. if (element.nodeType === NODE_TYPE_DOCUMENT) {
  3053. element = element.documentElement;
  3054. }
  3055. var names = isArray(name) ? name : [name];
  3056. while (element) {
  3057. for (var i = 0, ii = names.length; i < ii; i++) {
  3058. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  3059. }
  3060. // If dealing with a document fragment node with a host element, and no parent, use the host
  3061. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  3062. // to lookup parent controllers.
  3063. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  3064. }
  3065. }
  3066. function jqLiteEmpty(element) {
  3067. jqLiteDealoc(element, true);
  3068. while (element.firstChild) {
  3069. element.removeChild(element.firstChild);
  3070. }
  3071. }
  3072. function jqLiteRemove(element, keepData) {
  3073. if (!keepData) jqLiteDealoc(element);
  3074. var parent = element.parentNode;
  3075. if (parent) parent.removeChild(element);
  3076. }
  3077. function jqLiteDocumentLoaded(action, win) {
  3078. win = win || window;
  3079. if (win.document.readyState === 'complete') {
  3080. // Force the action to be run async for consistent behavior
  3081. // from the action's point of view
  3082. // i.e. it will definitely not be in a $apply
  3083. win.setTimeout(action);
  3084. } else {
  3085. // No need to unbind this handler as load is only ever called once
  3086. jqLite(win).on('load', action);
  3087. }
  3088. }
  3089. function jqLiteReady(fn) {
  3090. function trigger() {
  3091. window.document.removeEventListener('DOMContentLoaded', trigger);
  3092. window.removeEventListener('load', trigger);
  3093. fn();
  3094. }
  3095. // check if document is already loaded
  3096. if (window.document.readyState === 'complete') {
  3097. window.setTimeout(fn);
  3098. } else {
  3099. // We can not use jqLite since we are not done loading and jQuery could be loaded later.
  3100. // Works for modern browsers and IE9
  3101. window.document.addEventListener('DOMContentLoaded', trigger);
  3102. // Fallback to window.onload for others
  3103. window.addEventListener('load', trigger);
  3104. }
  3105. }
  3106. //////////////////////////////////////////
  3107. // Functions which are declared directly.
  3108. //////////////////////////////////////////
  3109. var JQLitePrototype = JQLite.prototype = {
  3110. ready: jqLiteReady,
  3111. toString: function() {
  3112. var value = [];
  3113. forEach(this, function(e) { value.push('' + e);});
  3114. return '[' + value.join(', ') + ']';
  3115. },
  3116. eq: function(index) {
  3117. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  3118. },
  3119. length: 0,
  3120. push: push,
  3121. sort: [].sort,
  3122. splice: [].splice
  3123. };
  3124. //////////////////////////////////////////
  3125. // Functions iterating getter/setters.
  3126. // these functions return self on setter and
  3127. // value on get.
  3128. //////////////////////////////////////////
  3129. var BOOLEAN_ATTR = {};
  3130. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  3131. BOOLEAN_ATTR[lowercase(value)] = value;
  3132. });
  3133. var BOOLEAN_ELEMENTS = {};
  3134. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  3135. BOOLEAN_ELEMENTS[value] = true;
  3136. });
  3137. var ALIASED_ATTR = {
  3138. 'ngMinlength': 'minlength',
  3139. 'ngMaxlength': 'maxlength',
  3140. 'ngMin': 'min',
  3141. 'ngMax': 'max',
  3142. 'ngPattern': 'pattern',
  3143. 'ngStep': 'step'
  3144. };
  3145. function getBooleanAttrName(element, name) {
  3146. // check dom last since we will most likely fail on name
  3147. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  3148. // booleanAttr is here twice to minimize DOM access
  3149. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  3150. }
  3151. function getAliasedAttrName(name) {
  3152. return ALIASED_ATTR[name];
  3153. }
  3154. forEach({
  3155. data: jqLiteData,
  3156. removeData: jqLiteRemoveData,
  3157. hasData: jqLiteHasData,
  3158. cleanData: function jqLiteCleanData(nodes) {
  3159. for (var i = 0, ii = nodes.length; i < ii; i++) {
  3160. jqLiteRemoveData(nodes[i]);
  3161. }
  3162. }
  3163. }, function(fn, name) {
  3164. JQLite[name] = fn;
  3165. });
  3166. forEach({
  3167. data: jqLiteData,
  3168. inheritedData: jqLiteInheritedData,
  3169. scope: function(element) {
  3170. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3171. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  3172. },
  3173. isolateScope: function(element) {
  3174. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3175. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  3176. },
  3177. controller: jqLiteController,
  3178. injector: function(element) {
  3179. return jqLiteInheritedData(element, '$injector');
  3180. },
  3181. removeAttr: function(element, name) {
  3182. element.removeAttribute(name);
  3183. },
  3184. hasClass: jqLiteHasClass,
  3185. css: function(element, name, value) {
  3186. name = cssKebabToCamel(name);
  3187. if (isDefined(value)) {
  3188. element.style[name] = value;
  3189. } else {
  3190. return element.style[name];
  3191. }
  3192. },
  3193. attr: function(element, name, value) {
  3194. var ret;
  3195. var nodeType = element.nodeType;
  3196. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
  3197. !element.getAttribute) {
  3198. return;
  3199. }
  3200. var lowercasedName = lowercase(name);
  3201. var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
  3202. if (isDefined(value)) {
  3203. // setter
  3204. if (value === null || (value === false && isBooleanAttr)) {
  3205. element.removeAttribute(name);
  3206. } else {
  3207. element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
  3208. }
  3209. } else {
  3210. // getter
  3211. ret = element.getAttribute(name);
  3212. if (isBooleanAttr && ret !== null) {
  3213. ret = lowercasedName;
  3214. }
  3215. // Normalize non-existing attributes to undefined (as jQuery).
  3216. return ret === null ? undefined : ret;
  3217. }
  3218. },
  3219. prop: function(element, name, value) {
  3220. if (isDefined(value)) {
  3221. element[name] = value;
  3222. } else {
  3223. return element[name];
  3224. }
  3225. },
  3226. text: (function() {
  3227. getText.$dv = '';
  3228. return getText;
  3229. function getText(element, value) {
  3230. if (isUndefined(value)) {
  3231. var nodeType = element.nodeType;
  3232. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  3233. }
  3234. element.textContent = value;
  3235. }
  3236. })(),
  3237. val: function(element, value) {
  3238. if (isUndefined(value)) {
  3239. if (element.multiple && nodeName_(element) === 'select') {
  3240. var result = [];
  3241. forEach(element.options, function(option) {
  3242. if (option.selected) {
  3243. result.push(option.value || option.text);
  3244. }
  3245. });
  3246. return result;
  3247. }
  3248. return element.value;
  3249. }
  3250. element.value = value;
  3251. },
  3252. html: function(element, value) {
  3253. if (isUndefined(value)) {
  3254. return element.innerHTML;
  3255. }
  3256. jqLiteDealoc(element, true);
  3257. element.innerHTML = value;
  3258. },
  3259. empty: jqLiteEmpty
  3260. }, function(fn, name) {
  3261. /**
  3262. * Properties: writes return selection, reads return first value
  3263. */
  3264. JQLite.prototype[name] = function(arg1, arg2) {
  3265. var i, key;
  3266. var nodeCount = this.length;
  3267. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3268. // in a way that survives minification.
  3269. // jqLiteEmpty takes no arguments but is a setter.
  3270. if (fn !== jqLiteEmpty &&
  3271. (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3272. if (isObject(arg1)) {
  3273. // we are a write, but the object properties are the key/values
  3274. for (i = 0; i < nodeCount; i++) {
  3275. if (fn === jqLiteData) {
  3276. // data() takes the whole object in jQuery
  3277. fn(this[i], arg1);
  3278. } else {
  3279. for (key in arg1) {
  3280. fn(this[i], key, arg1[key]);
  3281. }
  3282. }
  3283. }
  3284. // return self for chaining
  3285. return this;
  3286. } else {
  3287. // we are a read, so read the first child.
  3288. // TODO: do we still need this?
  3289. var value = fn.$dv;
  3290. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3291. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3292. for (var j = 0; j < jj; j++) {
  3293. var nodeValue = fn(this[j], arg1, arg2);
  3294. value = value ? value + nodeValue : nodeValue;
  3295. }
  3296. return value;
  3297. }
  3298. } else {
  3299. // we are a write, so apply to all children
  3300. for (i = 0; i < nodeCount; i++) {
  3301. fn(this[i], arg1, arg2);
  3302. }
  3303. // return self for chaining
  3304. return this;
  3305. }
  3306. };
  3307. });
  3308. function createEventHandler(element, events) {
  3309. var eventHandler = function(event, type) {
  3310. // jQuery specific api
  3311. event.isDefaultPrevented = function() {
  3312. return event.defaultPrevented;
  3313. };
  3314. var eventFns = events[type || event.type];
  3315. var eventFnsLength = eventFns ? eventFns.length : 0;
  3316. if (!eventFnsLength) return;
  3317. if (isUndefined(event.immediatePropagationStopped)) {
  3318. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3319. event.stopImmediatePropagation = function() {
  3320. event.immediatePropagationStopped = true;
  3321. if (event.stopPropagation) {
  3322. event.stopPropagation();
  3323. }
  3324. if (originalStopImmediatePropagation) {
  3325. originalStopImmediatePropagation.call(event);
  3326. }
  3327. };
  3328. }
  3329. event.isImmediatePropagationStopped = function() {
  3330. return event.immediatePropagationStopped === true;
  3331. };
  3332. // Some events have special handlers that wrap the real handler
  3333. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3334. // Copy event handlers in case event handlers array is modified during execution.
  3335. if ((eventFnsLength > 1)) {
  3336. eventFns = shallowCopy(eventFns);
  3337. }
  3338. for (var i = 0; i < eventFnsLength; i++) {
  3339. if (!event.isImmediatePropagationStopped()) {
  3340. handlerWrapper(element, event, eventFns[i]);
  3341. }
  3342. }
  3343. };
  3344. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3345. // events on `element`
  3346. eventHandler.elem = element;
  3347. return eventHandler;
  3348. }
  3349. function defaultHandlerWrapper(element, event, handler) {
  3350. handler.call(element, event);
  3351. }
  3352. function specialMouseHandlerWrapper(target, event, handler) {
  3353. // Refer to jQuery's implementation of mouseenter & mouseleave
  3354. // Read about mouseenter and mouseleave:
  3355. // http://www.quirksmode.org/js/events_mouse.html#link8
  3356. var related = event.relatedTarget;
  3357. // For mousenter/leave call the handler if related is outside the target.
  3358. // NB: No relatedTarget if the mouse left/entered the browser window
  3359. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3360. handler.call(target, event);
  3361. }
  3362. }
  3363. //////////////////////////////////////////
  3364. // Functions iterating traversal.
  3365. // These functions chain results into a single
  3366. // selector.
  3367. //////////////////////////////////////////
  3368. forEach({
  3369. removeData: jqLiteRemoveData,
  3370. on: function jqLiteOn(element, type, fn, unsupported) {
  3371. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3372. // Do not add event handlers to non-elements because they will not be cleaned up.
  3373. if (!jqLiteAcceptsData(element)) {
  3374. return;
  3375. }
  3376. var expandoStore = jqLiteExpandoStore(element, true);
  3377. var events = expandoStore.events;
  3378. var handle = expandoStore.handle;
  3379. if (!handle) {
  3380. handle = expandoStore.handle = createEventHandler(element, events);
  3381. }
  3382. // http://jsperf.com/string-indexof-vs-split
  3383. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3384. var i = types.length;
  3385. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3386. var eventFns = events[type];
  3387. if (!eventFns) {
  3388. eventFns = events[type] = [];
  3389. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3390. if (type !== '$destroy' && !noEventListener) {
  3391. element.addEventListener(type, handle);
  3392. }
  3393. }
  3394. eventFns.push(fn);
  3395. };
  3396. while (i--) {
  3397. type = types[i];
  3398. if (MOUSE_EVENT_MAP[type]) {
  3399. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3400. addHandler(type, undefined, true);
  3401. } else {
  3402. addHandler(type);
  3403. }
  3404. }
  3405. },
  3406. off: jqLiteOff,
  3407. one: function(element, type, fn) {
  3408. element = jqLite(element);
  3409. //add the listener twice so that when it is called
  3410. //you can remove the original function and still be
  3411. //able to call element.off(ev, fn) normally
  3412. element.on(type, function onFn() {
  3413. element.off(type, fn);
  3414. element.off(type, onFn);
  3415. });
  3416. element.on(type, fn);
  3417. },
  3418. replaceWith: function(element, replaceNode) {
  3419. var index, parent = element.parentNode;
  3420. jqLiteDealoc(element);
  3421. forEach(new JQLite(replaceNode), function(node) {
  3422. if (index) {
  3423. parent.insertBefore(node, index.nextSibling);
  3424. } else {
  3425. parent.replaceChild(node, element);
  3426. }
  3427. index = node;
  3428. });
  3429. },
  3430. children: function(element) {
  3431. var children = [];
  3432. forEach(element.childNodes, function(element) {
  3433. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3434. children.push(element);
  3435. }
  3436. });
  3437. return children;
  3438. },
  3439. contents: function(element) {
  3440. return element.contentDocument || element.childNodes || [];
  3441. },
  3442. append: function(element, node) {
  3443. var nodeType = element.nodeType;
  3444. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3445. node = new JQLite(node);
  3446. for (var i = 0, ii = node.length; i < ii; i++) {
  3447. var child = node[i];
  3448. element.appendChild(child);
  3449. }
  3450. },
  3451. prepend: function(element, node) {
  3452. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3453. var index = element.firstChild;
  3454. forEach(new JQLite(node), function(child) {
  3455. element.insertBefore(child, index);
  3456. });
  3457. }
  3458. },
  3459. wrap: function(element, wrapNode) {
  3460. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3461. },
  3462. remove: jqLiteRemove,
  3463. detach: function(element) {
  3464. jqLiteRemove(element, true);
  3465. },
  3466. after: function(element, newElement) {
  3467. var index = element, parent = element.parentNode;
  3468. if (parent) {
  3469. newElement = new JQLite(newElement);
  3470. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3471. var node = newElement[i];
  3472. parent.insertBefore(node, index.nextSibling);
  3473. index = node;
  3474. }
  3475. }
  3476. },
  3477. addClass: jqLiteAddClass,
  3478. removeClass: jqLiteRemoveClass,
  3479. toggleClass: function(element, selector, condition) {
  3480. if (selector) {
  3481. forEach(selector.split(' '), function(className) {
  3482. var classCondition = condition;
  3483. if (isUndefined(classCondition)) {
  3484. classCondition = !jqLiteHasClass(element, className);
  3485. }
  3486. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3487. });
  3488. }
  3489. },
  3490. parent: function(element) {
  3491. var parent = element.parentNode;
  3492. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3493. },
  3494. next: function(element) {
  3495. return element.nextElementSibling;
  3496. },
  3497. find: function(element, selector) {
  3498. if (element.getElementsByTagName) {
  3499. return element.getElementsByTagName(selector);
  3500. } else {
  3501. return [];
  3502. }
  3503. },
  3504. clone: jqLiteClone,
  3505. triggerHandler: function(element, event, extraParameters) {
  3506. var dummyEvent, eventFnsCopy, handlerArgs;
  3507. var eventName = event.type || event;
  3508. var expandoStore = jqLiteExpandoStore(element);
  3509. var events = expandoStore && expandoStore.events;
  3510. var eventFns = events && events[eventName];
  3511. if (eventFns) {
  3512. // Create a dummy event to pass to the handlers
  3513. dummyEvent = {
  3514. preventDefault: function() { this.defaultPrevented = true; },
  3515. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3516. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3517. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3518. stopPropagation: noop,
  3519. type: eventName,
  3520. target: element
  3521. };
  3522. // If a custom event was provided then extend our dummy event with it
  3523. if (event.type) {
  3524. dummyEvent = extend(dummyEvent, event);
  3525. }
  3526. // Copy event handlers in case event handlers array is modified during execution.
  3527. eventFnsCopy = shallowCopy(eventFns);
  3528. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3529. forEach(eventFnsCopy, function(fn) {
  3530. if (!dummyEvent.isImmediatePropagationStopped()) {
  3531. fn.apply(element, handlerArgs);
  3532. }
  3533. });
  3534. }
  3535. }
  3536. }, function(fn, name) {
  3537. /**
  3538. * chaining functions
  3539. */
  3540. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3541. var value;
  3542. for (var i = 0, ii = this.length; i < ii; i++) {
  3543. if (isUndefined(value)) {
  3544. value = fn(this[i], arg1, arg2, arg3);
  3545. if (isDefined(value)) {
  3546. // any function which returns a value needs to be wrapped
  3547. value = jqLite(value);
  3548. }
  3549. } else {
  3550. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3551. }
  3552. }
  3553. return isDefined(value) ? value : this;
  3554. };
  3555. });
  3556. // bind legacy bind/unbind to on/off
  3557. JQLite.prototype.bind = JQLite.prototype.on;
  3558. JQLite.prototype.unbind = JQLite.prototype.off;
  3559. // Provider for private $$jqLite service
  3560. /** @this */
  3561. function $$jqLiteProvider() {
  3562. this.$get = function $$jqLite() {
  3563. return extend(JQLite, {
  3564. hasClass: function(node, classes) {
  3565. if (node.attr) node = node[0];
  3566. return jqLiteHasClass(node, classes);
  3567. },
  3568. addClass: function(node, classes) {
  3569. if (node.attr) node = node[0];
  3570. return jqLiteAddClass(node, classes);
  3571. },
  3572. removeClass: function(node, classes) {
  3573. if (node.attr) node = node[0];
  3574. return jqLiteRemoveClass(node, classes);
  3575. }
  3576. });
  3577. };
  3578. }
  3579. /**
  3580. * Computes a hash of an 'obj'.
  3581. * Hash of a:
  3582. * string is string
  3583. * number is number as string
  3584. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3585. * that is also assigned to the $$hashKey property of the object.
  3586. *
  3587. * @param obj
  3588. * @returns {string} hash string such that the same input will have the same hash string.
  3589. * The resulting string key is in 'type:hashKey' format.
  3590. */
  3591. function hashKey(obj, nextUidFn) {
  3592. var key = obj && obj.$$hashKey;
  3593. if (key) {
  3594. if (typeof key === 'function') {
  3595. key = obj.$$hashKey();
  3596. }
  3597. return key;
  3598. }
  3599. var objType = typeof obj;
  3600. if (objType === 'function' || (objType === 'object' && obj !== null)) {
  3601. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3602. } else {
  3603. key = objType + ':' + obj;
  3604. }
  3605. return key;
  3606. }
  3607. // A minimal ES2015 Map implementation.
  3608. // Should be bug/feature equivalent to the native implementations of supported browsers
  3609. // (for the features required in Angular).
  3610. // See https://kangax.github.io/compat-table/es6/#test-Map
  3611. var nanKey = Object.create(null);
  3612. function NgMapShim() {
  3613. this._keys = [];
  3614. this._values = [];
  3615. this._lastKey = NaN;
  3616. this._lastIndex = -1;
  3617. }
  3618. NgMapShim.prototype = {
  3619. _idx: function(key) {
  3620. if (key === this._lastKey) {
  3621. return this._lastIndex;
  3622. }
  3623. this._lastKey = key;
  3624. this._lastIndex = this._keys.indexOf(key);
  3625. return this._lastIndex;
  3626. },
  3627. _transformKey: function(key) {
  3628. return isNumberNaN(key) ? nanKey : key;
  3629. },
  3630. get: function(key) {
  3631. key = this._transformKey(key);
  3632. var idx = this._idx(key);
  3633. if (idx !== -1) {
  3634. return this._values[idx];
  3635. }
  3636. },
  3637. set: function(key, value) {
  3638. key = this._transformKey(key);
  3639. var idx = this._idx(key);
  3640. if (idx === -1) {
  3641. idx = this._lastIndex = this._keys.length;
  3642. }
  3643. this._keys[idx] = key;
  3644. this._values[idx] = value;
  3645. // Support: IE11
  3646. // Do not `return this` to simulate the partial IE11 implementation
  3647. },
  3648. delete: function(key) {
  3649. key = this._transformKey(key);
  3650. var idx = this._idx(key);
  3651. if (idx === -1) {
  3652. return false;
  3653. }
  3654. this._keys.splice(idx, 1);
  3655. this._values.splice(idx, 1);
  3656. this._lastKey = NaN;
  3657. this._lastIndex = -1;
  3658. return true;
  3659. }
  3660. };
  3661. // For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations
  3662. // are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map`
  3663. // implementations get more stable, we can reconsider switching to `window.Map` (when available).
  3664. var NgMap = NgMapShim;
  3665. var $$MapProvider = [/** @this */function() {
  3666. this.$get = [function() {
  3667. return NgMap;
  3668. }];
  3669. }];
  3670. /**
  3671. * @ngdoc function
  3672. * @module ng
  3673. * @name angular.injector
  3674. * @kind function
  3675. *
  3676. * @description
  3677. * Creates an injector object that can be used for retrieving services as well as for
  3678. * dependency injection (see {@link guide/di dependency injection}).
  3679. *
  3680. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3681. * {@link angular.module}. The `ng` module must be explicitly added.
  3682. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3683. * disallows argument name annotation inference.
  3684. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3685. *
  3686. * @example
  3687. * Typical usage
  3688. * ```js
  3689. * // create an injector
  3690. * var $injector = angular.injector(['ng']);
  3691. *
  3692. * // use the injector to kick off your application
  3693. * // use the type inference to auto inject arguments, or use implicit injection
  3694. * $injector.invoke(function($rootScope, $compile, $document) {
  3695. * $compile($document)($rootScope);
  3696. * $rootScope.$digest();
  3697. * });
  3698. * ```
  3699. *
  3700. * Sometimes you want to get access to the injector of a currently running Angular app
  3701. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3702. * application has been bootstrapped. You can do this using the extra `injector()` added
  3703. * to JQuery/jqLite elements. See {@link angular.element}.
  3704. *
  3705. * *This is fairly rare but could be the case if a third party library is injecting the
  3706. * markup.*
  3707. *
  3708. * In the following example a new block of HTML containing a `ng-controller`
  3709. * directive is added to the end of the document body by JQuery. We then compile and link
  3710. * it into the current AngularJS scope.
  3711. *
  3712. * ```js
  3713. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3714. * $(document.body).append($div);
  3715. *
  3716. * angular.element(document).injector().invoke(function($compile) {
  3717. * var scope = angular.element($div).scope();
  3718. * $compile($div)(scope);
  3719. * });
  3720. * ```
  3721. */
  3722. /**
  3723. * @ngdoc module
  3724. * @name auto
  3725. * @installation
  3726. * @description
  3727. *
  3728. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3729. */
  3730. var ARROW_ARG = /^([^(]+?)=>/;
  3731. var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
  3732. var FN_ARG_SPLIT = /,/;
  3733. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3734. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3735. var $injectorMinErr = minErr('$injector');
  3736. function stringifyFn(fn) {
  3737. return Function.prototype.toString.call(fn);
  3738. }
  3739. function extractArgs(fn) {
  3740. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3741. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3742. return args;
  3743. }
  3744. function anonFn(fn) {
  3745. // For anonymous functions, showing at the very least the function signature can help in
  3746. // debugging.
  3747. var args = extractArgs(fn);
  3748. if (args) {
  3749. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3750. }
  3751. return 'fn';
  3752. }
  3753. function annotate(fn, strictDi, name) {
  3754. var $inject,
  3755. argDecl,
  3756. last;
  3757. if (typeof fn === 'function') {
  3758. if (!($inject = fn.$inject)) {
  3759. $inject = [];
  3760. if (fn.length) {
  3761. if (strictDi) {
  3762. if (!isString(name) || !name) {
  3763. name = fn.name || anonFn(fn);
  3764. }
  3765. throw $injectorMinErr('strictdi',
  3766. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3767. }
  3768. argDecl = extractArgs(fn);
  3769. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3770. arg.replace(FN_ARG, function(all, underscore, name) {
  3771. $inject.push(name);
  3772. });
  3773. });
  3774. }
  3775. fn.$inject = $inject;
  3776. }
  3777. } else if (isArray(fn)) {
  3778. last = fn.length - 1;
  3779. assertArgFn(fn[last], 'fn');
  3780. $inject = fn.slice(0, last);
  3781. } else {
  3782. assertArgFn(fn, 'fn', true);
  3783. }
  3784. return $inject;
  3785. }
  3786. ///////////////////////////////////////
  3787. /**
  3788. * @ngdoc service
  3789. * @name $injector
  3790. *
  3791. * @description
  3792. *
  3793. * `$injector` is used to retrieve object instances as defined by
  3794. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3795. * and load modules.
  3796. *
  3797. * The following always holds true:
  3798. *
  3799. * ```js
  3800. * var $injector = angular.injector();
  3801. * expect($injector.get('$injector')).toBe($injector);
  3802. * expect($injector.invoke(function($injector) {
  3803. * return $injector;
  3804. * })).toBe($injector);
  3805. * ```
  3806. *
  3807. * # Injection Function Annotation
  3808. *
  3809. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3810. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3811. *
  3812. * ```js
  3813. * // inferred (only works if code not minified/obfuscated)
  3814. * $injector.invoke(function(serviceA){});
  3815. *
  3816. * // annotated
  3817. * function explicit(serviceA) {};
  3818. * explicit.$inject = ['serviceA'];
  3819. * $injector.invoke(explicit);
  3820. *
  3821. * // inline
  3822. * $injector.invoke(['serviceA', function(serviceA){}]);
  3823. * ```
  3824. *
  3825. * ## Inference
  3826. *
  3827. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3828. * can then be parsed and the function arguments can be extracted. This method of discovering
  3829. * annotations is disallowed when the injector is in strict mode.
  3830. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3831. * argument names.
  3832. *
  3833. * ## `$inject` Annotation
  3834. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3835. *
  3836. * ## Inline
  3837. * As an array of injection names, where the last item in the array is the function to call.
  3838. */
  3839. /**
  3840. * @ngdoc property
  3841. * @name $injector#modules
  3842. * @type {Object}
  3843. * @description
  3844. * A hash containing all the modules that have been loaded into the
  3845. * $injector.
  3846. *
  3847. * You can use this property to find out information about a module via the
  3848. * {@link angular.Module#info `myModule.info(...)`} method.
  3849. *
  3850. * For example:
  3851. *
  3852. * ```
  3853. * var info = $injector.modules['ngAnimate'].info();
  3854. * ```
  3855. *
  3856. * **Do not use this property to attempt to modify the modules after the application
  3857. * has been bootstrapped.**
  3858. */
  3859. /**
  3860. * @ngdoc method
  3861. * @name $injector#get
  3862. *
  3863. * @description
  3864. * Return an instance of the service.
  3865. *
  3866. * @param {string} name The name of the instance to retrieve.
  3867. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3868. * @return {*} The instance.
  3869. */
  3870. /**
  3871. * @ngdoc method
  3872. * @name $injector#invoke
  3873. *
  3874. * @description
  3875. * Invoke the method and supply the method arguments from the `$injector`.
  3876. *
  3877. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3878. * injected according to the {@link guide/di $inject Annotation} rules.
  3879. * @param {Object=} self The `this` for the invoked method.
  3880. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3881. * object first, before the `$injector` is consulted.
  3882. * @returns {*} the value returned by the invoked `fn` function.
  3883. */
  3884. /**
  3885. * @ngdoc method
  3886. * @name $injector#has
  3887. *
  3888. * @description
  3889. * Allows the user to query if the particular service exists.
  3890. *
  3891. * @param {string} name Name of the service to query.
  3892. * @returns {boolean} `true` if injector has given service.
  3893. */
  3894. /**
  3895. * @ngdoc method
  3896. * @name $injector#instantiate
  3897. * @description
  3898. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3899. * operator, and supplies all of the arguments to the constructor function as specified by the
  3900. * constructor annotation.
  3901. *
  3902. * @param {Function} Type Annotated constructor function.
  3903. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3904. * object first, before the `$injector` is consulted.
  3905. * @returns {Object} new instance of `Type`.
  3906. */
  3907. /**
  3908. * @ngdoc method
  3909. * @name $injector#annotate
  3910. *
  3911. * @description
  3912. * Returns an array of service names which the function is requesting for injection. This API is
  3913. * used by the injector to determine which services need to be injected into the function when the
  3914. * function is invoked. There are three ways in which the function can be annotated with the needed
  3915. * dependencies.
  3916. *
  3917. * # Argument names
  3918. *
  3919. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3920. * by converting the function into a string using `toString()` method and extracting the argument
  3921. * names.
  3922. * ```js
  3923. * // Given
  3924. * function MyController($scope, $route) {
  3925. * // ...
  3926. * }
  3927. *
  3928. * // Then
  3929. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3930. * ```
  3931. *
  3932. * You can disallow this method by using strict injection mode.
  3933. *
  3934. * This method does not work with code minification / obfuscation. For this reason the following
  3935. * annotation strategies are supported.
  3936. *
  3937. * # The `$inject` property
  3938. *
  3939. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3940. * represent names of services to be injected into the function.
  3941. * ```js
  3942. * // Given
  3943. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3944. * // ...
  3945. * }
  3946. * // Define function dependencies
  3947. * MyController['$inject'] = ['$scope', '$route'];
  3948. *
  3949. * // Then
  3950. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3951. * ```
  3952. *
  3953. * # The array notation
  3954. *
  3955. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3956. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3957. * a way that survives minification is a better choice:
  3958. *
  3959. * ```js
  3960. * // We wish to write this (not minification / obfuscation safe)
  3961. * injector.invoke(function($compile, $rootScope) {
  3962. * // ...
  3963. * });
  3964. *
  3965. * // We are forced to write break inlining
  3966. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3967. * // ...
  3968. * };
  3969. * tmpFn.$inject = ['$compile', '$rootScope'];
  3970. * injector.invoke(tmpFn);
  3971. *
  3972. * // To better support inline function the inline annotation is supported
  3973. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3974. * // ...
  3975. * }]);
  3976. *
  3977. * // Therefore
  3978. * expect(injector.annotate(
  3979. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3980. * ).toEqual(['$compile', '$rootScope']);
  3981. * ```
  3982. *
  3983. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3984. * be retrieved as described above.
  3985. *
  3986. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3987. *
  3988. * @returns {Array.<string>} The names of the services which the function requires.
  3989. */
  3990. /**
  3991. * @ngdoc service
  3992. * @name $provide
  3993. *
  3994. * @description
  3995. *
  3996. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3997. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3998. * {@link angular.Module}.
  3999. *
  4000. * An Angular **service** is a singleton object created by a **service factory**. These **service
  4001. * factories** are functions which, in turn, are created by a **service provider**.
  4002. * The **service providers** are constructor functions. When instantiated they must contain a
  4003. * property called `$get`, which holds the **service factory** function.
  4004. *
  4005. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  4006. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  4007. * function to get the instance of the **service**.
  4008. *
  4009. * Often services have no configuration options and there is no need to add methods to the service
  4010. * provider. The provider will be no more than a constructor function with a `$get` property. For
  4011. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  4012. * services without specifying a provider.
  4013. *
  4014. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  4015. * {@link auto.$injector $injector}
  4016. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  4017. * providers and services.
  4018. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  4019. * services, not providers.
  4020. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  4021. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  4022. * given factory function.
  4023. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  4024. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  4025. * a new object using the given constructor function.
  4026. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  4027. * will be able to modify or replace the implementation of another service.
  4028. *
  4029. * See the individual methods for more information and examples.
  4030. */
  4031. /**
  4032. * @ngdoc method
  4033. * @name $provide#provider
  4034. * @description
  4035. *
  4036. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  4037. * are constructor functions, whose instances are responsible for "providing" a factory for a
  4038. * service.
  4039. *
  4040. * Service provider names start with the name of the service they provide followed by `Provider`.
  4041. * For example, the {@link ng.$log $log} service has a provider called
  4042. * {@link ng.$logProvider $logProvider}.
  4043. *
  4044. * Service provider objects can have additional methods which allow configuration of the provider
  4045. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  4046. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  4047. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  4048. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  4049. * console or not.
  4050. *
  4051. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  4052. 'Provider'` key.
  4053. * @param {(Object|function())} provider If the provider is:
  4054. *
  4055. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  4056. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  4057. * - `Constructor`: a new instance of the provider will be created using
  4058. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  4059. *
  4060. * @returns {Object} registered provider instance
  4061. * @example
  4062. *
  4063. * The following example shows how to create a simple event tracking service and register it using
  4064. * {@link auto.$provide#provider $provide.provider()}.
  4065. *
  4066. * ```js
  4067. * // Define the eventTracker provider
  4068. * function EventTrackerProvider() {
  4069. * var trackingUrl = '/track';
  4070. *
  4071. * // A provider method for configuring where the tracked events should been saved
  4072. * this.setTrackingUrl = function(url) {
  4073. * trackingUrl = url;
  4074. * };
  4075. *
  4076. * // The service factory function
  4077. * this.$get = ['$http', function($http) {
  4078. * var trackedEvents = {};
  4079. * return {
  4080. * // Call this to track an event
  4081. * event: function(event) {
  4082. * var count = trackedEvents[event] || 0;
  4083. * count += 1;
  4084. * trackedEvents[event] = count;
  4085. * return count;
  4086. * },
  4087. * // Call this to save the tracked events to the trackingUrl
  4088. * save: function() {
  4089. * $http.post(trackingUrl, trackedEvents);
  4090. * }
  4091. * };
  4092. * }];
  4093. * }
  4094. *
  4095. * describe('eventTracker', function() {
  4096. * var postSpy;
  4097. *
  4098. * beforeEach(module(function($provide) {
  4099. * // Register the eventTracker provider
  4100. * $provide.provider('eventTracker', EventTrackerProvider);
  4101. * }));
  4102. *
  4103. * beforeEach(module(function(eventTrackerProvider) {
  4104. * // Configure eventTracker provider
  4105. * eventTrackerProvider.setTrackingUrl('/custom-track');
  4106. * }));
  4107. *
  4108. * it('tracks events', inject(function(eventTracker) {
  4109. * expect(eventTracker.event('login')).toEqual(1);
  4110. * expect(eventTracker.event('login')).toEqual(2);
  4111. * }));
  4112. *
  4113. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  4114. * postSpy = spyOn($http, 'post');
  4115. * eventTracker.event('login');
  4116. * eventTracker.save();
  4117. * expect(postSpy).toHaveBeenCalled();
  4118. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  4119. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  4120. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  4121. * }));
  4122. * });
  4123. * ```
  4124. */
  4125. /**
  4126. * @ngdoc method
  4127. * @name $provide#factory
  4128. * @description
  4129. *
  4130. * Register a **service factory**, which will be called to return the service instance.
  4131. * This is short for registering a service where its provider consists of only a `$get` property,
  4132. * which is the given service factory function.
  4133. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  4134. * configure your service in a provider.
  4135. *
  4136. * @param {string} name The name of the instance.
  4137. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  4138. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  4139. * @returns {Object} registered provider instance
  4140. *
  4141. * @example
  4142. * Here is an example of registering a service
  4143. * ```js
  4144. * $provide.factory('ping', ['$http', function($http) {
  4145. * return function ping() {
  4146. * return $http.send('/ping');
  4147. * };
  4148. * }]);
  4149. * ```
  4150. * You would then inject and use this service like this:
  4151. * ```js
  4152. * someModule.controller('Ctrl', ['ping', function(ping) {
  4153. * ping();
  4154. * }]);
  4155. * ```
  4156. */
  4157. /**
  4158. * @ngdoc method
  4159. * @name $provide#service
  4160. * @description
  4161. *
  4162. * Register a **service constructor**, which will be invoked with `new` to create the service
  4163. * instance.
  4164. * This is short for registering a service where its provider's `$get` property is a factory
  4165. * function that returns an instance instantiated by the injector from the service constructor
  4166. * function.
  4167. *
  4168. * Internally it looks a bit like this:
  4169. *
  4170. * ```
  4171. * {
  4172. * $get: function() {
  4173. * return $injector.instantiate(constructor);
  4174. * }
  4175. * }
  4176. * ```
  4177. *
  4178. *
  4179. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  4180. * as a type/class.
  4181. *
  4182. * @param {string} name The name of the instance.
  4183. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  4184. * that will be instantiated.
  4185. * @returns {Object} registered provider instance
  4186. *
  4187. * @example
  4188. * Here is an example of registering a service using
  4189. * {@link auto.$provide#service $provide.service(class)}.
  4190. * ```js
  4191. * var Ping = function($http) {
  4192. * this.$http = $http;
  4193. * };
  4194. *
  4195. * Ping.$inject = ['$http'];
  4196. *
  4197. * Ping.prototype.send = function() {
  4198. * return this.$http.get('/ping');
  4199. * };
  4200. * $provide.service('ping', Ping);
  4201. * ```
  4202. * You would then inject and use this service like this:
  4203. * ```js
  4204. * someModule.controller('Ctrl', ['ping', function(ping) {
  4205. * ping.send();
  4206. * }]);
  4207. * ```
  4208. */
  4209. /**
  4210. * @ngdoc method
  4211. * @name $provide#value
  4212. * @description
  4213. *
  4214. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  4215. * number, an array, an object or a function. This is short for registering a service where its
  4216. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  4217. * service**. That also means it is not possible to inject other services into a value service.
  4218. *
  4219. * Value services are similar to constant services, except that they cannot be injected into a
  4220. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  4221. * an Angular {@link auto.$provide#decorator decorator}.
  4222. *
  4223. * @param {string} name The name of the instance.
  4224. * @param {*} value The value.
  4225. * @returns {Object} registered provider instance
  4226. *
  4227. * @example
  4228. * Here are some examples of creating value services.
  4229. * ```js
  4230. * $provide.value('ADMIN_USER', 'admin');
  4231. *
  4232. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  4233. *
  4234. * $provide.value('halfOf', function(value) {
  4235. * return value / 2;
  4236. * });
  4237. * ```
  4238. */
  4239. /**
  4240. * @ngdoc method
  4241. * @name $provide#constant
  4242. * @description
  4243. *
  4244. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  4245. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  4246. * possible to inject other services into a constant.
  4247. *
  4248. * But unlike {@link auto.$provide#value value}, a constant can be
  4249. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  4250. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  4251. *
  4252. * @param {string} name The name of the constant.
  4253. * @param {*} value The constant value.
  4254. * @returns {Object} registered instance
  4255. *
  4256. * @example
  4257. * Here a some examples of creating constants:
  4258. * ```js
  4259. * $provide.constant('SHARD_HEIGHT', 306);
  4260. *
  4261. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  4262. *
  4263. * $provide.constant('double', function(value) {
  4264. * return value * 2;
  4265. * });
  4266. * ```
  4267. */
  4268. /**
  4269. * @ngdoc method
  4270. * @name $provide#decorator
  4271. * @description
  4272. *
  4273. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  4274. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  4275. * service. The return value of the decorator function may be the original service, or a new service
  4276. * that replaces (or wraps and delegates to) the original service.
  4277. *
  4278. * You can find out more about using decorators in the {@link guide/decorators} guide.
  4279. *
  4280. * @param {string} name The name of the service to decorate.
  4281. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  4282. * provided and should return the decorated service instance. The function is called using
  4283. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  4284. * Local injection arguments:
  4285. *
  4286. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  4287. * decorated or delegated to.
  4288. *
  4289. * @example
  4290. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  4291. * calls to {@link ng.$log#error $log.warn()}.
  4292. * ```js
  4293. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4294. * $delegate.warn = $delegate.error;
  4295. * return $delegate;
  4296. * }]);
  4297. * ```
  4298. */
  4299. function createInjector(modulesToLoad, strictDi) {
  4300. strictDi = (strictDi === true);
  4301. var INSTANTIATING = {},
  4302. providerSuffix = 'Provider',
  4303. path = [],
  4304. loadedModules = new NgMap(),
  4305. providerCache = {
  4306. $provide: {
  4307. provider: supportObject(provider),
  4308. factory: supportObject(factory),
  4309. service: supportObject(service),
  4310. value: supportObject(value),
  4311. constant: supportObject(constant),
  4312. decorator: decorator
  4313. }
  4314. },
  4315. providerInjector = (providerCache.$injector =
  4316. createInternalInjector(providerCache, function(serviceName, caller) {
  4317. if (angular.isString(caller)) {
  4318. path.push(caller);
  4319. }
  4320. throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
  4321. })),
  4322. instanceCache = {},
  4323. protoInstanceInjector =
  4324. createInternalInjector(instanceCache, function(serviceName, caller) {
  4325. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4326. return instanceInjector.invoke(
  4327. provider.$get, provider, undefined, serviceName);
  4328. }),
  4329. instanceInjector = protoInstanceInjector;
  4330. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4331. instanceInjector.modules = providerInjector.modules = createMap();
  4332. var runBlocks = loadModules(modulesToLoad);
  4333. instanceInjector = protoInstanceInjector.get('$injector');
  4334. instanceInjector.strictDi = strictDi;
  4335. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4336. return instanceInjector;
  4337. ////////////////////////////////////
  4338. // $provider
  4339. ////////////////////////////////////
  4340. function supportObject(delegate) {
  4341. return function(key, value) {
  4342. if (isObject(key)) {
  4343. forEach(key, reverseParams(delegate));
  4344. } else {
  4345. return delegate(key, value);
  4346. }
  4347. };
  4348. }
  4349. function provider(name, provider_) {
  4350. assertNotHasOwnProperty(name, 'service');
  4351. if (isFunction(provider_) || isArray(provider_)) {
  4352. provider_ = providerInjector.instantiate(provider_);
  4353. }
  4354. if (!provider_.$get) {
  4355. throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
  4356. }
  4357. return (providerCache[name + providerSuffix] = provider_);
  4358. }
  4359. function enforceReturnValue(name, factory) {
  4360. return /** @this */ function enforcedReturnValue() {
  4361. var result = instanceInjector.invoke(factory, this);
  4362. if (isUndefined(result)) {
  4363. throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
  4364. }
  4365. return result;
  4366. };
  4367. }
  4368. function factory(name, factoryFn, enforce) {
  4369. return provider(name, {
  4370. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4371. });
  4372. }
  4373. function service(name, constructor) {
  4374. return factory(name, ['$injector', function($injector) {
  4375. return $injector.instantiate(constructor);
  4376. }]);
  4377. }
  4378. function value(name, val) { return factory(name, valueFn(val), false); }
  4379. function constant(name, value) {
  4380. assertNotHasOwnProperty(name, 'constant');
  4381. providerCache[name] = value;
  4382. instanceCache[name] = value;
  4383. }
  4384. function decorator(serviceName, decorFn) {
  4385. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4386. orig$get = origProvider.$get;
  4387. origProvider.$get = function() {
  4388. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4389. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4390. };
  4391. }
  4392. ////////////////////////////////////
  4393. // Module Loading
  4394. ////////////////////////////////////
  4395. function loadModules(modulesToLoad) {
  4396. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4397. var runBlocks = [], moduleFn;
  4398. forEach(modulesToLoad, function(module) {
  4399. if (loadedModules.get(module)) return;
  4400. loadedModules.set(module, true);
  4401. function runInvokeQueue(queue) {
  4402. var i, ii;
  4403. for (i = 0, ii = queue.length; i < ii; i++) {
  4404. var invokeArgs = queue[i],
  4405. provider = providerInjector.get(invokeArgs[0]);
  4406. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4407. }
  4408. }
  4409. try {
  4410. if (isString(module)) {
  4411. moduleFn = angularModule(module);
  4412. instanceInjector.modules[module] = moduleFn;
  4413. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4414. runInvokeQueue(moduleFn._invokeQueue);
  4415. runInvokeQueue(moduleFn._configBlocks);
  4416. } else if (isFunction(module)) {
  4417. runBlocks.push(providerInjector.invoke(module));
  4418. } else if (isArray(module)) {
  4419. runBlocks.push(providerInjector.invoke(module));
  4420. } else {
  4421. assertArgFn(module, 'module');
  4422. }
  4423. } catch (e) {
  4424. if (isArray(module)) {
  4425. module = module[module.length - 1];
  4426. }
  4427. if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
  4428. // Safari & FF's stack traces don't contain error.message content
  4429. // unlike those of Chrome and IE
  4430. // So if stack doesn't contain message, we create a new string that contains both.
  4431. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4432. // eslint-disable-next-line no-ex-assign
  4433. e = e.message + '\n' + e.stack;
  4434. }
  4435. throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
  4436. module, e.stack || e.message || e);
  4437. }
  4438. });
  4439. return runBlocks;
  4440. }
  4441. ////////////////////////////////////
  4442. // internal Injector
  4443. ////////////////////////////////////
  4444. function createInternalInjector(cache, factory) {
  4445. function getService(serviceName, caller) {
  4446. if (cache.hasOwnProperty(serviceName)) {
  4447. if (cache[serviceName] === INSTANTIATING) {
  4448. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4449. serviceName + ' <- ' + path.join(' <- '));
  4450. }
  4451. return cache[serviceName];
  4452. } else {
  4453. try {
  4454. path.unshift(serviceName);
  4455. cache[serviceName] = INSTANTIATING;
  4456. cache[serviceName] = factory(serviceName, caller);
  4457. return cache[serviceName];
  4458. } catch (err) {
  4459. if (cache[serviceName] === INSTANTIATING) {
  4460. delete cache[serviceName];
  4461. }
  4462. throw err;
  4463. } finally {
  4464. path.shift();
  4465. }
  4466. }
  4467. }
  4468. function injectionArgs(fn, locals, serviceName) {
  4469. var args = [],
  4470. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4471. for (var i = 0, length = $inject.length; i < length; i++) {
  4472. var key = $inject[i];
  4473. if (typeof key !== 'string') {
  4474. throw $injectorMinErr('itkn',
  4475. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4476. }
  4477. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4478. getService(key, serviceName));
  4479. }
  4480. return args;
  4481. }
  4482. function isClass(func) {
  4483. // Support: IE 9-11 only
  4484. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4485. if (msie || typeof func !== 'function') {
  4486. return false;
  4487. }
  4488. var result = func.$$ngIsClass;
  4489. if (!isBoolean(result)) {
  4490. // Support: Edge 12-13 only
  4491. // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
  4492. result = func.$$ngIsClass = /^(?:class\b|constructor\()/.test(stringifyFn(func));
  4493. }
  4494. return result;
  4495. }
  4496. function invoke(fn, self, locals, serviceName) {
  4497. if (typeof locals === 'string') {
  4498. serviceName = locals;
  4499. locals = null;
  4500. }
  4501. var args = injectionArgs(fn, locals, serviceName);
  4502. if (isArray(fn)) {
  4503. fn = fn[fn.length - 1];
  4504. }
  4505. if (!isClass(fn)) {
  4506. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4507. // #5388
  4508. return fn.apply(self, args);
  4509. } else {
  4510. args.unshift(null);
  4511. return new (Function.prototype.bind.apply(fn, args))();
  4512. }
  4513. }
  4514. function instantiate(Type, locals, serviceName) {
  4515. // Check if Type is annotated and use just the given function at n-1 as parameter
  4516. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4517. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4518. var args = injectionArgs(Type, locals, serviceName);
  4519. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4520. args.unshift(null);
  4521. return new (Function.prototype.bind.apply(ctor, args))();
  4522. }
  4523. return {
  4524. invoke: invoke,
  4525. instantiate: instantiate,
  4526. get: getService,
  4527. annotate: createInjector.$$annotate,
  4528. has: function(name) {
  4529. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4530. }
  4531. };
  4532. }
  4533. }
  4534. createInjector.$$annotate = annotate;
  4535. /**
  4536. * @ngdoc provider
  4537. * @name $anchorScrollProvider
  4538. * @this
  4539. *
  4540. * @description
  4541. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4542. * {@link ng.$location#hash $location.hash()} changes.
  4543. */
  4544. function $AnchorScrollProvider() {
  4545. var autoScrollingEnabled = true;
  4546. /**
  4547. * @ngdoc method
  4548. * @name $anchorScrollProvider#disableAutoScrolling
  4549. *
  4550. * @description
  4551. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4552. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4553. * Use this method to disable automatic scrolling.
  4554. *
  4555. * If automatic scrolling is disabled, one must explicitly call
  4556. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4557. * current hash.
  4558. */
  4559. this.disableAutoScrolling = function() {
  4560. autoScrollingEnabled = false;
  4561. };
  4562. /**
  4563. * @ngdoc service
  4564. * @name $anchorScroll
  4565. * @kind function
  4566. * @requires $window
  4567. * @requires $location
  4568. * @requires $rootScope
  4569. *
  4570. * @description
  4571. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4572. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4573. * in the
  4574. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4575. *
  4576. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4577. * match any anchor whenever it changes. This can be disabled by calling
  4578. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4579. *
  4580. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4581. * vertical scroll-offset (either fixed or dynamic).
  4582. *
  4583. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4584. * {@link ng.$location#hash $location.hash()} will be used.
  4585. *
  4586. * @property {(number|function|jqLite)} yOffset
  4587. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4588. * positioned elements at the top of the page, such as navbars, headers etc.
  4589. *
  4590. * `yOffset` can be specified in various ways:
  4591. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4592. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4593. * a number representing the offset (in pixels).<br /><br />
  4594. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4595. * the top of the page to the element's bottom will be used as offset.<br />
  4596. * **Note**: The element will be taken into account only as long as its `position` is set to
  4597. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4598. * their height and/or positioning according to the viewport's size.
  4599. *
  4600. * <br />
  4601. * <div class="alert alert-warning">
  4602. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4603. * not some child element.
  4604. * </div>
  4605. *
  4606. * @example
  4607. <example module="anchorScrollExample" name="anchor-scroll">
  4608. <file name="index.html">
  4609. <div id="scrollArea" ng-controller="ScrollController">
  4610. <a ng-click="gotoBottom()">Go to bottom</a>
  4611. <a id="bottom"></a> You're at the bottom!
  4612. </div>
  4613. </file>
  4614. <file name="script.js">
  4615. angular.module('anchorScrollExample', [])
  4616. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4617. function($scope, $location, $anchorScroll) {
  4618. $scope.gotoBottom = function() {
  4619. // set the location.hash to the id of
  4620. // the element you wish to scroll to.
  4621. $location.hash('bottom');
  4622. // call $anchorScroll()
  4623. $anchorScroll();
  4624. };
  4625. }]);
  4626. </file>
  4627. <file name="style.css">
  4628. #scrollArea {
  4629. height: 280px;
  4630. overflow: auto;
  4631. }
  4632. #bottom {
  4633. display: block;
  4634. margin-top: 2000px;
  4635. }
  4636. </file>
  4637. </example>
  4638. *
  4639. * <hr />
  4640. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4641. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4642. *
  4643. * @example
  4644. <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
  4645. <file name="index.html">
  4646. <div class="fixed-header" ng-controller="headerCtrl">
  4647. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4648. Go to anchor {{x}}
  4649. </a>
  4650. </div>
  4651. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4652. Anchor {{x}} of 5
  4653. </div>
  4654. </file>
  4655. <file name="script.js">
  4656. angular.module('anchorScrollOffsetExample', [])
  4657. .run(['$anchorScroll', function($anchorScroll) {
  4658. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4659. }])
  4660. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4661. function($anchorScroll, $location, $scope) {
  4662. $scope.gotoAnchor = function(x) {
  4663. var newHash = 'anchor' + x;
  4664. if ($location.hash() !== newHash) {
  4665. // set the $location.hash to `newHash` and
  4666. // $anchorScroll will automatically scroll to it
  4667. $location.hash('anchor' + x);
  4668. } else {
  4669. // call $anchorScroll() explicitly,
  4670. // since $location.hash hasn't changed
  4671. $anchorScroll();
  4672. }
  4673. };
  4674. }
  4675. ]);
  4676. </file>
  4677. <file name="style.css">
  4678. body {
  4679. padding-top: 50px;
  4680. }
  4681. .anchor {
  4682. border: 2px dashed DarkOrchid;
  4683. padding: 10px 10px 200px 10px;
  4684. }
  4685. .fixed-header {
  4686. background-color: rgba(0, 0, 0, 0.2);
  4687. height: 50px;
  4688. position: fixed;
  4689. top: 0; left: 0; right: 0;
  4690. }
  4691. .fixed-header > a {
  4692. display: inline-block;
  4693. margin: 5px 15px;
  4694. }
  4695. </file>
  4696. </example>
  4697. */
  4698. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4699. var document = $window.document;
  4700. // Helper function to get first anchor from a NodeList
  4701. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4702. // and working in all supported browsers.)
  4703. function getFirstAnchor(list) {
  4704. var result = null;
  4705. Array.prototype.some.call(list, function(element) {
  4706. if (nodeName_(element) === 'a') {
  4707. result = element;
  4708. return true;
  4709. }
  4710. });
  4711. return result;
  4712. }
  4713. function getYOffset() {
  4714. var offset = scroll.yOffset;
  4715. if (isFunction(offset)) {
  4716. offset = offset();
  4717. } else if (isElement(offset)) {
  4718. var elem = offset[0];
  4719. var style = $window.getComputedStyle(elem);
  4720. if (style.position !== 'fixed') {
  4721. offset = 0;
  4722. } else {
  4723. offset = elem.getBoundingClientRect().bottom;
  4724. }
  4725. } else if (!isNumber(offset)) {
  4726. offset = 0;
  4727. }
  4728. return offset;
  4729. }
  4730. function scrollTo(elem) {
  4731. if (elem) {
  4732. elem.scrollIntoView();
  4733. var offset = getYOffset();
  4734. if (offset) {
  4735. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4736. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4737. // top of the viewport.
  4738. //
  4739. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4740. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4741. // way down the page.
  4742. //
  4743. // This is often the case for elements near the bottom of the page.
  4744. //
  4745. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4746. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4747. // desired position.
  4748. var elemTop = elem.getBoundingClientRect().top;
  4749. $window.scrollBy(0, elemTop - offset);
  4750. }
  4751. } else {
  4752. $window.scrollTo(0, 0);
  4753. }
  4754. }
  4755. function scroll(hash) {
  4756. // Allow numeric hashes
  4757. hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
  4758. var elm;
  4759. // empty hash, scroll to the top of the page
  4760. if (!hash) scrollTo(null);
  4761. // element with given id
  4762. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4763. // first anchor with given name :-D
  4764. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4765. // no element and hash === 'top', scroll to the top of the page
  4766. else if (hash === 'top') scrollTo(null);
  4767. }
  4768. // does not scroll when user clicks on anchor link that is currently on
  4769. // (no url change, no $location.hash() change), browser native does scroll
  4770. if (autoScrollingEnabled) {
  4771. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4772. function autoScrollWatchAction(newVal, oldVal) {
  4773. // skip the initial scroll if $location.hash is empty
  4774. if (newVal === oldVal && newVal === '') return;
  4775. jqLiteDocumentLoaded(function() {
  4776. $rootScope.$evalAsync(scroll);
  4777. });
  4778. });
  4779. }
  4780. return scroll;
  4781. }];
  4782. }
  4783. var $animateMinErr = minErr('$animate');
  4784. var ELEMENT_NODE = 1;
  4785. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4786. function mergeClasses(a,b) {
  4787. if (!a && !b) return '';
  4788. if (!a) return b;
  4789. if (!b) return a;
  4790. if (isArray(a)) a = a.join(' ');
  4791. if (isArray(b)) b = b.join(' ');
  4792. return a + ' ' + b;
  4793. }
  4794. function extractElementNode(element) {
  4795. for (var i = 0; i < element.length; i++) {
  4796. var elm = element[i];
  4797. if (elm.nodeType === ELEMENT_NODE) {
  4798. return elm;
  4799. }
  4800. }
  4801. }
  4802. function splitClasses(classes) {
  4803. if (isString(classes)) {
  4804. classes = classes.split(' ');
  4805. }
  4806. // Use createMap() to prevent class assumptions involving property names in
  4807. // Object.prototype
  4808. var obj = createMap();
  4809. forEach(classes, function(klass) {
  4810. // sometimes the split leaves empty string values
  4811. // incase extra spaces were applied to the options
  4812. if (klass.length) {
  4813. obj[klass] = true;
  4814. }
  4815. });
  4816. return obj;
  4817. }
  4818. // if any other type of options value besides an Object value is
  4819. // passed into the $animate.method() animation then this helper code
  4820. // will be run which will ignore it. While this patch is not the
  4821. // greatest solution to this, a lot of existing plugins depend on
  4822. // $animate to either call the callback (< 1.2) or return a promise
  4823. // that can be changed. This helper function ensures that the options
  4824. // are wiped clean incase a callback function is provided.
  4825. function prepareAnimateOptions(options) {
  4826. return isObject(options)
  4827. ? options
  4828. : {};
  4829. }
  4830. var $$CoreAnimateJsProvider = /** @this */ function() {
  4831. this.$get = noop;
  4832. };
  4833. // this is prefixed with Core since it conflicts with
  4834. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4835. var $$CoreAnimateQueueProvider = /** @this */ function() {
  4836. var postDigestQueue = new NgMap();
  4837. var postDigestElements = [];
  4838. this.$get = ['$$AnimateRunner', '$rootScope',
  4839. function($$AnimateRunner, $rootScope) {
  4840. return {
  4841. enabled: noop,
  4842. on: noop,
  4843. off: noop,
  4844. pin: noop,
  4845. push: function(element, event, options, domOperation) {
  4846. if (domOperation) {
  4847. domOperation();
  4848. }
  4849. options = options || {};
  4850. if (options.from) {
  4851. element.css(options.from);
  4852. }
  4853. if (options.to) {
  4854. element.css(options.to);
  4855. }
  4856. if (options.addClass || options.removeClass) {
  4857. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4858. }
  4859. var runner = new $$AnimateRunner();
  4860. // since there are no animations to run the runner needs to be
  4861. // notified that the animation call is complete.
  4862. runner.complete();
  4863. return runner;
  4864. }
  4865. };
  4866. function updateData(data, classes, value) {
  4867. var changed = false;
  4868. if (classes) {
  4869. classes = isString(classes) ? classes.split(' ') :
  4870. isArray(classes) ? classes : [];
  4871. forEach(classes, function(className) {
  4872. if (className) {
  4873. changed = true;
  4874. data[className] = value;
  4875. }
  4876. });
  4877. }
  4878. return changed;
  4879. }
  4880. function handleCSSClassChanges() {
  4881. forEach(postDigestElements, function(element) {
  4882. var data = postDigestQueue.get(element);
  4883. if (data) {
  4884. var existing = splitClasses(element.attr('class'));
  4885. var toAdd = '';
  4886. var toRemove = '';
  4887. forEach(data, function(status, className) {
  4888. var hasClass = !!existing[className];
  4889. if (status !== hasClass) {
  4890. if (status) {
  4891. toAdd += (toAdd.length ? ' ' : '') + className;
  4892. } else {
  4893. toRemove += (toRemove.length ? ' ' : '') + className;
  4894. }
  4895. }
  4896. });
  4897. forEach(element, function(elm) {
  4898. if (toAdd) {
  4899. jqLiteAddClass(elm, toAdd);
  4900. }
  4901. if (toRemove) {
  4902. jqLiteRemoveClass(elm, toRemove);
  4903. }
  4904. });
  4905. postDigestQueue.delete(element);
  4906. }
  4907. });
  4908. postDigestElements.length = 0;
  4909. }
  4910. function addRemoveClassesPostDigest(element, add, remove) {
  4911. var data = postDigestQueue.get(element) || {};
  4912. var classesAdded = updateData(data, add, true);
  4913. var classesRemoved = updateData(data, remove, false);
  4914. if (classesAdded || classesRemoved) {
  4915. postDigestQueue.set(element, data);
  4916. postDigestElements.push(element);
  4917. if (postDigestElements.length === 1) {
  4918. $rootScope.$$postDigest(handleCSSClassChanges);
  4919. }
  4920. }
  4921. }
  4922. }];
  4923. };
  4924. /**
  4925. * @ngdoc provider
  4926. * @name $animateProvider
  4927. *
  4928. * @description
  4929. * Default implementation of $animate that doesn't perform any animations, instead just
  4930. * synchronously performs DOM updates and resolves the returned runner promise.
  4931. *
  4932. * In order to enable animations the `ngAnimate` module has to be loaded.
  4933. *
  4934. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4935. */
  4936. var $AnimateProvider = ['$provide', /** @this */ function($provide) {
  4937. var provider = this;
  4938. var classNameFilter = null;
  4939. var customFilter = null;
  4940. this.$$registeredAnimations = Object.create(null);
  4941. /**
  4942. * @ngdoc method
  4943. * @name $animateProvider#register
  4944. *
  4945. * @description
  4946. * Registers a new injectable animation factory function. The factory function produces the
  4947. * animation object which contains callback functions for each event that is expected to be
  4948. * animated.
  4949. *
  4950. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4951. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4952. * on the type of animation additional arguments will be injected into the animation function. The
  4953. * list below explains the function signatures for the different animation methods:
  4954. *
  4955. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4956. * - addClass: function(element, addedClasses, doneFunction, options)
  4957. * - removeClass: function(element, removedClasses, doneFunction, options)
  4958. * - enter, leave, move: function(element, doneFunction, options)
  4959. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4960. *
  4961. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4962. *
  4963. * ```js
  4964. * return {
  4965. * //enter, leave, move signature
  4966. * eventFn : function(element, done, options) {
  4967. * //code to run the animation
  4968. * //once complete, then run done()
  4969. * return function endFunction(wasCancelled) {
  4970. * //code to cancel the animation
  4971. * }
  4972. * }
  4973. * }
  4974. * ```
  4975. *
  4976. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4977. * @param {Function} factory The factory function that will be executed to return the animation
  4978. * object.
  4979. */
  4980. this.register = function(name, factory) {
  4981. if (name && name.charAt(0) !== '.') {
  4982. throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
  4983. }
  4984. var key = name + '-animation';
  4985. provider.$$registeredAnimations[name.substr(1)] = key;
  4986. $provide.factory(key, factory);
  4987. };
  4988. /**
  4989. * @ngdoc method
  4990. * @name $animateProvider#customFilter
  4991. *
  4992. * @description
  4993. * Sets and/or returns the custom filter function that is used to "filter" animations, i.e.
  4994. * determine if an animation is allowed or not. When no filter is specified (the default), no
  4995. * animation will be blocked. Setting the `customFilter` value will only allow animations for
  4996. * which the filter function's return value is truthy.
  4997. *
  4998. * This allows to easily create arbitrarily complex rules for filtering animations, such as
  4999. * allowing specific events only, or enabling animations on specific subtrees of the DOM, etc.
  5000. * Filtering animations can also boost performance for low-powered devices, as well as
  5001. * applications containing a lot of structural operations.
  5002. *
  5003. * <div class="alert alert-success">
  5004. * **Best Practice:**
  5005. * Keep the filtering function as lean as possible, because it will be called for each DOM
  5006. * action (e.g. insertion, removal, class change) performed by "animation-aware" directives.
  5007. * See {@link guide/animations#which-directives-support-animations- here} for a list of built-in
  5008. * directives that support animations.
  5009. * Performing computationally expensive or time-consuming operations on each call of the
  5010. * filtering function can make your animations sluggish.
  5011. * </div>
  5012. *
  5013. * **Note:** If present, `customFilter` will be checked before
  5014. * {@link $animateProvider#classNameFilter classNameFilter}.
  5015. *
  5016. * @param {Function=} filterFn - The filter function which will be used to filter all animations.
  5017. * If a falsy value is returned, no animation will be performed. The function will be called
  5018. * with the following arguments:
  5019. * - **node** `{DOMElement}` - The DOM element to be animated.
  5020. * - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass`
  5021. * etc).
  5022. * - **options** `{Object}` - A collection of options/styles used for the animation.
  5023. * @return {Function} The current filter function or `null` if there is none set.
  5024. */
  5025. this.customFilter = function(filterFn) {
  5026. if (arguments.length === 1) {
  5027. customFilter = isFunction(filterFn) ? filterFn : null;
  5028. }
  5029. return customFilter;
  5030. };
  5031. /**
  5032. * @ngdoc method
  5033. * @name $animateProvider#classNameFilter
  5034. *
  5035. * @description
  5036. * Sets and/or returns the CSS class regular expression that is checked when performing
  5037. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  5038. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  5039. * When setting the `classNameFilter` value, animations will only be performed on elements
  5040. * that successfully match the filter expression. This in turn can boost performance
  5041. * for low-powered devices as well as applications containing a lot of structural operations.
  5042. *
  5043. * **Note:** If present, `classNameFilter` will be checked after
  5044. * {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns
  5045. * false, `classNameFilter` will not be checked.
  5046. *
  5047. * @param {RegExp=} expression The className expression which will be checked against all animations
  5048. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  5049. */
  5050. this.classNameFilter = function(expression) {
  5051. if (arguments.length === 1) {
  5052. classNameFilter = (expression instanceof RegExp) ? expression : null;
  5053. if (classNameFilter) {
  5054. var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]');
  5055. if (reservedRegex.test(classNameFilter.toString())) {
  5056. classNameFilter = null;
  5057. throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  5058. }
  5059. }
  5060. }
  5061. return classNameFilter;
  5062. };
  5063. this.$get = ['$$animateQueue', function($$animateQueue) {
  5064. function domInsert(element, parentElement, afterElement) {
  5065. // if for some reason the previous element was removed
  5066. // from the dom sometime before this code runs then let's
  5067. // just stick to using the parent element as the anchor
  5068. if (afterElement) {
  5069. var afterNode = extractElementNode(afterElement);
  5070. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  5071. afterElement = null;
  5072. }
  5073. }
  5074. if (afterElement) {
  5075. afterElement.after(element);
  5076. } else {
  5077. parentElement.prepend(element);
  5078. }
  5079. }
  5080. /**
  5081. * @ngdoc service
  5082. * @name $animate
  5083. * @description The $animate service exposes a series of DOM utility methods that provide support
  5084. * for animation hooks. The default behavior is the application of DOM operations, however,
  5085. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  5086. * to ensure that animation runs with the triggered DOM operation.
  5087. *
  5088. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  5089. * included and only when it is active then the animation hooks that `$animate` triggers will be
  5090. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  5091. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  5092. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  5093. *
  5094. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  5095. *
  5096. * To learn more about enabling animation support, click here to visit the
  5097. * {@link ngAnimate ngAnimate module page}.
  5098. */
  5099. return {
  5100. // we don't call it directly since non-existant arguments may
  5101. // be interpreted as null within the sub enabled function
  5102. /**
  5103. *
  5104. * @ngdoc method
  5105. * @name $animate#on
  5106. * @kind function
  5107. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  5108. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  5109. * is fired with the following params:
  5110. *
  5111. * ```js
  5112. * $animate.on('enter', container,
  5113. * function callback(element, phase) {
  5114. * // cool we detected an enter animation within the container
  5115. * }
  5116. * );
  5117. * ```
  5118. *
  5119. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  5120. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  5121. * as well as among its children
  5122. * @param {Function} callback the callback function that will be fired when the listener is triggered
  5123. *
  5124. * The arguments present in the callback function are:
  5125. * * `element` - The captured DOM element that the animation was fired on.
  5126. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  5127. */
  5128. on: $$animateQueue.on,
  5129. /**
  5130. *
  5131. * @ngdoc method
  5132. * @name $animate#off
  5133. * @kind function
  5134. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  5135. * can be used in three different ways depending on the arguments:
  5136. *
  5137. * ```js
  5138. * // remove all the animation event listeners listening for `enter`
  5139. * $animate.off('enter');
  5140. *
  5141. * // remove listeners for all animation events from the container element
  5142. * $animate.off(container);
  5143. *
  5144. * // remove all the animation event listeners listening for `enter` on the given element and its children
  5145. * $animate.off('enter', container);
  5146. *
  5147. * // remove the event listener function provided by `callback` that is set
  5148. * // to listen for `enter` on the given `container` as well as its children
  5149. * $animate.off('enter', container, callback);
  5150. * ```
  5151. *
  5152. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  5153. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  5154. * arguments are ignored.
  5155. * @param {DOMElement=} container the container element the event listener was placed on
  5156. * @param {Function=} callback the callback function that was registered as the listener
  5157. */
  5158. off: $$animateQueue.off,
  5159. /**
  5160. * @ngdoc method
  5161. * @name $animate#pin
  5162. * @kind function
  5163. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  5164. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  5165. * element despite being outside the realm of the application or within another application. Say for example if the application
  5166. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  5167. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  5168. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  5169. *
  5170. * Note that this feature is only active when the `ngAnimate` module is used.
  5171. *
  5172. * @param {DOMElement} element the external element that will be pinned
  5173. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  5174. */
  5175. pin: $$animateQueue.pin,
  5176. /**
  5177. *
  5178. * @ngdoc method
  5179. * @name $animate#enabled
  5180. * @kind function
  5181. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  5182. * function can be called in four ways:
  5183. *
  5184. * ```js
  5185. * // returns true or false
  5186. * $animate.enabled();
  5187. *
  5188. * // changes the enabled state for all animations
  5189. * $animate.enabled(false);
  5190. * $animate.enabled(true);
  5191. *
  5192. * // returns true or false if animations are enabled for an element
  5193. * $animate.enabled(element);
  5194. *
  5195. * // changes the enabled state for an element and its children
  5196. * $animate.enabled(element, true);
  5197. * $animate.enabled(element, false);
  5198. * ```
  5199. *
  5200. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  5201. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  5202. *
  5203. * @return {boolean} whether or not animations are enabled
  5204. */
  5205. enabled: $$animateQueue.enabled,
  5206. /**
  5207. * @ngdoc method
  5208. * @name $animate#cancel
  5209. * @kind function
  5210. * @description Cancels the provided animation.
  5211. *
  5212. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  5213. */
  5214. cancel: function(runner) {
  5215. if (runner.end) {
  5216. runner.end();
  5217. }
  5218. },
  5219. /**
  5220. *
  5221. * @ngdoc method
  5222. * @name $animate#enter
  5223. * @kind function
  5224. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  5225. * as the first child within the `parent` element and then triggers an animation.
  5226. * A promise is returned that will be resolved during the next digest once the animation
  5227. * has completed.
  5228. *
  5229. * @param {DOMElement} element the element which will be inserted into the DOM
  5230. * @param {DOMElement} parent the parent element which will append the element as
  5231. * a child (so long as the after element is not present)
  5232. * @param {DOMElement=} after the sibling element after which the element will be appended
  5233. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5234. * The object can have the following properties:
  5235. *
  5236. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5237. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5238. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5239. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5240. *
  5241. * @return {Promise} the animation callback promise
  5242. */
  5243. enter: function(element, parent, after, options) {
  5244. parent = parent && jqLite(parent);
  5245. after = after && jqLite(after);
  5246. parent = parent || after.parent();
  5247. domInsert(element, parent, after);
  5248. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  5249. },
  5250. /**
  5251. *
  5252. * @ngdoc method
  5253. * @name $animate#move
  5254. * @kind function
  5255. * @description Inserts (moves) the element into its new position in the DOM either after
  5256. * the `after` element (if provided) or as the first child within the `parent` element
  5257. * and then triggers an animation. A promise is returned that will be resolved
  5258. * during the next digest once the animation has completed.
  5259. *
  5260. * @param {DOMElement} element the element which will be moved into the new DOM position
  5261. * @param {DOMElement} parent the parent element which will append the element as
  5262. * a child (so long as the after element is not present)
  5263. * @param {DOMElement=} after the sibling element after which the element will be appended
  5264. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5265. * The object can have the following properties:
  5266. *
  5267. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5268. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5269. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5270. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5271. *
  5272. * @return {Promise} the animation callback promise
  5273. */
  5274. move: function(element, parent, after, options) {
  5275. parent = parent && jqLite(parent);
  5276. after = after && jqLite(after);
  5277. parent = parent || after.parent();
  5278. domInsert(element, parent, after);
  5279. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  5280. },
  5281. /**
  5282. * @ngdoc method
  5283. * @name $animate#leave
  5284. * @kind function
  5285. * @description Triggers an animation and then removes the element from the DOM.
  5286. * When the function is called a promise is returned that will be resolved during the next
  5287. * digest once the animation has completed.
  5288. *
  5289. * @param {DOMElement} element the element which will be removed from the DOM
  5290. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5291. * The object can have the following properties:
  5292. *
  5293. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5294. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5295. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5296. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5297. *
  5298. * @return {Promise} the animation callback promise
  5299. */
  5300. leave: function(element, options) {
  5301. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  5302. element.remove();
  5303. });
  5304. },
  5305. /**
  5306. * @ngdoc method
  5307. * @name $animate#addClass
  5308. * @kind function
  5309. *
  5310. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  5311. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  5312. * animation if element already contains the CSS class or if the class is removed at a later step.
  5313. * Note that class-based animations are treated differently compared to structural animations
  5314. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5315. * depending if CSS or JavaScript animations are used.
  5316. *
  5317. * @param {DOMElement} element the element which the CSS classes will be applied to
  5318. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  5319. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5320. * The object can have the following properties:
  5321. *
  5322. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5323. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5324. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5325. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5326. *
  5327. * @return {Promise} the animation callback promise
  5328. */
  5329. addClass: function(element, className, options) {
  5330. options = prepareAnimateOptions(options);
  5331. options.addClass = mergeClasses(options.addclass, className);
  5332. return $$animateQueue.push(element, 'addClass', options);
  5333. },
  5334. /**
  5335. * @ngdoc method
  5336. * @name $animate#removeClass
  5337. * @kind function
  5338. *
  5339. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  5340. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  5341. * animation if element does not contain the CSS class or if the class is added at a later step.
  5342. * Note that class-based animations are treated differently compared to structural animations
  5343. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5344. * depending if CSS or JavaScript animations are used.
  5345. *
  5346. * @param {DOMElement} element the element which the CSS classes will be applied to
  5347. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5348. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5349. * The object can have the following properties:
  5350. *
  5351. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5352. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5353. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5354. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5355. *
  5356. * @return {Promise} the animation callback promise
  5357. */
  5358. removeClass: function(element, className, options) {
  5359. options = prepareAnimateOptions(options);
  5360. options.removeClass = mergeClasses(options.removeClass, className);
  5361. return $$animateQueue.push(element, 'removeClass', options);
  5362. },
  5363. /**
  5364. * @ngdoc method
  5365. * @name $animate#setClass
  5366. * @kind function
  5367. *
  5368. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5369. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5370. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5371. * passed. Note that class-based animations are treated differently compared to structural animations
  5372. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5373. * depending if CSS or JavaScript animations are used.
  5374. *
  5375. * @param {DOMElement} element the element which the CSS classes will be applied to
  5376. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5377. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5378. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5379. * The object can have the following properties:
  5380. *
  5381. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5382. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5383. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5384. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5385. *
  5386. * @return {Promise} the animation callback promise
  5387. */
  5388. setClass: function(element, add, remove, options) {
  5389. options = prepareAnimateOptions(options);
  5390. options.addClass = mergeClasses(options.addClass, add);
  5391. options.removeClass = mergeClasses(options.removeClass, remove);
  5392. return $$animateQueue.push(element, 'setClass', options);
  5393. },
  5394. /**
  5395. * @ngdoc method
  5396. * @name $animate#animate
  5397. * @kind function
  5398. *
  5399. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5400. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5401. * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
  5402. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5403. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5404. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5405. * method (or as part of the `options` parameter):
  5406. *
  5407. * ```js
  5408. * ngModule.animation('.my-inline-animation', function() {
  5409. * return {
  5410. * animate : function(element, from, to, done, options) {
  5411. * //animation
  5412. * done();
  5413. * }
  5414. * }
  5415. * });
  5416. * ```
  5417. *
  5418. * @param {DOMElement} element the element which the CSS styles will be applied to
  5419. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5420. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5421. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5422. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5423. * (Note that if no animation is detected then this value will not be applied to the element.)
  5424. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5425. * The object can have the following properties:
  5426. *
  5427. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5428. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5429. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5430. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5431. *
  5432. * @return {Promise} the animation callback promise
  5433. */
  5434. animate: function(element, from, to, className, options) {
  5435. options = prepareAnimateOptions(options);
  5436. options.from = options.from ? extend(options.from, from) : from;
  5437. options.to = options.to ? extend(options.to, to) : to;
  5438. className = className || 'ng-inline-animate';
  5439. options.tempClasses = mergeClasses(options.tempClasses, className);
  5440. return $$animateQueue.push(element, 'animate', options);
  5441. }
  5442. };
  5443. }];
  5444. }];
  5445. var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
  5446. this.$get = ['$$rAF', function($$rAF) {
  5447. var waitQueue = [];
  5448. function waitForTick(fn) {
  5449. waitQueue.push(fn);
  5450. if (waitQueue.length > 1) return;
  5451. $$rAF(function() {
  5452. for (var i = 0; i < waitQueue.length; i++) {
  5453. waitQueue[i]();
  5454. }
  5455. waitQueue = [];
  5456. });
  5457. }
  5458. return function() {
  5459. var passed = false;
  5460. waitForTick(function() {
  5461. passed = true;
  5462. });
  5463. return function(callback) {
  5464. if (passed) {
  5465. callback();
  5466. } else {
  5467. waitForTick(callback);
  5468. }
  5469. };
  5470. };
  5471. }];
  5472. };
  5473. var $$AnimateRunnerFactoryProvider = /** @this */ function() {
  5474. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
  5475. function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
  5476. var INITIAL_STATE = 0;
  5477. var DONE_PENDING_STATE = 1;
  5478. var DONE_COMPLETE_STATE = 2;
  5479. AnimateRunner.chain = function(chain, callback) {
  5480. var index = 0;
  5481. next();
  5482. function next() {
  5483. if (index === chain.length) {
  5484. callback(true);
  5485. return;
  5486. }
  5487. chain[index](function(response) {
  5488. if (response === false) {
  5489. callback(false);
  5490. return;
  5491. }
  5492. index++;
  5493. next();
  5494. });
  5495. }
  5496. };
  5497. AnimateRunner.all = function(runners, callback) {
  5498. var count = 0;
  5499. var status = true;
  5500. forEach(runners, function(runner) {
  5501. runner.done(onProgress);
  5502. });
  5503. function onProgress(response) {
  5504. status = status && response;
  5505. if (++count === runners.length) {
  5506. callback(status);
  5507. }
  5508. }
  5509. };
  5510. function AnimateRunner(host) {
  5511. this.setHost(host);
  5512. var rafTick = $$animateAsyncRun();
  5513. var timeoutTick = function(fn) {
  5514. $timeout(fn, 0, false);
  5515. };
  5516. this._doneCallbacks = [];
  5517. this._tick = function(fn) {
  5518. if ($$isDocumentHidden()) {
  5519. timeoutTick(fn);
  5520. } else {
  5521. rafTick(fn);
  5522. }
  5523. };
  5524. this._state = 0;
  5525. }
  5526. AnimateRunner.prototype = {
  5527. setHost: function(host) {
  5528. this.host = host || {};
  5529. },
  5530. done: function(fn) {
  5531. if (this._state === DONE_COMPLETE_STATE) {
  5532. fn();
  5533. } else {
  5534. this._doneCallbacks.push(fn);
  5535. }
  5536. },
  5537. progress: noop,
  5538. getPromise: function() {
  5539. if (!this.promise) {
  5540. var self = this;
  5541. this.promise = $q(function(resolve, reject) {
  5542. self.done(function(status) {
  5543. if (status === false) {
  5544. reject();
  5545. } else {
  5546. resolve();
  5547. }
  5548. });
  5549. });
  5550. }
  5551. return this.promise;
  5552. },
  5553. then: function(resolveHandler, rejectHandler) {
  5554. return this.getPromise().then(resolveHandler, rejectHandler);
  5555. },
  5556. 'catch': function(handler) {
  5557. return this.getPromise()['catch'](handler);
  5558. },
  5559. 'finally': function(handler) {
  5560. return this.getPromise()['finally'](handler);
  5561. },
  5562. pause: function() {
  5563. if (this.host.pause) {
  5564. this.host.pause();
  5565. }
  5566. },
  5567. resume: function() {
  5568. if (this.host.resume) {
  5569. this.host.resume();
  5570. }
  5571. },
  5572. end: function() {
  5573. if (this.host.end) {
  5574. this.host.end();
  5575. }
  5576. this._resolve(true);
  5577. },
  5578. cancel: function() {
  5579. if (this.host.cancel) {
  5580. this.host.cancel();
  5581. }
  5582. this._resolve(false);
  5583. },
  5584. complete: function(response) {
  5585. var self = this;
  5586. if (self._state === INITIAL_STATE) {
  5587. self._state = DONE_PENDING_STATE;
  5588. self._tick(function() {
  5589. self._resolve(response);
  5590. });
  5591. }
  5592. },
  5593. _resolve: function(response) {
  5594. if (this._state !== DONE_COMPLETE_STATE) {
  5595. forEach(this._doneCallbacks, function(fn) {
  5596. fn(response);
  5597. });
  5598. this._doneCallbacks.length = 0;
  5599. this._state = DONE_COMPLETE_STATE;
  5600. }
  5601. }
  5602. };
  5603. return AnimateRunner;
  5604. }];
  5605. };
  5606. /* exported $CoreAnimateCssProvider */
  5607. /**
  5608. * @ngdoc service
  5609. * @name $animateCss
  5610. * @kind object
  5611. * @this
  5612. *
  5613. * @description
  5614. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5615. * then the `$animateCss` service will actually perform animations.
  5616. *
  5617. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5618. */
  5619. var $CoreAnimateCssProvider = function() {
  5620. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5621. return function(element, initialOptions) {
  5622. // all of the animation functions should create
  5623. // a copy of the options data, however, if a
  5624. // parent service has already created a copy then
  5625. // we should stick to using that
  5626. var options = initialOptions || {};
  5627. if (!options.$$prepared) {
  5628. options = copy(options);
  5629. }
  5630. // there is no point in applying the styles since
  5631. // there is no animation that goes on at all in
  5632. // this version of $animateCss.
  5633. if (options.cleanupStyles) {
  5634. options.from = options.to = null;
  5635. }
  5636. if (options.from) {
  5637. element.css(options.from);
  5638. options.from = null;
  5639. }
  5640. var closed, runner = new $$AnimateRunner();
  5641. return {
  5642. start: run,
  5643. end: run
  5644. };
  5645. function run() {
  5646. $$rAF(function() {
  5647. applyAnimationContents();
  5648. if (!closed) {
  5649. runner.complete();
  5650. }
  5651. closed = true;
  5652. });
  5653. return runner;
  5654. }
  5655. function applyAnimationContents() {
  5656. if (options.addClass) {
  5657. element.addClass(options.addClass);
  5658. options.addClass = null;
  5659. }
  5660. if (options.removeClass) {
  5661. element.removeClass(options.removeClass);
  5662. options.removeClass = null;
  5663. }
  5664. if (options.to) {
  5665. element.css(options.to);
  5666. options.to = null;
  5667. }
  5668. }
  5669. };
  5670. }];
  5671. };
  5672. /* global stripHash: true */
  5673. /**
  5674. * ! This is a private undocumented service !
  5675. *
  5676. * @name $browser
  5677. * @requires $log
  5678. * @description
  5679. * This object has two goals:
  5680. *
  5681. * - hide all the global state in the browser caused by the window object
  5682. * - abstract away all the browser specific features and inconsistencies
  5683. *
  5684. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5685. * service, which can be used for convenient testing of the application without the interaction with
  5686. * the real browser apis.
  5687. */
  5688. /**
  5689. * @param {object} window The global window object.
  5690. * @param {object} document jQuery wrapped document.
  5691. * @param {object} $log window.console or an object with the same interface.
  5692. * @param {object} $sniffer $sniffer service
  5693. */
  5694. function Browser(window, document, $log, $sniffer) {
  5695. var self = this,
  5696. location = window.location,
  5697. history = window.history,
  5698. setTimeout = window.setTimeout,
  5699. clearTimeout = window.clearTimeout,
  5700. pendingDeferIds = {};
  5701. self.isMock = false;
  5702. var outstandingRequestCount = 0;
  5703. var outstandingRequestCallbacks = [];
  5704. // TODO(vojta): remove this temporary api
  5705. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5706. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5707. /**
  5708. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5709. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5710. */
  5711. function completeOutstandingRequest(fn) {
  5712. try {
  5713. fn.apply(null, sliceArgs(arguments, 1));
  5714. } finally {
  5715. outstandingRequestCount--;
  5716. if (outstandingRequestCount === 0) {
  5717. while (outstandingRequestCallbacks.length) {
  5718. try {
  5719. outstandingRequestCallbacks.pop()();
  5720. } catch (e) {
  5721. $log.error(e);
  5722. }
  5723. }
  5724. }
  5725. }
  5726. }
  5727. function getHash(url) {
  5728. var index = url.indexOf('#');
  5729. return index === -1 ? '' : url.substr(index);
  5730. }
  5731. /**
  5732. * @private
  5733. * Note: this method is used only by scenario runner
  5734. * TODO(vojta): prefix this method with $$ ?
  5735. * @param {function()} callback Function that will be called when no outstanding request
  5736. */
  5737. self.notifyWhenNoOutstandingRequests = function(callback) {
  5738. if (outstandingRequestCount === 0) {
  5739. callback();
  5740. } else {
  5741. outstandingRequestCallbacks.push(callback);
  5742. }
  5743. };
  5744. //////////////////////////////////////////////////////////////
  5745. // URL API
  5746. //////////////////////////////////////////////////////////////
  5747. var cachedState, lastHistoryState,
  5748. lastBrowserUrl = location.href,
  5749. baseElement = document.find('base'),
  5750. pendingLocation = null,
  5751. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5752. try {
  5753. return history.state;
  5754. } catch (e) {
  5755. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5756. }
  5757. };
  5758. cacheState();
  5759. /**
  5760. * @name $browser#url
  5761. *
  5762. * @description
  5763. * GETTER:
  5764. * Without any argument, this method just returns current value of location.href.
  5765. *
  5766. * SETTER:
  5767. * With at least one argument, this method sets url to new value.
  5768. * If html5 history api supported, pushState/replaceState is used, otherwise
  5769. * location.href/location.replace is used.
  5770. * Returns its own instance to allow chaining
  5771. *
  5772. * NOTE: this api is intended for use only by the $location service. Please use the
  5773. * {@link ng.$location $location service} to change url.
  5774. *
  5775. * @param {string} url New url (when used as setter)
  5776. * @param {boolean=} replace Should new url replace current history record?
  5777. * @param {object=} state object to use with pushState/replaceState
  5778. */
  5779. self.url = function(url, replace, state) {
  5780. // In modern browsers `history.state` is `null` by default; treating it separately
  5781. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5782. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5783. if (isUndefined(state)) {
  5784. state = null;
  5785. }
  5786. // Android Browser BFCache causes location, history reference to become stale.
  5787. if (location !== window.location) location = window.location;
  5788. if (history !== window.history) history = window.history;
  5789. // setter
  5790. if (url) {
  5791. var sameState = lastHistoryState === state;
  5792. // Don't change anything if previous and current URLs and states match. This also prevents
  5793. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5794. // See https://github.com/angular/angular.js/commit/ffb2701
  5795. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5796. return self;
  5797. }
  5798. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5799. lastBrowserUrl = url;
  5800. lastHistoryState = state;
  5801. // Don't use history API if only the hash changed
  5802. // due to a bug in IE10/IE11 which leads
  5803. // to not firing a `hashchange` nor `popstate` event
  5804. // in some cases (see #9143).
  5805. if ($sniffer.history && (!sameBase || !sameState)) {
  5806. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5807. cacheState();
  5808. } else {
  5809. if (!sameBase) {
  5810. pendingLocation = url;
  5811. }
  5812. if (replace) {
  5813. location.replace(url);
  5814. } else if (!sameBase) {
  5815. location.href = url;
  5816. } else {
  5817. location.hash = getHash(url);
  5818. }
  5819. if (location.href !== url) {
  5820. pendingLocation = url;
  5821. }
  5822. }
  5823. if (pendingLocation) {
  5824. pendingLocation = url;
  5825. }
  5826. return self;
  5827. // getter
  5828. } else {
  5829. // - pendingLocation is needed as browsers don't allow to read out
  5830. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5831. // https://openradar.appspot.com/22186109).
  5832. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5833. return pendingLocation || location.href.replace(/%27/g,'\'');
  5834. }
  5835. };
  5836. /**
  5837. * @name $browser#state
  5838. *
  5839. * @description
  5840. * This method is a getter.
  5841. *
  5842. * Return history.state or null if history.state is undefined.
  5843. *
  5844. * @returns {object} state
  5845. */
  5846. self.state = function() {
  5847. return cachedState;
  5848. };
  5849. var urlChangeListeners = [],
  5850. urlChangeInit = false;
  5851. function cacheStateAndFireUrlChange() {
  5852. pendingLocation = null;
  5853. fireStateOrUrlChange();
  5854. }
  5855. // This variable should be used *only* inside the cacheState function.
  5856. var lastCachedState = null;
  5857. function cacheState() {
  5858. // This should be the only place in $browser where `history.state` is read.
  5859. cachedState = getCurrentState();
  5860. cachedState = isUndefined(cachedState) ? null : cachedState;
  5861. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5862. if (equals(cachedState, lastCachedState)) {
  5863. cachedState = lastCachedState;
  5864. }
  5865. lastCachedState = cachedState;
  5866. lastHistoryState = cachedState;
  5867. }
  5868. function fireStateOrUrlChange() {
  5869. var prevLastHistoryState = lastHistoryState;
  5870. cacheState();
  5871. if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {
  5872. return;
  5873. }
  5874. lastBrowserUrl = self.url();
  5875. lastHistoryState = cachedState;
  5876. forEach(urlChangeListeners, function(listener) {
  5877. listener(self.url(), cachedState);
  5878. });
  5879. }
  5880. /**
  5881. * @name $browser#onUrlChange
  5882. *
  5883. * @description
  5884. * Register callback function that will be called, when url changes.
  5885. *
  5886. * It's only called when the url is changed from outside of angular:
  5887. * - user types different url into address bar
  5888. * - user clicks on history (forward/back) button
  5889. * - user clicks on a link
  5890. *
  5891. * It's not called when url is changed by $browser.url() method
  5892. *
  5893. * The listener gets called with new url as parameter.
  5894. *
  5895. * NOTE: this api is intended for use only by the $location service. Please use the
  5896. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5897. *
  5898. * @param {function(string)} listener Listener function to be called when url changes.
  5899. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5900. */
  5901. self.onUrlChange = function(callback) {
  5902. // TODO(vojta): refactor to use node's syntax for events
  5903. if (!urlChangeInit) {
  5904. // We listen on both (hashchange/popstate) when available, as some browsers don't
  5905. // fire popstate when user changes the address bar and don't fire hashchange when url
  5906. // changed by push/replaceState
  5907. // html5 history api - popstate event
  5908. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5909. // hashchange event
  5910. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5911. urlChangeInit = true;
  5912. }
  5913. urlChangeListeners.push(callback);
  5914. return callback;
  5915. };
  5916. /**
  5917. * @private
  5918. * Remove popstate and hashchange handler from window.
  5919. *
  5920. * NOTE: this api is intended for use only by $rootScope.
  5921. */
  5922. self.$$applicationDestroyed = function() {
  5923. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5924. };
  5925. /**
  5926. * Checks whether the url has changed outside of Angular.
  5927. * Needs to be exported to be able to check for changes that have been done in sync,
  5928. * as hashchange/popstate events fire in async.
  5929. */
  5930. self.$$checkUrlChange = fireStateOrUrlChange;
  5931. //////////////////////////////////////////////////////////////
  5932. // Misc API
  5933. //////////////////////////////////////////////////////////////
  5934. /**
  5935. * @name $browser#baseHref
  5936. *
  5937. * @description
  5938. * Returns current <base href>
  5939. * (always relative - without domain)
  5940. *
  5941. * @returns {string} The current base href
  5942. */
  5943. self.baseHref = function() {
  5944. var href = baseElement.attr('href');
  5945. return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
  5946. };
  5947. /**
  5948. * @name $browser#defer
  5949. * @param {function()} fn A function, who's execution should be deferred.
  5950. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5951. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5952. *
  5953. * @description
  5954. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5955. *
  5956. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5957. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5958. * via `$browser.defer.flush()`.
  5959. *
  5960. */
  5961. self.defer = function(fn, delay) {
  5962. var timeoutId;
  5963. outstandingRequestCount++;
  5964. timeoutId = setTimeout(function() {
  5965. delete pendingDeferIds[timeoutId];
  5966. completeOutstandingRequest(fn);
  5967. }, delay || 0);
  5968. pendingDeferIds[timeoutId] = true;
  5969. return timeoutId;
  5970. };
  5971. /**
  5972. * @name $browser#defer.cancel
  5973. *
  5974. * @description
  5975. * Cancels a deferred task identified with `deferId`.
  5976. *
  5977. * @param {*} deferId Token returned by the `$browser.defer` function.
  5978. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5979. * canceled.
  5980. */
  5981. self.defer.cancel = function(deferId) {
  5982. if (pendingDeferIds[deferId]) {
  5983. delete pendingDeferIds[deferId];
  5984. clearTimeout(deferId);
  5985. completeOutstandingRequest(noop);
  5986. return true;
  5987. }
  5988. return false;
  5989. };
  5990. }
  5991. /** @this */
  5992. function $BrowserProvider() {
  5993. this.$get = ['$window', '$log', '$sniffer', '$document',
  5994. function($window, $log, $sniffer, $document) {
  5995. return new Browser($window, $document, $log, $sniffer);
  5996. }];
  5997. }
  5998. /**
  5999. * @ngdoc service
  6000. * @name $cacheFactory
  6001. * @this
  6002. *
  6003. * @description
  6004. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  6005. * them.
  6006. *
  6007. * ```js
  6008. *
  6009. * var cache = $cacheFactory('cacheId');
  6010. * expect($cacheFactory.get('cacheId')).toBe(cache);
  6011. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  6012. *
  6013. * cache.put("key", "value");
  6014. * cache.put("another key", "another value");
  6015. *
  6016. * // We've specified no options on creation
  6017. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  6018. *
  6019. * ```
  6020. *
  6021. *
  6022. * @param {string} cacheId Name or id of the newly created cache.
  6023. * @param {object=} options Options object that specifies the cache behavior. Properties:
  6024. *
  6025. * - `{number=}` `capacity` — turns the cache into LRU cache.
  6026. *
  6027. * @returns {object} Newly created cache object with the following set of methods:
  6028. *
  6029. * - `{object}` `info()` — Returns id, size, and options of cache.
  6030. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  6031. * it.
  6032. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  6033. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  6034. * - `{void}` `removeAll()` — Removes all cached values.
  6035. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  6036. *
  6037. * @example
  6038. <example module="cacheExampleApp" name="cache-factory">
  6039. <file name="index.html">
  6040. <div ng-controller="CacheController">
  6041. <input ng-model="newCacheKey" placeholder="Key">
  6042. <input ng-model="newCacheValue" placeholder="Value">
  6043. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  6044. <p ng-if="keys.length">Cached Values</p>
  6045. <div ng-repeat="key in keys">
  6046. <span ng-bind="key"></span>
  6047. <span>: </span>
  6048. <b ng-bind="cache.get(key)"></b>
  6049. </div>
  6050. <p>Cache Info</p>
  6051. <div ng-repeat="(key, value) in cache.info()">
  6052. <span ng-bind="key"></span>
  6053. <span>: </span>
  6054. <b ng-bind="value"></b>
  6055. </div>
  6056. </div>
  6057. </file>
  6058. <file name="script.js">
  6059. angular.module('cacheExampleApp', []).
  6060. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  6061. $scope.keys = [];
  6062. $scope.cache = $cacheFactory('cacheId');
  6063. $scope.put = function(key, value) {
  6064. if (angular.isUndefined($scope.cache.get(key))) {
  6065. $scope.keys.push(key);
  6066. }
  6067. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  6068. };
  6069. }]);
  6070. </file>
  6071. <file name="style.css">
  6072. p {
  6073. margin: 10px 0 3px;
  6074. }
  6075. </file>
  6076. </example>
  6077. */
  6078. function $CacheFactoryProvider() {
  6079. this.$get = function() {
  6080. var caches = {};
  6081. function cacheFactory(cacheId, options) {
  6082. if (cacheId in caches) {
  6083. throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
  6084. }
  6085. var size = 0,
  6086. stats = extend({}, options, {id: cacheId}),
  6087. data = createMap(),
  6088. capacity = (options && options.capacity) || Number.MAX_VALUE,
  6089. lruHash = createMap(),
  6090. freshEnd = null,
  6091. staleEnd = null;
  6092. /**
  6093. * @ngdoc type
  6094. * @name $cacheFactory.Cache
  6095. *
  6096. * @description
  6097. * A cache object used to store and retrieve data, primarily used by
  6098. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  6099. * templates and other data.
  6100. *
  6101. * ```js
  6102. * angular.module('superCache')
  6103. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  6104. * return $cacheFactory('super-cache');
  6105. * }]);
  6106. * ```
  6107. *
  6108. * Example test:
  6109. *
  6110. * ```js
  6111. * it('should behave like a cache', inject(function(superCache) {
  6112. * superCache.put('key', 'value');
  6113. * superCache.put('another key', 'another value');
  6114. *
  6115. * expect(superCache.info()).toEqual({
  6116. * id: 'super-cache',
  6117. * size: 2
  6118. * });
  6119. *
  6120. * superCache.remove('another key');
  6121. * expect(superCache.get('another key')).toBeUndefined();
  6122. *
  6123. * superCache.removeAll();
  6124. * expect(superCache.info()).toEqual({
  6125. * id: 'super-cache',
  6126. * size: 0
  6127. * });
  6128. * }));
  6129. * ```
  6130. */
  6131. return (caches[cacheId] = {
  6132. /**
  6133. * @ngdoc method
  6134. * @name $cacheFactory.Cache#put
  6135. * @kind function
  6136. *
  6137. * @description
  6138. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  6139. * retrieved later, and incrementing the size of the cache if the key was not already
  6140. * present in the cache. If behaving like an LRU cache, it will also remove stale
  6141. * entries from the set.
  6142. *
  6143. * It will not insert undefined values into the cache.
  6144. *
  6145. * @param {string} key the key under which the cached data is stored.
  6146. * @param {*} value the value to store alongside the key. If it is undefined, the key
  6147. * will not be stored.
  6148. * @returns {*} the value stored.
  6149. */
  6150. put: function(key, value) {
  6151. if (isUndefined(value)) return;
  6152. if (capacity < Number.MAX_VALUE) {
  6153. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  6154. refresh(lruEntry);
  6155. }
  6156. if (!(key in data)) size++;
  6157. data[key] = value;
  6158. if (size > capacity) {
  6159. this.remove(staleEnd.key);
  6160. }
  6161. return value;
  6162. },
  6163. /**
  6164. * @ngdoc method
  6165. * @name $cacheFactory.Cache#get
  6166. * @kind function
  6167. *
  6168. * @description
  6169. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  6170. *
  6171. * @param {string} key the key of the data to be retrieved
  6172. * @returns {*} the value stored.
  6173. */
  6174. get: function(key) {
  6175. if (capacity < Number.MAX_VALUE) {
  6176. var lruEntry = lruHash[key];
  6177. if (!lruEntry) return;
  6178. refresh(lruEntry);
  6179. }
  6180. return data[key];
  6181. },
  6182. /**
  6183. * @ngdoc method
  6184. * @name $cacheFactory.Cache#remove
  6185. * @kind function
  6186. *
  6187. * @description
  6188. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  6189. *
  6190. * @param {string} key the key of the entry to be removed
  6191. */
  6192. remove: function(key) {
  6193. if (capacity < Number.MAX_VALUE) {
  6194. var lruEntry = lruHash[key];
  6195. if (!lruEntry) return;
  6196. if (lruEntry === freshEnd) freshEnd = lruEntry.p;
  6197. if (lruEntry === staleEnd) staleEnd = lruEntry.n;
  6198. link(lruEntry.n,lruEntry.p);
  6199. delete lruHash[key];
  6200. }
  6201. if (!(key in data)) return;
  6202. delete data[key];
  6203. size--;
  6204. },
  6205. /**
  6206. * @ngdoc method
  6207. * @name $cacheFactory.Cache#removeAll
  6208. * @kind function
  6209. *
  6210. * @description
  6211. * Clears the cache object of any entries.
  6212. */
  6213. removeAll: function() {
  6214. data = createMap();
  6215. size = 0;
  6216. lruHash = createMap();
  6217. freshEnd = staleEnd = null;
  6218. },
  6219. /**
  6220. * @ngdoc method
  6221. * @name $cacheFactory.Cache#destroy
  6222. * @kind function
  6223. *
  6224. * @description
  6225. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  6226. * removing it from the {@link $cacheFactory $cacheFactory} set.
  6227. */
  6228. destroy: function() {
  6229. data = null;
  6230. stats = null;
  6231. lruHash = null;
  6232. delete caches[cacheId];
  6233. },
  6234. /**
  6235. * @ngdoc method
  6236. * @name $cacheFactory.Cache#info
  6237. * @kind function
  6238. *
  6239. * @description
  6240. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  6241. *
  6242. * @returns {object} an object with the following properties:
  6243. * <ul>
  6244. * <li>**id**: the id of the cache instance</li>
  6245. * <li>**size**: the number of entries kept in the cache instance</li>
  6246. * <li>**...**: any additional properties from the options object when creating the
  6247. * cache.</li>
  6248. * </ul>
  6249. */
  6250. info: function() {
  6251. return extend({}, stats, {size: size});
  6252. }
  6253. });
  6254. /**
  6255. * makes the `entry` the freshEnd of the LRU linked list
  6256. */
  6257. function refresh(entry) {
  6258. if (entry !== freshEnd) {
  6259. if (!staleEnd) {
  6260. staleEnd = entry;
  6261. } else if (staleEnd === entry) {
  6262. staleEnd = entry.n;
  6263. }
  6264. link(entry.n, entry.p);
  6265. link(entry, freshEnd);
  6266. freshEnd = entry;
  6267. freshEnd.n = null;
  6268. }
  6269. }
  6270. /**
  6271. * bidirectionally links two entries of the LRU linked list
  6272. */
  6273. function link(nextEntry, prevEntry) {
  6274. if (nextEntry !== prevEntry) {
  6275. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  6276. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  6277. }
  6278. }
  6279. }
  6280. /**
  6281. * @ngdoc method
  6282. * @name $cacheFactory#info
  6283. *
  6284. * @description
  6285. * Get information about all the caches that have been created
  6286. *
  6287. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  6288. */
  6289. cacheFactory.info = function() {
  6290. var info = {};
  6291. forEach(caches, function(cache, cacheId) {
  6292. info[cacheId] = cache.info();
  6293. });
  6294. return info;
  6295. };
  6296. /**
  6297. * @ngdoc method
  6298. * @name $cacheFactory#get
  6299. *
  6300. * @description
  6301. * Get access to a cache object by the `cacheId` used when it was created.
  6302. *
  6303. * @param {string} cacheId Name or id of a cache to access.
  6304. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  6305. */
  6306. cacheFactory.get = function(cacheId) {
  6307. return caches[cacheId];
  6308. };
  6309. return cacheFactory;
  6310. };
  6311. }
  6312. /**
  6313. * @ngdoc service
  6314. * @name $templateCache
  6315. * @this
  6316. *
  6317. * @description
  6318. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  6319. * can load templates directly into the cache in a `script` tag, or by consuming the
  6320. * `$templateCache` service directly.
  6321. *
  6322. * Adding via the `script` tag:
  6323. *
  6324. * ```html
  6325. * <script type="text/ng-template" id="templateId.html">
  6326. * <p>This is the content of the template</p>
  6327. * </script>
  6328. * ```
  6329. *
  6330. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  6331. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  6332. * element with ng-app attribute), otherwise the template will be ignored.
  6333. *
  6334. * Adding via the `$templateCache` service:
  6335. *
  6336. * ```js
  6337. * var myApp = angular.module('myApp', []);
  6338. * myApp.run(function($templateCache) {
  6339. * $templateCache.put('templateId.html', 'This is the content of the template');
  6340. * });
  6341. * ```
  6342. *
  6343. * To retrieve the template later, simply use it in your component:
  6344. * ```js
  6345. * myApp.component('myComponent', {
  6346. * templateUrl: 'templateId.html'
  6347. * });
  6348. * ```
  6349. *
  6350. * or get it via the `$templateCache` service:
  6351. * ```js
  6352. * $templateCache.get('templateId.html')
  6353. * ```
  6354. *
  6355. * See {@link ng.$cacheFactory $cacheFactory}.
  6356. *
  6357. */
  6358. function $TemplateCacheProvider() {
  6359. this.$get = ['$cacheFactory', function($cacheFactory) {
  6360. return $cacheFactory('templates');
  6361. }];
  6362. }
  6363. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  6364. * Any commits to this file should be reviewed with security in mind. *
  6365. * Changes to this file can potentially create security vulnerabilities. *
  6366. * An approval from 2 Core members with history of modifying *
  6367. * this file is required. *
  6368. * *
  6369. * Does the change somehow allow for arbitrary javascript to be executed? *
  6370. * Or allows for someone to change the prototype of built-in objects? *
  6371. * Or gives undesired access to variables like document or window? *
  6372. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  6373. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  6374. *
  6375. * DOM-related variables:
  6376. *
  6377. * - "node" - DOM Node
  6378. * - "element" - DOM Element or Node
  6379. * - "$node" or "$element" - jqLite-wrapped node or element
  6380. *
  6381. *
  6382. * Compiler related stuff:
  6383. *
  6384. * - "linkFn" - linking fn of a single directive
  6385. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6386. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6387. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6388. */
  6389. /**
  6390. * @ngdoc service
  6391. * @name $compile
  6392. * @kind function
  6393. *
  6394. * @description
  6395. * Compiles an HTML string or DOM into a template and produces a template function, which
  6396. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6397. *
  6398. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6399. * {@link ng.$compileProvider#directive directives}.
  6400. *
  6401. * <div class="alert alert-warning">
  6402. * **Note:** This document is an in-depth reference of all directive options.
  6403. * For a gentle introduction to directives with examples of common use cases,
  6404. * see the {@link guide/directive directive guide}.
  6405. * </div>
  6406. *
  6407. * ## Comprehensive Directive API
  6408. *
  6409. * There are many different options for a directive.
  6410. *
  6411. * The difference resides in the return value of the factory function.
  6412. * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
  6413. * that defines the directive properties, or just the `postLink` function (all other properties will have
  6414. * the default values).
  6415. *
  6416. * <div class="alert alert-success">
  6417. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6418. * </div>
  6419. *
  6420. * Here's an example directive declared with a Directive Definition Object:
  6421. *
  6422. * ```js
  6423. * var myModule = angular.module(...);
  6424. *
  6425. * myModule.directive('directiveName', function factory(injectables) {
  6426. * var directiveDefinitionObject = {
  6427. * {@link $compile#-priority- priority}: 0,
  6428. * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6429. * // or
  6430. * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6431. * {@link $compile#-transclude- transclude}: false,
  6432. * {@link $compile#-restrict- restrict}: 'A',
  6433. * {@link $compile#-templatenamespace- templateNamespace}: 'html',
  6434. * {@link $compile#-scope- scope}: false,
  6435. * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6436. * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
  6437. * {@link $compile#-bindtocontroller- bindToController}: false,
  6438. * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6439. * {@link $compile#-multielement- multiElement}: false,
  6440. * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
  6441. * return {
  6442. * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6443. * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6444. * }
  6445. * // or
  6446. * // return function postLink( ... ) { ... }
  6447. * },
  6448. * // or
  6449. * // {@link $compile#-link- link}: {
  6450. * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6451. * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6452. * // }
  6453. * // or
  6454. * // {@link $compile#-link- link}: function postLink( ... ) { ... }
  6455. * };
  6456. * return directiveDefinitionObject;
  6457. * });
  6458. * ```
  6459. *
  6460. * <div class="alert alert-warning">
  6461. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6462. * </div>
  6463. *
  6464. * Therefore the above can be simplified as:
  6465. *
  6466. * ```js
  6467. * var myModule = angular.module(...);
  6468. *
  6469. * myModule.directive('directiveName', function factory(injectables) {
  6470. * var directiveDefinitionObject = {
  6471. * link: function postLink(scope, iElement, iAttrs) { ... }
  6472. * };
  6473. * return directiveDefinitionObject;
  6474. * // or
  6475. * // return function postLink(scope, iElement, iAttrs) { ... }
  6476. * });
  6477. * ```
  6478. *
  6479. * ### Life-cycle hooks
  6480. * Directive controllers can provide the following methods that are called by Angular at points in the life-cycle of the
  6481. * directive:
  6482. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6483. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6484. * this element). This is a good place to put initialization code for your controller.
  6485. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6486. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6487. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6488. * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will
  6489. * also be called when your bindings are initialized.
  6490. * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
  6491. * changes. Any actions that you wish to take in response to the changes that you detect must be
  6492. * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
  6493. * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
  6494. * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
  6495. * if detecting changes, you must store the previous value(s) for comparison to the current values.
  6496. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6497. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6498. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6499. * components will have their `$onDestroy()` hook called before child components.
  6500. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6501. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6502. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6503. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6504. * suspended until that occurs.
  6505. *
  6506. * #### Comparison with Angular 2 life-cycle hooks
  6507. * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are
  6508. * some differences that you should be aware of, especially when it comes to moving your code from Angular 1 to Angular 2:
  6509. *
  6510. * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`.
  6511. * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor.
  6512. * In Angular 2 you can only define hooks on the prototype of the Component class.
  6513. * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to
  6514. * `ngDoCheck` in Angular 2
  6515. * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
  6516. * propagated throughout the application.
  6517. * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
  6518. * error or do nothing depending upon the state of `enableProdMode()`.
  6519. *
  6520. * #### Life-cycle hook examples
  6521. *
  6522. * This example shows how you can check for mutations to a Date object even though the identity of the object
  6523. * has not changed.
  6524. *
  6525. * <example name="doCheckDateExample" module="do-check-module">
  6526. * <file name="app.js">
  6527. * angular.module('do-check-module', [])
  6528. * .component('app', {
  6529. * template:
  6530. * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
  6531. * 'Date: {{ $ctrl.date }}' +
  6532. * '<test date="$ctrl.date"></test>',
  6533. * controller: function() {
  6534. * this.date = new Date();
  6535. * this.month = this.date.getMonth();
  6536. * this.updateDate = function() {
  6537. * this.date.setMonth(this.month);
  6538. * };
  6539. * }
  6540. * })
  6541. * .component('test', {
  6542. * bindings: { date: '<' },
  6543. * template:
  6544. * '<pre>{{ $ctrl.log | json }}</pre>',
  6545. * controller: function() {
  6546. * var previousValue;
  6547. * this.log = [];
  6548. * this.$doCheck = function() {
  6549. * var currentValue = this.date && this.date.valueOf();
  6550. * if (previousValue !== currentValue) {
  6551. * this.log.push('doCheck: date mutated: ' + this.date);
  6552. * previousValue = currentValue;
  6553. * }
  6554. * };
  6555. * }
  6556. * });
  6557. * </file>
  6558. * <file name="index.html">
  6559. * <app></app>
  6560. * </file>
  6561. * </example>
  6562. *
  6563. * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
  6564. * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
  6565. * arrays or objects can have a negative impact on your application performance)
  6566. *
  6567. * <example name="doCheckArrayExample" module="do-check-module">
  6568. * <file name="index.html">
  6569. * <div ng-init="items = []">
  6570. * <button ng-click="items.push(items.length)">Add Item</button>
  6571. * <button ng-click="items = []">Reset Items</button>
  6572. * <pre>{{ items }}</pre>
  6573. * <test items="items"></test>
  6574. * </div>
  6575. * </file>
  6576. * <file name="app.js">
  6577. * angular.module('do-check-module', [])
  6578. * .component('test', {
  6579. * bindings: { items: '<' },
  6580. * template:
  6581. * '<pre>{{ $ctrl.log | json }}</pre>',
  6582. * controller: function() {
  6583. * this.log = [];
  6584. *
  6585. * this.$doCheck = function() {
  6586. * if (this.items_ref !== this.items) {
  6587. * this.log.push('doCheck: items changed');
  6588. * this.items_ref = this.items;
  6589. * }
  6590. * if (!angular.equals(this.items_clone, this.items)) {
  6591. * this.log.push('doCheck: items mutated');
  6592. * this.items_clone = angular.copy(this.items);
  6593. * }
  6594. * };
  6595. * }
  6596. * });
  6597. * </file>
  6598. * </example>
  6599. *
  6600. *
  6601. * ### Directive Definition Object
  6602. *
  6603. * The directive definition object provides instructions to the {@link ng.$compile
  6604. * compiler}. The attributes are:
  6605. *
  6606. * #### `multiElement`
  6607. * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
  6608. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6609. * together as the directive elements. It is recommended that this feature be used on directives
  6610. * which are not strictly behavioral (such as {@link ngClick}), and which
  6611. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6612. *
  6613. * #### `priority`
  6614. * When there are multiple directives defined on a single DOM element, sometimes it
  6615. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6616. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6617. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6618. * are also run in priority order, but post-link functions are run in reverse order. The order
  6619. * of directives with the same priority is undefined. The default priority is `0`.
  6620. *
  6621. * #### `terminal`
  6622. * If set to true then the current `priority` will be the last set of directives
  6623. * which will execute (any directives at the current priority will still execute
  6624. * as the order of execution on same `priority` is undefined). Note that expressions
  6625. * and other directives used in the directive's template will also be excluded from execution.
  6626. *
  6627. * #### `scope`
  6628. * The scope property can be `false`, `true`, or an object:
  6629. *
  6630. * * **`false` (default):** No scope will be created for the directive. The directive will use its
  6631. * parent's scope.
  6632. *
  6633. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6634. * the directive's element. If multiple directives on the same element request a new scope,
  6635. * only one new scope is created.
  6636. *
  6637. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template.
  6638. * The 'isolate' scope differs from normal scope in that it does not prototypically
  6639. * inherit from its parent scope. This is useful when creating reusable components, which should not
  6640. * accidentally read or modify data in the parent scope. Note that an isolate scope
  6641. * directive without a `template` or `templateUrl` will not apply the isolate scope
  6642. * to its children elements.
  6643. *
  6644. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6645. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6646. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6647. * is bound to the parent scope, via matching attributes on the directive's element:
  6648. *
  6649. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6650. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6651. * attribute name is assumed to be the same as the local name. Given `<my-component
  6652. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6653. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6654. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6655. * scope. The `name` is read from the parent scope (not the directive's scope).
  6656. *
  6657. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6658. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6659. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6660. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6661. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6662. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6663. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6664. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6665. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6666. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6667. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6668. * method is used for tracking changes, and the equality check is based on object identity.
  6669. * However, if an object literal or an array literal is passed as the binding expression, the
  6670. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6671. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6672. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6673. *
  6674. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6675. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6676. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6677. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6678. *
  6679. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6680. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6681. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6682. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6683. * two caveats:
  6684. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6685. * sets the same value. That means if your bound value is an object, changes to its properties
  6686. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6687. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6688. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6689. * to the value has changed. In most cases, this should not be of concern, but can be important
  6690. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6691. * If you now change a property of the object in your parent scope, the change will not be
  6692. * propagated to the isolated scope, because the identity of the object on the parent scope
  6693. * has not changed. Instead you must assign a new object.
  6694. *
  6695. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6696. * back to the parent. However, it does not make this completely impossible.
  6697. *
  6698. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6699. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6700. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6701. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6702. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6703. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6704. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6705. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6706. *
  6707. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6708. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6709. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6710. *
  6711. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6712. * * **child scope** + **no scope** => Both directives will share one single child scope
  6713. * * **child scope** + **child scope** => Both directives will share one single child scope
  6714. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6715. * its parent's scope
  6716. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6717. * be applied to the same element.
  6718. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6719. * cannot be applied to the same element.
  6720. *
  6721. *
  6722. * #### `bindToController`
  6723. * This property is used to bind scope properties directly to the controller. It can be either
  6724. * `true` or an object hash with the same format as the `scope` property.
  6725. *
  6726. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6727. * allow a component to have its properties bound to the controller, rather than to scope.
  6728. *
  6729. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6730. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6731. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6732. * initialized.
  6733. *
  6734. * <div class="alert alert-warning">
  6735. * **Deprecation warning:** if `$compileProcvider.preAssignBindingsEnabled(true)` was called, bindings for non-ES6 class
  6736. * controllers are bound to `this` before the controller constructor is called but this use is now deprecated. Please
  6737. * place initialization code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6738. * </div>
  6739. *
  6740. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6741. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6742. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6743. * scope (useful for component directives).
  6744. *
  6745. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6746. *
  6747. *
  6748. * #### `controller`
  6749. * Controller constructor function. The controller is instantiated before the
  6750. * pre-linking phase and can be accessed by other directives (see
  6751. * `require` attribute). This allows the directives to communicate with each other and augment
  6752. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6753. *
  6754. * * `$scope` - Current scope associated with the element
  6755. * * `$element` - Current element
  6756. * * `$attrs` - Current attributes object for the element
  6757. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6758. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6759. * * `scope`: (optional) override the scope.
  6760. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6761. * * `futureParentElement` (optional):
  6762. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6763. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6764. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6765. * and when the `cloneLinkingFn` is passed,
  6766. * as those elements need to created and cloned in a special way when they are defined outside their
  6767. * usual containers (e.g. like `<svg>`).
  6768. * * See also the `directive.templateNamespace` property.
  6769. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6770. * then the default transclusion is provided.
  6771. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6772. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6773. *
  6774. * #### `require`
  6775. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6776. * `require` property can be a string, an array or an object:
  6777. * * a **string** containing the name of the directive to pass to the linking function
  6778. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6779. * linking function will be an array of controllers in the same order as the names in the `require` property
  6780. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6781. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6782. * controllers.
  6783. *
  6784. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6785. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6786. * have been constructed but before `$onInit` is called.
  6787. * If the name of the required controller is the same as the local name (the key), the name can be
  6788. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  6789. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6790. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6791. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6792. * controller, in which case error checking is skipped). The name can be prefixed with:
  6793. *
  6794. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6795. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6796. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6797. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6798. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6799. * `null` to the `link` fn if not found.
  6800. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6801. * `null` to the `link` fn if not found.
  6802. *
  6803. *
  6804. * #### `controllerAs`
  6805. * Identifier name for a reference to the controller in the directive's scope.
  6806. * This allows the controller to be referenced from the directive template. This is especially
  6807. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6808. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6809. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6810. *
  6811. *
  6812. * #### `restrict`
  6813. * String of subset of `EACM` which restricts the directive to a specific directive
  6814. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6815. *
  6816. * * `E` - Element name (default): `<my-directive></my-directive>`
  6817. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6818. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6819. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6820. *
  6821. *
  6822. * #### `templateNamespace`
  6823. * String representing the document type used by the markup in the template.
  6824. * AngularJS needs this information as those elements need to be created and cloned
  6825. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6826. *
  6827. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6828. * top-level elements such as `<svg>` or `<math>`.
  6829. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6830. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6831. *
  6832. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6833. *
  6834. * #### `template`
  6835. * HTML markup that may:
  6836. * * Replace the contents of the directive's element (default).
  6837. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6838. * * Wrap the contents of the directive's element (if `transclude` is true).
  6839. *
  6840. * Value may be:
  6841. *
  6842. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6843. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6844. * function api below) and returns a string value.
  6845. *
  6846. *
  6847. * #### `templateUrl`
  6848. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6849. *
  6850. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6851. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6852. * sibling and parent elements as though this element had not contained any directives.
  6853. *
  6854. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6855. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6856. * case when only one deeply nested directive has `templateUrl`.
  6857. *
  6858. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6859. *
  6860. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6861. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6862. * a string value representing the url. In either case, the template URL is passed through {@link
  6863. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6864. *
  6865. *
  6866. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  6867. * specify what the template should replace. Defaults to `false`.
  6868. *
  6869. * * `true` - the template will replace the directive's element.
  6870. * * `false` - the template will replace the contents of the directive's element.
  6871. *
  6872. * The replacement process migrates all of the attributes / classes from the old element to the new
  6873. * one. See the {@link guide/directive#template-expanding-directive
  6874. * Directives Guide} for an example.
  6875. *
  6876. * There are very few scenarios where element replacement is required for the application function,
  6877. * the main one being reusable custom components that are used within SVG contexts
  6878. * (because SVG doesn't work with custom elements in the DOM tree).
  6879. *
  6880. * #### `transclude`
  6881. * Extract the contents of the element where the directive appears and make it available to the directive.
  6882. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6883. * {@link $compile#transclusion Transclusion} section below.
  6884. *
  6885. *
  6886. * #### `compile`
  6887. *
  6888. * ```js
  6889. * function compile(tElement, tAttrs, transclude) { ... }
  6890. * ```
  6891. *
  6892. * The compile function deals with transforming the template DOM. Since most directives do not do
  6893. * template transformation, it is not used often. The compile function takes the following arguments:
  6894. *
  6895. * * `tElement` - template element - The element where the directive has been declared. It is
  6896. * safe to do template transformation on the element and child elements only.
  6897. *
  6898. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6899. * between all directive compile functions.
  6900. *
  6901. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6902. *
  6903. * <div class="alert alert-warning">
  6904. * **Note:** The template instance and the link instance may be different objects if the template has
  6905. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6906. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6907. * should be done in a linking function rather than in a compile function.
  6908. * </div>
  6909. * <div class="alert alert-warning">
  6910. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6911. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6912. * stack overflow errors.
  6913. *
  6914. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6915. * a directive's template instead of relying on automatic template compilation via `template` or
  6916. * `templateUrl` declaration or manual compilation inside the compile function.
  6917. * </div>
  6918. *
  6919. * <div class="alert alert-danger">
  6920. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6921. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6922. * to the link function instead.
  6923. * </div>
  6924. * A compile function can have a return value which can be either a function or an object.
  6925. *
  6926. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6927. * `link` property of the config object when the compile function is empty.
  6928. *
  6929. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6930. * control when a linking function should be called during the linking phase. See info about
  6931. * pre-linking and post-linking functions below.
  6932. *
  6933. *
  6934. * #### `link`
  6935. * This property is used only if the `compile` property is not defined.
  6936. *
  6937. * ```js
  6938. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6939. * ```
  6940. *
  6941. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6942. * executed after the template has been cloned. This is where most of the directive logic will be
  6943. * put.
  6944. *
  6945. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6946. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6947. *
  6948. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6949. * manipulate the children of the element only in `postLink` function since the children have
  6950. * already been linked.
  6951. *
  6952. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6953. * between all directive linking functions.
  6954. *
  6955. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6956. * among all directives, which allows the directives to use the controllers as a communication
  6957. * channel. The exact value depends on the directive's `require` property:
  6958. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6959. * * `string`: the controller instance
  6960. * * `array`: array of controller instances
  6961. *
  6962. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6963. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6964. *
  6965. * Note that you can also require the directive's own controller - it will be made available like
  6966. * any other controller.
  6967. *
  6968. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6969. * This is the same as the `$transclude` parameter of directive controllers,
  6970. * see {@link ng.$compile#-controller- the controller section for details}.
  6971. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6972. *
  6973. * #### Pre-linking function
  6974. *
  6975. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6976. * compiler linking function will fail to locate the correct elements for linking.
  6977. *
  6978. * #### Post-linking function
  6979. *
  6980. * Executed after the child elements are linked.
  6981. *
  6982. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6983. * and linked since they are waiting for their template to load asynchronously and their own
  6984. * compilation and linking has been suspended until that occurs.
  6985. *
  6986. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6987. * for their async templates to be resolved.
  6988. *
  6989. *
  6990. * ### Transclusion
  6991. *
  6992. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6993. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6994. * scope from where they were taken.
  6995. *
  6996. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6997. * original contents of a directive's element into a specified place in the template of the directive.
  6998. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6999. * content has access to the properties on the scope from which it was taken, even if the directive
  7000. * has isolated scope.
  7001. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  7002. *
  7003. * This makes it possible for the widget to have private state for its template, while the transcluded
  7004. * content has access to its originating scope.
  7005. *
  7006. * <div class="alert alert-warning">
  7007. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  7008. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  7009. * Testing Transclusion Directives}.
  7010. * </div>
  7011. *
  7012. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  7013. * directive's element, the entire element or multiple parts of the element contents:
  7014. *
  7015. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  7016. * * `'element'` - transclude the whole of the directive's element including any directives on this
  7017. * element that defined at a lower priority than this directive. When used, the `template`
  7018. * property is ignored.
  7019. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  7020. *
  7021. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  7022. *
  7023. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  7024. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  7025. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  7026. *
  7027. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7028. *
  7029. * If the element selector is prefixed with a `?` then that slot is optional.
  7030. *
  7031. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  7032. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  7033. *
  7034. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  7035. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  7036. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  7037. * injectable into the directive's controller.
  7038. *
  7039. *
  7040. * #### Transclusion Functions
  7041. *
  7042. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  7043. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  7044. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  7045. *
  7046. * <div class="alert alert-info">
  7047. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  7048. * ngTransclude will deal with it for us.
  7049. * </div>
  7050. *
  7051. * If you want to manually control the insertion and removal of the transcluded content in your directive
  7052. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  7053. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  7054. *
  7055. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  7056. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  7057. * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
  7058. *
  7059. * <div class="alert alert-info">
  7060. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  7061. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  7062. * </div>
  7063. *
  7064. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  7065. * attach function**:
  7066. *
  7067. * ```js
  7068. * var transcludedContent, transclusionScope;
  7069. *
  7070. * $transclude(function(clone, scope) {
  7071. * element.append(clone);
  7072. * transcludedContent = clone;
  7073. * transclusionScope = scope;
  7074. * });
  7075. * ```
  7076. *
  7077. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  7078. * associated transclusion scope:
  7079. *
  7080. * ```js
  7081. * transcludedContent.remove();
  7082. * transclusionScope.$destroy();
  7083. * ```
  7084. *
  7085. * <div class="alert alert-info">
  7086. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  7087. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  7088. * then you are also responsible for calling `$destroy` on the transclusion scope.
  7089. * </div>
  7090. *
  7091. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  7092. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  7093. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  7094. *
  7095. *
  7096. * #### Transclusion Scopes
  7097. *
  7098. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  7099. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  7100. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  7101. * was taken.
  7102. *
  7103. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  7104. * like this:
  7105. *
  7106. * ```html
  7107. * <div ng-app>
  7108. * <div isolate>
  7109. * <div transclusion>
  7110. * </div>
  7111. * </div>
  7112. * </div>
  7113. * ```
  7114. *
  7115. * The `$parent` scope hierarchy will look like this:
  7116. *
  7117. ```
  7118. - $rootScope
  7119. - isolate
  7120. - transclusion
  7121. ```
  7122. *
  7123. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  7124. *
  7125. ```
  7126. - $rootScope
  7127. - transclusion
  7128. - isolate
  7129. ```
  7130. *
  7131. *
  7132. * ### Attributes
  7133. *
  7134. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  7135. * `link()` or `compile()` functions. It has a variety of uses.
  7136. *
  7137. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  7138. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  7139. * to the attributes.
  7140. *
  7141. * * *Directive inter-communication:* All directives share the same instance of the attributes
  7142. * object which allows the directives to use the attributes object as inter directive
  7143. * communication.
  7144. *
  7145. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  7146. * allowing other directives to read the interpolated value.
  7147. *
  7148. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  7149. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  7150. * the only way to easily get the actual value because during the linking phase the interpolation
  7151. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  7152. *
  7153. * ```js
  7154. * function linkingFn(scope, elm, attrs, ctrl) {
  7155. * // get the attribute value
  7156. * console.log(attrs.ngModel);
  7157. *
  7158. * // change the attribute
  7159. * attrs.$set('ngModel', 'new value');
  7160. *
  7161. * // observe changes to interpolated attribute
  7162. * attrs.$observe('ngModel', function(value) {
  7163. * console.log('ngModel has changed value to ' + value);
  7164. * });
  7165. * }
  7166. * ```
  7167. *
  7168. * ## Example
  7169. *
  7170. * <div class="alert alert-warning">
  7171. * **Note**: Typically directives are registered with `module.directive`. The example below is
  7172. * to illustrate how `$compile` works.
  7173. * </div>
  7174. *
  7175. <example module="compileExample" name="compile">
  7176. <file name="index.html">
  7177. <script>
  7178. angular.module('compileExample', [], function($compileProvider) {
  7179. // configure new 'compile' directive by passing a directive
  7180. // factory function. The factory function injects the '$compile'
  7181. $compileProvider.directive('compile', function($compile) {
  7182. // directive factory creates a link function
  7183. return function(scope, element, attrs) {
  7184. scope.$watch(
  7185. function(scope) {
  7186. // watch the 'compile' expression for changes
  7187. return scope.$eval(attrs.compile);
  7188. },
  7189. function(value) {
  7190. // when the 'compile' expression changes
  7191. // assign it into the current DOM
  7192. element.html(value);
  7193. // compile the new DOM and link it to the current
  7194. // scope.
  7195. // NOTE: we only compile .childNodes so that
  7196. // we don't get into infinite loop compiling ourselves
  7197. $compile(element.contents())(scope);
  7198. }
  7199. );
  7200. };
  7201. });
  7202. })
  7203. .controller('GreeterController', ['$scope', function($scope) {
  7204. $scope.name = 'Angular';
  7205. $scope.html = 'Hello {{name}}';
  7206. }]);
  7207. </script>
  7208. <div ng-controller="GreeterController">
  7209. <input ng-model="name"> <br/>
  7210. <textarea ng-model="html"></textarea> <br/>
  7211. <div compile="html"></div>
  7212. </div>
  7213. </file>
  7214. <file name="protractor.js" type="protractor">
  7215. it('should auto compile', function() {
  7216. var textarea = $('textarea');
  7217. var output = $('div[compile]');
  7218. // The initial state reads 'Hello Angular'.
  7219. expect(output.getText()).toBe('Hello Angular');
  7220. textarea.clear();
  7221. textarea.sendKeys('{{name}}!');
  7222. expect(output.getText()).toBe('Angular!');
  7223. });
  7224. </file>
  7225. </example>
  7226. *
  7227. *
  7228. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  7229. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  7230. *
  7231. * <div class="alert alert-danger">
  7232. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  7233. * e.g. will not use the right outer scope. Please pass the transclude function as a
  7234. * `parentBoundTranscludeFn` to the link function instead.
  7235. * </div>
  7236. *
  7237. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  7238. * root element(s), not their children)
  7239. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  7240. * (a DOM element/tree) to a scope. Where:
  7241. *
  7242. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  7243. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  7244. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  7245. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  7246. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  7247. *
  7248. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  7249. * * `scope` - is the current scope with which the linking function is working with.
  7250. *
  7251. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  7252. * keys may be used to control linking behavior:
  7253. *
  7254. * * `parentBoundTranscludeFn` - the transclude function made available to
  7255. * directives; if given, it will be passed through to the link functions of
  7256. * directives found in `element` during compilation.
  7257. * * `transcludeControllers` - an object hash with keys that map controller names
  7258. * to a hash with the key `instance`, which maps to the controller instance;
  7259. * if given, it will make the controllers available to directives on the compileNode:
  7260. * ```
  7261. * {
  7262. * parent: {
  7263. * instance: parentControllerInstance
  7264. * }
  7265. * }
  7266. * ```
  7267. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  7268. * the cloned elements; only needed for transcludes that are allowed to contain non html
  7269. * elements (e.g. SVG elements). See also the directive.controller property.
  7270. *
  7271. * Calling the linking function returns the element of the template. It is either the original
  7272. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  7273. *
  7274. * After linking the view is not updated until after a call to $digest which typically is done by
  7275. * Angular automatically.
  7276. *
  7277. * If you need access to the bound view, there are two ways to do it:
  7278. *
  7279. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  7280. * before you send them to the compiler and keep this reference around.
  7281. * ```js
  7282. * var element = $compile('<p>{{total}}</p>')(scope);
  7283. * ```
  7284. *
  7285. * - if on the other hand, you need the element to be cloned, the view reference from the original
  7286. * example would not point to the clone, but rather to the original template that was cloned. In
  7287. * this case, you can access the clone via the cloneAttachFn:
  7288. * ```js
  7289. * var templateElement = angular.element('<p>{{total}}</p>'),
  7290. * scope = ....;
  7291. *
  7292. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  7293. * //attach the clone to DOM document at the right place
  7294. * });
  7295. *
  7296. * //now we have reference to the cloned DOM via `clonedElement`
  7297. * ```
  7298. *
  7299. *
  7300. * For information on how the compiler works, see the
  7301. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  7302. *
  7303. * @knownIssue
  7304. *
  7305. * ### Double Compilation
  7306. *
  7307. Double compilation occurs when an already compiled part of the DOM gets
  7308. compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,
  7309. and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it
  7310. section on double compilation} for an in-depth explanation and ways to avoid it.
  7311. *
  7312. */
  7313. var $compileMinErr = minErr('$compile');
  7314. function UNINITIALIZED_VALUE() {}
  7315. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  7316. /**
  7317. * @ngdoc provider
  7318. * @name $compileProvider
  7319. *
  7320. * @description
  7321. */
  7322. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  7323. /** @this */
  7324. function $CompileProvider($provide, $$sanitizeUriProvider) {
  7325. var hasDirectives = {},
  7326. Suffix = 'Directive',
  7327. COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/,
  7328. CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,
  7329. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  7330. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  7331. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  7332. // The assumption is that future DOM event attribute names will begin with
  7333. // 'on' and be composed of only English letters.
  7334. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  7335. var bindingCache = createMap();
  7336. function parseIsolateBindings(scope, directiveName, isController) {
  7337. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*([\w$]*)\s*$/;
  7338. var bindings = createMap();
  7339. forEach(scope, function(definition, scopeName) {
  7340. if (definition in bindingCache) {
  7341. bindings[scopeName] = bindingCache[definition];
  7342. return;
  7343. }
  7344. var match = definition.match(LOCAL_REGEXP);
  7345. if (!match) {
  7346. throw $compileMinErr('iscp',
  7347. 'Invalid {3} for directive \'{0}\'.' +
  7348. ' Definition: {... {1}: \'{2}\' ...}',
  7349. directiveName, scopeName, definition,
  7350. (isController ? 'controller bindings definition' :
  7351. 'isolate scope definition'));
  7352. }
  7353. bindings[scopeName] = {
  7354. mode: match[1][0],
  7355. collection: match[2] === '*',
  7356. optional: match[3] === '?',
  7357. attrName: match[4] || scopeName
  7358. };
  7359. if (match[4]) {
  7360. bindingCache[definition] = bindings[scopeName];
  7361. }
  7362. });
  7363. return bindings;
  7364. }
  7365. function parseDirectiveBindings(directive, directiveName) {
  7366. var bindings = {
  7367. isolateScope: null,
  7368. bindToController: null
  7369. };
  7370. if (isObject(directive.scope)) {
  7371. if (directive.bindToController === true) {
  7372. bindings.bindToController = parseIsolateBindings(directive.scope,
  7373. directiveName, true);
  7374. bindings.isolateScope = {};
  7375. } else {
  7376. bindings.isolateScope = parseIsolateBindings(directive.scope,
  7377. directiveName, false);
  7378. }
  7379. }
  7380. if (isObject(directive.bindToController)) {
  7381. bindings.bindToController =
  7382. parseIsolateBindings(directive.bindToController, directiveName, true);
  7383. }
  7384. if (bindings.bindToController && !directive.controller) {
  7385. // There is no controller
  7386. throw $compileMinErr('noctrl',
  7387. 'Cannot bind to controller without directive \'{0}\'s controller.',
  7388. directiveName);
  7389. }
  7390. return bindings;
  7391. }
  7392. function assertValidDirectiveName(name) {
  7393. var letter = name.charAt(0);
  7394. if (!letter || letter !== lowercase(letter)) {
  7395. throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
  7396. }
  7397. if (name !== name.trim()) {
  7398. throw $compileMinErr('baddir',
  7399. 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
  7400. name);
  7401. }
  7402. }
  7403. function getDirectiveRequire(directive) {
  7404. var require = directive.require || (directive.controller && directive.name);
  7405. if (!isArray(require) && isObject(require)) {
  7406. forEach(require, function(value, key) {
  7407. var match = value.match(REQUIRE_PREFIX_REGEXP);
  7408. var name = value.substring(match[0].length);
  7409. if (!name) require[key] = match[0] + key;
  7410. });
  7411. }
  7412. return require;
  7413. }
  7414. function getDirectiveRestrict(restrict, name) {
  7415. if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
  7416. throw $compileMinErr('badrestrict',
  7417. 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
  7418. restrict,
  7419. name);
  7420. }
  7421. return restrict || 'EA';
  7422. }
  7423. /**
  7424. * @ngdoc method
  7425. * @name $compileProvider#directive
  7426. * @kind function
  7427. *
  7428. * @description
  7429. * Register a new directive with the compiler.
  7430. *
  7431. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  7432. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  7433. * names and the values are the factories.
  7434. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  7435. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  7436. * @returns {ng.$compileProvider} Self for chaining.
  7437. */
  7438. this.directive = function registerDirective(name, directiveFactory) {
  7439. assertArg(name, 'name');
  7440. assertNotHasOwnProperty(name, 'directive');
  7441. if (isString(name)) {
  7442. assertValidDirectiveName(name);
  7443. assertArg(directiveFactory, 'directiveFactory');
  7444. if (!hasDirectives.hasOwnProperty(name)) {
  7445. hasDirectives[name] = [];
  7446. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  7447. function($injector, $exceptionHandler) {
  7448. var directives = [];
  7449. forEach(hasDirectives[name], function(directiveFactory, index) {
  7450. try {
  7451. var directive = $injector.invoke(directiveFactory);
  7452. if (isFunction(directive)) {
  7453. directive = { compile: valueFn(directive) };
  7454. } else if (!directive.compile && directive.link) {
  7455. directive.compile = valueFn(directive.link);
  7456. }
  7457. directive.priority = directive.priority || 0;
  7458. directive.index = index;
  7459. directive.name = directive.name || name;
  7460. directive.require = getDirectiveRequire(directive);
  7461. directive.restrict = getDirectiveRestrict(directive.restrict, name);
  7462. directive.$$moduleName = directiveFactory.$$moduleName;
  7463. directives.push(directive);
  7464. } catch (e) {
  7465. $exceptionHandler(e);
  7466. }
  7467. });
  7468. return directives;
  7469. }]);
  7470. }
  7471. hasDirectives[name].push(directiveFactory);
  7472. } else {
  7473. forEach(name, reverseParams(registerDirective));
  7474. }
  7475. return this;
  7476. };
  7477. /**
  7478. * @ngdoc method
  7479. * @name $compileProvider#component
  7480. * @module ng
  7481. * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`),
  7482. * or an object map of components where the keys are the names and the values are the component definition objects.
  7483. * @param {Object} options Component definition object (a simplified
  7484. * {@link ng.$compile#directive-definition-object directive definition object}),
  7485. * with the following properties (all optional):
  7486. *
  7487. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  7488. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  7489. * registered controller} if passed as a string. An empty `noop` function by default.
  7490. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  7491. * If present, the controller will be published to scope under the `controllerAs` name.
  7492. * If not present, this will default to be `$ctrl`.
  7493. * - `template` – `{string=|function()=}` – html template as a string or a function that
  7494. * returns an html template as a string which should be used as the contents of this component.
  7495. * Empty string by default.
  7496. *
  7497. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  7498. * the following locals:
  7499. *
  7500. * - `$element` - Current element
  7501. * - `$attrs` - Current attributes object for the element
  7502. *
  7503. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  7504. * template that should be used as the contents of this component.
  7505. *
  7506. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  7507. * the following locals:
  7508. *
  7509. * - `$element` - Current element
  7510. * - `$attrs` - Current attributes object for the element
  7511. *
  7512. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  7513. * Component properties are always bound to the component controller and not to the scope.
  7514. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  7515. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  7516. * Disabled by default.
  7517. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  7518. * this component's controller. The object keys specify the property names under which the required
  7519. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  7520. * - `$...` – additional properties to attach to the directive factory function and the controller
  7521. * constructor function. (This is used by the component router to annotate)
  7522. *
  7523. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  7524. * @description
  7525. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  7526. * type of directive, which represents a self-contained UI component in your application. Such components
  7527. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  7528. *
  7529. * Component definitions are very simple and do not require as much configuration as defining general
  7530. * directives. Component definitions usually consist only of a template and a controller backing it.
  7531. *
  7532. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  7533. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  7534. *
  7535. * Here are a few examples of how you would usually define components:
  7536. *
  7537. * ```js
  7538. * var myMod = angular.module(...);
  7539. * myMod.component('myComp', {
  7540. * template: '<div>My name is {{$ctrl.name}}</div>',
  7541. * controller: function() {
  7542. * this.name = 'shahar';
  7543. * }
  7544. * });
  7545. *
  7546. * myMod.component('myComp', {
  7547. * template: '<div>My name is {{$ctrl.name}}</div>',
  7548. * bindings: {name: '@'}
  7549. * });
  7550. *
  7551. * myMod.component('myComp', {
  7552. * templateUrl: 'views/my-comp.html',
  7553. * controller: 'MyCtrl',
  7554. * controllerAs: 'ctrl',
  7555. * bindings: {name: '@'}
  7556. * });
  7557. *
  7558. * ```
  7559. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  7560. *
  7561. * <br />
  7562. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  7563. */
  7564. this.component = function registerComponent(name, options) {
  7565. if (!isString(name)) {
  7566. forEach(name, reverseParams(bind(this, registerComponent)));
  7567. return this;
  7568. }
  7569. var controller = options.controller || function() {};
  7570. function factory($injector) {
  7571. function makeInjectable(fn) {
  7572. if (isFunction(fn) || isArray(fn)) {
  7573. return /** @this */ function(tElement, tAttrs) {
  7574. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  7575. };
  7576. } else {
  7577. return fn;
  7578. }
  7579. }
  7580. var template = (!options.template && !options.templateUrl ? '' : options.template);
  7581. var ddo = {
  7582. controller: controller,
  7583. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  7584. template: makeInjectable(template),
  7585. templateUrl: makeInjectable(options.templateUrl),
  7586. transclude: options.transclude,
  7587. scope: {},
  7588. bindToController: options.bindings || {},
  7589. restrict: 'E',
  7590. require: options.require
  7591. };
  7592. // Copy annotations (starting with $) over to the DDO
  7593. forEach(options, function(val, key) {
  7594. if (key.charAt(0) === '$') ddo[key] = val;
  7595. });
  7596. return ddo;
  7597. }
  7598. // TODO(pete) remove the following `forEach` before we release 1.6.0
  7599. // The component-router@0.2.0 looks for the annotations on the controller constructor
  7600. // Nothing in Angular looks for annotations on the factory function but we can't remove
  7601. // it from 1.5.x yet.
  7602. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  7603. // These could be used by libraries such as the new component router
  7604. forEach(options, function(val, key) {
  7605. if (key.charAt(0) === '$') {
  7606. factory[key] = val;
  7607. // Don't try to copy over annotations to named controller
  7608. if (isFunction(controller)) controller[key] = val;
  7609. }
  7610. });
  7611. factory.$inject = ['$injector'];
  7612. return this.directive(name, factory);
  7613. };
  7614. /**
  7615. * @ngdoc method
  7616. * @name $compileProvider#aHrefSanitizationWhitelist
  7617. * @kind function
  7618. *
  7619. * @description
  7620. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7621. * urls during a[href] sanitization.
  7622. *
  7623. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  7624. *
  7625. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  7626. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  7627. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7628. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7629. *
  7630. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7631. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7632. * chaining otherwise.
  7633. */
  7634. this.aHrefSanitizationWhitelist = function(regexp) {
  7635. if (isDefined(regexp)) {
  7636. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  7637. return this;
  7638. } else {
  7639. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  7640. }
  7641. };
  7642. /**
  7643. * @ngdoc method
  7644. * @name $compileProvider#imgSrcSanitizationWhitelist
  7645. * @kind function
  7646. *
  7647. * @description
  7648. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7649. * urls during img[src] sanitization.
  7650. *
  7651. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  7652. *
  7653. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  7654. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  7655. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7656. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7657. *
  7658. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7659. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7660. * chaining otherwise.
  7661. */
  7662. this.imgSrcSanitizationWhitelist = function(regexp) {
  7663. if (isDefined(regexp)) {
  7664. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  7665. return this;
  7666. } else {
  7667. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  7668. }
  7669. };
  7670. /**
  7671. * @ngdoc method
  7672. * @name $compileProvider#debugInfoEnabled
  7673. *
  7674. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  7675. * current debugInfoEnabled state
  7676. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7677. *
  7678. * @kind function
  7679. *
  7680. * @description
  7681. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7682. * binding information and a reference to the current scope on to DOM elements.
  7683. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7684. * * `ng-binding` CSS class
  7685. * * `$binding` data property containing an array of the binding expressions
  7686. *
  7687. * You may want to disable this in production for a significant performance boost. See
  7688. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7689. *
  7690. * The default value is true.
  7691. */
  7692. var debugInfoEnabled = true;
  7693. this.debugInfoEnabled = function(enabled) {
  7694. if (isDefined(enabled)) {
  7695. debugInfoEnabled = enabled;
  7696. return this;
  7697. }
  7698. return debugInfoEnabled;
  7699. };
  7700. /**
  7701. * @ngdoc method
  7702. * @name $compileProvider#preAssignBindingsEnabled
  7703. *
  7704. * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the
  7705. * current preAssignBindingsEnabled state
  7706. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7707. *
  7708. * @kind function
  7709. *
  7710. * @description
  7711. * Call this method to enable/disable whether directive controllers are assigned bindings before
  7712. * calling the controller's constructor.
  7713. * If enabled (true), the compiler assigns the value of each of the bindings to the
  7714. * properties of the controller object before the constructor of this object is called.
  7715. *
  7716. * If disabled (false), the compiler calls the constructor first before assigning bindings.
  7717. *
  7718. * The default value is false.
  7719. *
  7720. * @deprecated
  7721. * sinceVersion="1.6.0"
  7722. * removeVersion="1.7.0"
  7723. *
  7724. * This method and the option to assign the bindings before calling the controller's constructor
  7725. * will be removed in v1.7.0.
  7726. */
  7727. var preAssignBindingsEnabled = false;
  7728. this.preAssignBindingsEnabled = function(enabled) {
  7729. if (isDefined(enabled)) {
  7730. preAssignBindingsEnabled = enabled;
  7731. return this;
  7732. }
  7733. return preAssignBindingsEnabled;
  7734. };
  7735. /**
  7736. * @ngdoc method
  7737. * @name $compileProvider#strictComponentBindingsEnabled
  7738. *
  7739. * @param {boolean=} enabled update the strictComponentBindingsEnabled state if provided, otherwise just return the
  7740. * current strictComponentBindingsEnabled state
  7741. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7742. *
  7743. * @kind function
  7744. *
  7745. * @description
  7746. * Call this method to enable/disable strict component bindings check. If enabled, the compiler will enforce that
  7747. * for all bindings of a component that are not set as optional with `?`, an attribute needs to be provided
  7748. * on the component's HTML tag.
  7749. *
  7750. * The default value is false.
  7751. */
  7752. var strictComponentBindingsEnabled = false;
  7753. this.strictComponentBindingsEnabled = function(enabled) {
  7754. if (isDefined(enabled)) {
  7755. strictComponentBindingsEnabled = enabled;
  7756. return this;
  7757. }
  7758. return strictComponentBindingsEnabled;
  7759. };
  7760. var TTL = 10;
  7761. /**
  7762. * @ngdoc method
  7763. * @name $compileProvider#onChangesTtl
  7764. * @description
  7765. *
  7766. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  7767. * assuming that the model is unstable.
  7768. *
  7769. * The current default is 10 iterations.
  7770. *
  7771. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  7772. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  7773. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  7774. * the `$onChanges` hook execution.
  7775. *
  7776. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  7777. *
  7778. * @param {number} limit The number of `$onChanges` hook iterations.
  7779. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  7780. */
  7781. this.onChangesTtl = function(value) {
  7782. if (arguments.length) {
  7783. TTL = value;
  7784. return this;
  7785. }
  7786. return TTL;
  7787. };
  7788. var commentDirectivesEnabledConfig = true;
  7789. /**
  7790. * @ngdoc method
  7791. * @name $compileProvider#commentDirectivesEnabled
  7792. * @description
  7793. *
  7794. * It indicates to the compiler
  7795. * whether or not directives on comments should be compiled.
  7796. * Defaults to `true`.
  7797. *
  7798. * Calling this function with false disables the compilation of directives
  7799. * on comments for the whole application.
  7800. * This results in a compilation performance gain,
  7801. * as the compiler doesn't have to check comments when looking for directives.
  7802. * This should however only be used if you are sure that no comment directives are used in
  7803. * the application (including any 3rd party directives).
  7804. *
  7805. * @param {boolean} enabled `false` if the compiler may ignore directives on comments
  7806. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7807. */
  7808. this.commentDirectivesEnabled = function(value) {
  7809. if (arguments.length) {
  7810. commentDirectivesEnabledConfig = value;
  7811. return this;
  7812. }
  7813. return commentDirectivesEnabledConfig;
  7814. };
  7815. var cssClassDirectivesEnabledConfig = true;
  7816. /**
  7817. * @ngdoc method
  7818. * @name $compileProvider#cssClassDirectivesEnabled
  7819. * @description
  7820. *
  7821. * It indicates to the compiler
  7822. * whether or not directives on element classes should be compiled.
  7823. * Defaults to `true`.
  7824. *
  7825. * Calling this function with false disables the compilation of directives
  7826. * on element classes for the whole application.
  7827. * This results in a compilation performance gain,
  7828. * as the compiler doesn't have to check element classes when looking for directives.
  7829. * This should however only be used if you are sure that no class directives are used in
  7830. * the application (including any 3rd party directives).
  7831. *
  7832. * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
  7833. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7834. */
  7835. this.cssClassDirectivesEnabled = function(value) {
  7836. if (arguments.length) {
  7837. cssClassDirectivesEnabledConfig = value;
  7838. return this;
  7839. }
  7840. return cssClassDirectivesEnabledConfig;
  7841. };
  7842. this.$get = [
  7843. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7844. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7845. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7846. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7847. var SIMPLE_ATTR_NAME = /^\w/;
  7848. var specialAttrHolder = window.document.createElement('div');
  7849. var commentDirectivesEnabled = commentDirectivesEnabledConfig;
  7850. var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
  7851. var onChangesTtl = TTL;
  7852. // The onChanges hooks should all be run together in a single digest
  7853. // When changes occur, the call to trigger their hooks will be added to this queue
  7854. var onChangesQueue;
  7855. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  7856. function flushOnChangesQueue() {
  7857. try {
  7858. if (!(--onChangesTtl)) {
  7859. // We have hit the TTL limit so reset everything
  7860. onChangesQueue = undefined;
  7861. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  7862. }
  7863. // We must run this hook in an apply since the $$postDigest runs outside apply
  7864. $rootScope.$apply(function() {
  7865. var errors = [];
  7866. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  7867. try {
  7868. onChangesQueue[i]();
  7869. } catch (e) {
  7870. errors.push(e);
  7871. }
  7872. }
  7873. // Reset the queue to trigger a new schedule next time there is a change
  7874. onChangesQueue = undefined;
  7875. if (errors.length) {
  7876. throw errors;
  7877. }
  7878. });
  7879. } finally {
  7880. onChangesTtl++;
  7881. }
  7882. }
  7883. function Attributes(element, attributesToCopy) {
  7884. if (attributesToCopy) {
  7885. var keys = Object.keys(attributesToCopy);
  7886. var i, l, key;
  7887. for (i = 0, l = keys.length; i < l; i++) {
  7888. key = keys[i];
  7889. this[key] = attributesToCopy[key];
  7890. }
  7891. } else {
  7892. this.$attr = {};
  7893. }
  7894. this.$$element = element;
  7895. }
  7896. Attributes.prototype = {
  7897. /**
  7898. * @ngdoc method
  7899. * @name $compile.directive.Attributes#$normalize
  7900. * @kind function
  7901. *
  7902. * @description
  7903. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7904. * `data-`) to its normalized, camelCase form.
  7905. *
  7906. * Also there is special case for Moz prefix starting with upper case letter.
  7907. *
  7908. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7909. *
  7910. * @param {string} name Name to normalize
  7911. */
  7912. $normalize: directiveNormalize,
  7913. /**
  7914. * @ngdoc method
  7915. * @name $compile.directive.Attributes#$addClass
  7916. * @kind function
  7917. *
  7918. * @description
  7919. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7920. * are enabled then an animation will be triggered for the class addition.
  7921. *
  7922. * @param {string} classVal The className value that will be added to the element
  7923. */
  7924. $addClass: function(classVal) {
  7925. if (classVal && classVal.length > 0) {
  7926. $animate.addClass(this.$$element, classVal);
  7927. }
  7928. },
  7929. /**
  7930. * @ngdoc method
  7931. * @name $compile.directive.Attributes#$removeClass
  7932. * @kind function
  7933. *
  7934. * @description
  7935. * Removes the CSS class value specified by the classVal parameter from the element. If
  7936. * animations are enabled then an animation will be triggered for the class removal.
  7937. *
  7938. * @param {string} classVal The className value that will be removed from the element
  7939. */
  7940. $removeClass: function(classVal) {
  7941. if (classVal && classVal.length > 0) {
  7942. $animate.removeClass(this.$$element, classVal);
  7943. }
  7944. },
  7945. /**
  7946. * @ngdoc method
  7947. * @name $compile.directive.Attributes#$updateClass
  7948. * @kind function
  7949. *
  7950. * @description
  7951. * Adds and removes the appropriate CSS class values to the element based on the difference
  7952. * between the new and old CSS class values (specified as newClasses and oldClasses).
  7953. *
  7954. * @param {string} newClasses The current CSS className value
  7955. * @param {string} oldClasses The former CSS className value
  7956. */
  7957. $updateClass: function(newClasses, oldClasses) {
  7958. var toAdd = tokenDifference(newClasses, oldClasses);
  7959. if (toAdd && toAdd.length) {
  7960. $animate.addClass(this.$$element, toAdd);
  7961. }
  7962. var toRemove = tokenDifference(oldClasses, newClasses);
  7963. if (toRemove && toRemove.length) {
  7964. $animate.removeClass(this.$$element, toRemove);
  7965. }
  7966. },
  7967. /**
  7968. * Set a normalized attribute on the element in a way such that all directives
  7969. * can share the attribute. This function properly handles boolean attributes.
  7970. * @param {string} key Normalized key. (ie ngAttribute)
  7971. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  7972. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  7973. * Defaults to true.
  7974. * @param {string=} attrName Optional none normalized name. Defaults to key.
  7975. */
  7976. $set: function(key, value, writeAttr, attrName) {
  7977. // TODO: decide whether or not to throw an error if "class"
  7978. //is set through this function since it may cause $updateClass to
  7979. //become unstable.
  7980. var node = this.$$element[0],
  7981. booleanKey = getBooleanAttrName(node, key),
  7982. aliasedKey = getAliasedAttrName(key),
  7983. observer = key,
  7984. nodeName;
  7985. if (booleanKey) {
  7986. this.$$element.prop(key, value);
  7987. attrName = booleanKey;
  7988. } else if (aliasedKey) {
  7989. this[aliasedKey] = value;
  7990. observer = aliasedKey;
  7991. }
  7992. this[key] = value;
  7993. // translate normalized key to actual key
  7994. if (attrName) {
  7995. this.$attr[key] = attrName;
  7996. } else {
  7997. attrName = this.$attr[key];
  7998. if (!attrName) {
  7999. this.$attr[key] = attrName = snake_case(key, '-');
  8000. }
  8001. }
  8002. nodeName = nodeName_(this.$$element);
  8003. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  8004. (nodeName === 'img' && key === 'src')) {
  8005. // sanitize a[href] and img[src] values
  8006. this[key] = value = $$sanitizeUri(value, key === 'src');
  8007. } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
  8008. // sanitize img[srcset] values
  8009. var result = '';
  8010. // first check if there are spaces because it's not the same pattern
  8011. var trimmedSrcset = trim(value);
  8012. // ( 999x ,| 999w ,| ,|, )
  8013. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  8014. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  8015. // split srcset into tuple of uri and descriptor except for the last item
  8016. var rawUris = trimmedSrcset.split(pattern);
  8017. // for each tuples
  8018. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  8019. for (var i = 0; i < nbrUrisWith2parts; i++) {
  8020. var innerIdx = i * 2;
  8021. // sanitize the uri
  8022. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  8023. // add the descriptor
  8024. result += (' ' + trim(rawUris[innerIdx + 1]));
  8025. }
  8026. // split the last item into uri and descriptor
  8027. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  8028. // sanitize the last uri
  8029. result += $$sanitizeUri(trim(lastTuple[0]), true);
  8030. // and add the last descriptor if any
  8031. if (lastTuple.length === 2) {
  8032. result += (' ' + trim(lastTuple[1]));
  8033. }
  8034. this[key] = value = result;
  8035. }
  8036. if (writeAttr !== false) {
  8037. if (value === null || isUndefined(value)) {
  8038. this.$$element.removeAttr(attrName);
  8039. } else {
  8040. if (SIMPLE_ATTR_NAME.test(attrName)) {
  8041. this.$$element.attr(attrName, value);
  8042. } else {
  8043. setSpecialAttr(this.$$element[0], attrName, value);
  8044. }
  8045. }
  8046. }
  8047. // fire observers
  8048. var $$observers = this.$$observers;
  8049. if ($$observers) {
  8050. forEach($$observers[observer], function(fn) {
  8051. try {
  8052. fn(value);
  8053. } catch (e) {
  8054. $exceptionHandler(e);
  8055. }
  8056. });
  8057. }
  8058. },
  8059. /**
  8060. * @ngdoc method
  8061. * @name $compile.directive.Attributes#$observe
  8062. * @kind function
  8063. *
  8064. * @description
  8065. * Observes an interpolated attribute.
  8066. *
  8067. * The observer function will be invoked once during the next `$digest` following
  8068. * compilation. The observer is then invoked whenever the interpolated value
  8069. * changes.
  8070. *
  8071. * @param {string} key Normalized key. (ie ngAttribute) .
  8072. * @param {function(interpolatedValue)} fn Function that will be called whenever
  8073. the interpolated value of the attribute changes.
  8074. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  8075. * guide} for more info.
  8076. * @returns {function()} Returns a deregistration function for this observer.
  8077. */
  8078. $observe: function(key, fn) {
  8079. var attrs = this,
  8080. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  8081. listeners = ($$observers[key] || ($$observers[key] = []));
  8082. listeners.push(fn);
  8083. $rootScope.$evalAsync(function() {
  8084. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  8085. // no one registered attribute interpolation function, so lets call it manually
  8086. fn(attrs[key]);
  8087. }
  8088. });
  8089. return function() {
  8090. arrayRemove(listeners, fn);
  8091. };
  8092. }
  8093. };
  8094. function setSpecialAttr(element, attrName, value) {
  8095. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  8096. // so we have to jump through some hoops to get such an attribute
  8097. // https://github.com/angular/angular.js/pull/13318
  8098. specialAttrHolder.innerHTML = '<span ' + attrName + '>';
  8099. var attributes = specialAttrHolder.firstChild.attributes;
  8100. var attribute = attributes[0];
  8101. // We have to remove the attribute from its container element before we can add it to the destination element
  8102. attributes.removeNamedItem(attribute.name);
  8103. attribute.value = value;
  8104. element.attributes.setNamedItem(attribute);
  8105. }
  8106. function safeAddClass($element, className) {
  8107. try {
  8108. $element.addClass(className);
  8109. } catch (e) {
  8110. // ignore, since it means that we are trying to set class on
  8111. // SVG element, where class name is read-only.
  8112. }
  8113. }
  8114. var startSymbol = $interpolate.startSymbol(),
  8115. endSymbol = $interpolate.endSymbol(),
  8116. denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
  8117. ? identity
  8118. : function denormalizeTemplate(template) {
  8119. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  8120. },
  8121. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  8122. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  8123. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  8124. var bindings = $element.data('$binding') || [];
  8125. if (isArray(binding)) {
  8126. bindings = bindings.concat(binding);
  8127. } else {
  8128. bindings.push(binding);
  8129. }
  8130. $element.data('$binding', bindings);
  8131. } : noop;
  8132. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  8133. safeAddClass($element, 'ng-binding');
  8134. } : noop;
  8135. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  8136. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  8137. $element.data(dataName, scope);
  8138. } : noop;
  8139. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  8140. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  8141. } : noop;
  8142. compile.$$createComment = function(directiveName, comment) {
  8143. var content = '';
  8144. if (debugInfoEnabled) {
  8145. content = ' ' + (directiveName || '') + ': ';
  8146. if (comment) content += comment + ' ';
  8147. }
  8148. return window.document.createComment(content);
  8149. };
  8150. return compile;
  8151. //================================
  8152. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  8153. previousCompileContext) {
  8154. if (!($compileNodes instanceof jqLite)) {
  8155. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  8156. // modify it.
  8157. $compileNodes = jqLite($compileNodes);
  8158. }
  8159. var compositeLinkFn =
  8160. compileNodes($compileNodes, transcludeFn, $compileNodes,
  8161. maxPriority, ignoreDirective, previousCompileContext);
  8162. compile.$$addScopeClass($compileNodes);
  8163. var namespace = null;
  8164. return function publicLinkFn(scope, cloneConnectFn, options) {
  8165. if (!$compileNodes) {
  8166. throw $compileMinErr('multilink', 'This element has already been linked.');
  8167. }
  8168. assertArg(scope, 'scope');
  8169. if (previousCompileContext && previousCompileContext.needsNewScope) {
  8170. // A parent directive did a replace and a directive on this element asked
  8171. // for transclusion, which caused us to lose a layer of element on which
  8172. // we could hold the new transclusion scope, so we will create it manually
  8173. // here.
  8174. scope = scope.$parent.$new();
  8175. }
  8176. options = options || {};
  8177. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  8178. transcludeControllers = options.transcludeControllers,
  8179. futureParentElement = options.futureParentElement;
  8180. // When `parentBoundTranscludeFn` is passed, it is a
  8181. // `controllersBoundTransclude` function (it was previously passed
  8182. // as `transclude` to directive.link) so we must unwrap it to get
  8183. // its `boundTranscludeFn`
  8184. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  8185. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  8186. }
  8187. if (!namespace) {
  8188. namespace = detectNamespaceForChildElements(futureParentElement);
  8189. }
  8190. var $linkNode;
  8191. if (namespace !== 'html') {
  8192. // When using a directive with replace:true and templateUrl the $compileNodes
  8193. // (or a child element inside of them)
  8194. // might change, so we need to recreate the namespace adapted compileNodes
  8195. // for call to the link function.
  8196. // Note: This will already clone the nodes...
  8197. $linkNode = jqLite(
  8198. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  8199. );
  8200. } else if (cloneConnectFn) {
  8201. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  8202. // and sometimes changes the structure of the DOM.
  8203. $linkNode = JQLitePrototype.clone.call($compileNodes);
  8204. } else {
  8205. $linkNode = $compileNodes;
  8206. }
  8207. if (transcludeControllers) {
  8208. for (var controllerName in transcludeControllers) {
  8209. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  8210. }
  8211. }
  8212. compile.$$addScopeInfo($linkNode, scope);
  8213. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  8214. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  8215. if (!cloneConnectFn) {
  8216. $compileNodes = compositeLinkFn = null;
  8217. }
  8218. return $linkNode;
  8219. };
  8220. }
  8221. function detectNamespaceForChildElements(parentElement) {
  8222. // TODO: Make this detect MathML as well...
  8223. var node = parentElement && parentElement[0];
  8224. if (!node) {
  8225. return 'html';
  8226. } else {
  8227. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  8228. }
  8229. }
  8230. /**
  8231. * Compile function matches each node in nodeList against the directives. Once all directives
  8232. * for a particular node are collected their compile functions are executed. The compile
  8233. * functions return values - the linking functions - are combined into a composite linking
  8234. * function, which is the a linking function for the node.
  8235. *
  8236. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  8237. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8238. * scope argument is auto-generated to the new child of the transcluded parent scope.
  8239. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  8240. * the rootElement must be set the jqLite collection of the compile root. This is
  8241. * needed so that the jqLite collection items can be replaced with widgets.
  8242. * @param {number=} maxPriority Max directive priority.
  8243. * @returns {Function} A composite linking function of all of the matched directives or null.
  8244. */
  8245. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  8246. previousCompileContext) {
  8247. var linkFns = [],
  8248. // `nodeList` can be either an element's `.childNodes` (live NodeList)
  8249. // or a jqLite/jQuery collection or an array
  8250. notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),
  8251. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  8252. for (var i = 0; i < nodeList.length; i++) {
  8253. attrs = new Attributes();
  8254. // Support: IE 11 only
  8255. // Workaround for #11781 and #14924
  8256. if (msie === 11) {
  8257. mergeConsecutiveTextNodes(nodeList, i, notLiveList);
  8258. }
  8259. // We must always refer to `nodeList[i]` hereafter,
  8260. // since the nodes can be replaced underneath us.
  8261. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  8262. ignoreDirective);
  8263. nodeLinkFn = (directives.length)
  8264. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  8265. null, [], [], previousCompileContext)
  8266. : null;
  8267. if (nodeLinkFn && nodeLinkFn.scope) {
  8268. compile.$$addScopeClass(attrs.$$element);
  8269. }
  8270. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  8271. !(childNodes = nodeList[i].childNodes) ||
  8272. !childNodes.length)
  8273. ? null
  8274. : compileNodes(childNodes,
  8275. nodeLinkFn ? (
  8276. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  8277. && nodeLinkFn.transclude) : transcludeFn);
  8278. if (nodeLinkFn || childLinkFn) {
  8279. linkFns.push(i, nodeLinkFn, childLinkFn);
  8280. linkFnFound = true;
  8281. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  8282. }
  8283. //use the previous context only for the first element in the virtual group
  8284. previousCompileContext = null;
  8285. }
  8286. // return a linking function if we have found anything, null otherwise
  8287. return linkFnFound ? compositeLinkFn : null;
  8288. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  8289. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  8290. var stableNodeList;
  8291. if (nodeLinkFnFound) {
  8292. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  8293. // offsets don't get screwed up
  8294. var nodeListLength = nodeList.length;
  8295. stableNodeList = new Array(nodeListLength);
  8296. // create a sparse array by only copying the elements which have a linkFn
  8297. for (i = 0; i < linkFns.length; i += 3) {
  8298. idx = linkFns[i];
  8299. stableNodeList[idx] = nodeList[idx];
  8300. }
  8301. } else {
  8302. stableNodeList = nodeList;
  8303. }
  8304. for (i = 0, ii = linkFns.length; i < ii;) {
  8305. node = stableNodeList[linkFns[i++]];
  8306. nodeLinkFn = linkFns[i++];
  8307. childLinkFn = linkFns[i++];
  8308. if (nodeLinkFn) {
  8309. if (nodeLinkFn.scope) {
  8310. childScope = scope.$new();
  8311. compile.$$addScopeInfo(jqLite(node), childScope);
  8312. } else {
  8313. childScope = scope;
  8314. }
  8315. if (nodeLinkFn.transcludeOnThisElement) {
  8316. childBoundTranscludeFn = createBoundTranscludeFn(
  8317. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  8318. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  8319. childBoundTranscludeFn = parentBoundTranscludeFn;
  8320. } else if (!parentBoundTranscludeFn && transcludeFn) {
  8321. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  8322. } else {
  8323. childBoundTranscludeFn = null;
  8324. }
  8325. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  8326. } else if (childLinkFn) {
  8327. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  8328. }
  8329. }
  8330. }
  8331. }
  8332. function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {
  8333. var node = nodeList[idx];
  8334. var parent = node.parentNode;
  8335. var sibling;
  8336. if (node.nodeType !== NODE_TYPE_TEXT) {
  8337. return;
  8338. }
  8339. while (true) {
  8340. sibling = parent ? node.nextSibling : nodeList[idx + 1];
  8341. if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {
  8342. break;
  8343. }
  8344. node.nodeValue = node.nodeValue + sibling.nodeValue;
  8345. if (sibling.parentNode) {
  8346. sibling.parentNode.removeChild(sibling);
  8347. }
  8348. if (notLiveList && sibling === nodeList[idx + 1]) {
  8349. nodeList.splice(idx + 1, 1);
  8350. }
  8351. }
  8352. }
  8353. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  8354. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  8355. if (!transcludedScope) {
  8356. transcludedScope = scope.$new(false, containingScope);
  8357. transcludedScope.$$transcluded = true;
  8358. }
  8359. return transcludeFn(transcludedScope, cloneFn, {
  8360. parentBoundTranscludeFn: previousBoundTranscludeFn,
  8361. transcludeControllers: controllers,
  8362. futureParentElement: futureParentElement
  8363. });
  8364. }
  8365. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  8366. // so that they are available inside the `controllersBoundTransclude` function
  8367. var boundSlots = boundTranscludeFn.$$slots = createMap();
  8368. for (var slotName in transcludeFn.$$slots) {
  8369. if (transcludeFn.$$slots[slotName]) {
  8370. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  8371. } else {
  8372. boundSlots[slotName] = null;
  8373. }
  8374. }
  8375. return boundTranscludeFn;
  8376. }
  8377. /**
  8378. * Looks for directives on the given node and adds them to the directive collection which is
  8379. * sorted.
  8380. *
  8381. * @param node Node to search.
  8382. * @param directives An array to which the directives are added to. This array is sorted before
  8383. * the function returns.
  8384. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  8385. * @param {number=} maxPriority Max directive priority.
  8386. */
  8387. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8388. var nodeType = node.nodeType,
  8389. attrsMap = attrs.$attr,
  8390. match,
  8391. nodeName,
  8392. className;
  8393. switch (nodeType) {
  8394. case NODE_TYPE_ELEMENT: /* Element */
  8395. nodeName = nodeName_(node);
  8396. // use the node name: <directive>
  8397. addDirective(directives,
  8398. directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
  8399. // iterate over the attributes
  8400. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  8401. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  8402. var attrStartName = false;
  8403. var attrEndName = false;
  8404. attr = nAttrs[j];
  8405. name = attr.name;
  8406. value = attr.value;
  8407. // support ngAttr attribute binding
  8408. ngAttrName = directiveNormalize(name);
  8409. isNgAttr = NG_ATTR_BINDING.test(ngAttrName);
  8410. if (isNgAttr) {
  8411. name = name.replace(PREFIX_REGEXP, '')
  8412. .substr(8).replace(/_(.)/g, function(match, letter) {
  8413. return letter.toUpperCase();
  8414. });
  8415. }
  8416. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  8417. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  8418. attrStartName = name;
  8419. attrEndName = name.substr(0, name.length - 5) + 'end';
  8420. name = name.substr(0, name.length - 6);
  8421. }
  8422. nName = directiveNormalize(name.toLowerCase());
  8423. attrsMap[nName] = name;
  8424. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  8425. attrs[nName] = value;
  8426. if (getBooleanAttrName(node, nName)) {
  8427. attrs[nName] = true; // presence means true
  8428. }
  8429. }
  8430. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  8431. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  8432. attrEndName);
  8433. }
  8434. if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {
  8435. // Hidden input elements can have strange behaviour when navigating back to the page
  8436. // This tells the browser not to try to cache and reinstate previous values
  8437. node.setAttribute('autocomplete', 'off');
  8438. }
  8439. // use class as directive
  8440. if (!cssClassDirectivesEnabled) break;
  8441. className = node.className;
  8442. if (isObject(className)) {
  8443. // Maybe SVGAnimatedString
  8444. className = className.animVal;
  8445. }
  8446. if (isString(className) && className !== '') {
  8447. while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
  8448. nName = directiveNormalize(match[2]);
  8449. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  8450. attrs[nName] = trim(match[3]);
  8451. }
  8452. className = className.substr(match.index + match[0].length);
  8453. }
  8454. }
  8455. break;
  8456. case NODE_TYPE_TEXT: /* Text Node */
  8457. addTextInterpolateDirective(directives, node.nodeValue);
  8458. break;
  8459. case NODE_TYPE_COMMENT: /* Comment */
  8460. if (!commentDirectivesEnabled) break;
  8461. collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
  8462. break;
  8463. }
  8464. directives.sort(byPriority);
  8465. return directives;
  8466. }
  8467. function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8468. // function created because of performance, try/catch disables
  8469. // the optimization of the whole function #14848
  8470. try {
  8471. var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  8472. if (match) {
  8473. var nName = directiveNormalize(match[1]);
  8474. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  8475. attrs[nName] = trim(match[2]);
  8476. }
  8477. }
  8478. } catch (e) {
  8479. // turns out that under some circumstances IE9 throws errors when one attempts to read
  8480. // comment's node value.
  8481. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  8482. }
  8483. }
  8484. /**
  8485. * Given a node with a directive-start it collects all of the siblings until it finds
  8486. * directive-end.
  8487. * @param node
  8488. * @param attrStart
  8489. * @param attrEnd
  8490. * @returns {*}
  8491. */
  8492. function groupScan(node, attrStart, attrEnd) {
  8493. var nodes = [];
  8494. var depth = 0;
  8495. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  8496. do {
  8497. if (!node) {
  8498. throw $compileMinErr('uterdir',
  8499. 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
  8500. attrStart, attrEnd);
  8501. }
  8502. if (node.nodeType === NODE_TYPE_ELEMENT) {
  8503. if (node.hasAttribute(attrStart)) depth++;
  8504. if (node.hasAttribute(attrEnd)) depth--;
  8505. }
  8506. nodes.push(node);
  8507. node = node.nextSibling;
  8508. } while (depth > 0);
  8509. } else {
  8510. nodes.push(node);
  8511. }
  8512. return jqLite(nodes);
  8513. }
  8514. /**
  8515. * Wrapper for linking function which converts normal linking function into a grouped
  8516. * linking function.
  8517. * @param linkFn
  8518. * @param attrStart
  8519. * @param attrEnd
  8520. * @returns {Function}
  8521. */
  8522. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  8523. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  8524. element = groupScan(element[0], attrStart, attrEnd);
  8525. return linkFn(scope, element, attrs, controllers, transcludeFn);
  8526. };
  8527. }
  8528. /**
  8529. * A function generator that is used to support both eager and lazy compilation
  8530. * linking function.
  8531. * @param eager
  8532. * @param $compileNodes
  8533. * @param transcludeFn
  8534. * @param maxPriority
  8535. * @param ignoreDirective
  8536. * @param previousCompileContext
  8537. * @returns {Function}
  8538. */
  8539. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  8540. var compiled;
  8541. if (eager) {
  8542. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8543. }
  8544. return /** @this */ function lazyCompilation() {
  8545. if (!compiled) {
  8546. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8547. // Null out all of these references in order to make them eligible for garbage collection
  8548. // since this is a potentially long lived closure
  8549. $compileNodes = transcludeFn = previousCompileContext = null;
  8550. }
  8551. return compiled.apply(this, arguments);
  8552. };
  8553. }
  8554. /**
  8555. * Once the directives have been collected, their compile functions are executed. This method
  8556. * is responsible for inlining directive templates as well as terminating the application
  8557. * of the directives if the terminal directive has been reached.
  8558. *
  8559. * @param {Array} directives Array of collected directives to execute their compile function.
  8560. * this needs to be pre-sorted by priority order.
  8561. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  8562. * @param {Object} templateAttrs The shared attribute function
  8563. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8564. * scope argument is auto-generated to the new
  8565. * child of the transcluded parent scope.
  8566. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  8567. * argument has the root jqLite array so that we can replace nodes
  8568. * on it.
  8569. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  8570. * compiling the transclusion.
  8571. * @param {Array.<Function>} preLinkFns
  8572. * @param {Array.<Function>} postLinkFns
  8573. * @param {Object} previousCompileContext Context used for previous compilation of the current
  8574. * node
  8575. * @returns {Function} linkFn
  8576. */
  8577. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  8578. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  8579. previousCompileContext) {
  8580. previousCompileContext = previousCompileContext || {};
  8581. var terminalPriority = -Number.MAX_VALUE,
  8582. newScopeDirective = previousCompileContext.newScopeDirective,
  8583. controllerDirectives = previousCompileContext.controllerDirectives,
  8584. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  8585. templateDirective = previousCompileContext.templateDirective,
  8586. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  8587. hasTranscludeDirective = false,
  8588. hasTemplate = false,
  8589. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  8590. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  8591. directive,
  8592. directiveName,
  8593. $template,
  8594. replaceDirective = originalReplaceDirective,
  8595. childTranscludeFn = transcludeFn,
  8596. linkFn,
  8597. didScanForMultipleTransclusion = false,
  8598. mightHaveMultipleTransclusionError = false,
  8599. directiveValue;
  8600. // executes all directives on the current element
  8601. for (var i = 0, ii = directives.length; i < ii; i++) {
  8602. directive = directives[i];
  8603. var attrStart = directive.$$start;
  8604. var attrEnd = directive.$$end;
  8605. // collect multiblock sections
  8606. if (attrStart) {
  8607. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  8608. }
  8609. $template = undefined;
  8610. if (terminalPriority > directive.priority) {
  8611. break; // prevent further processing of directives
  8612. }
  8613. directiveValue = directive.scope;
  8614. if (directiveValue) {
  8615. // skip the check for directives with async templates, we'll check the derived sync
  8616. // directive when the template arrives
  8617. if (!directive.templateUrl) {
  8618. if (isObject(directiveValue)) {
  8619. // This directive is trying to add an isolated scope.
  8620. // Check that there is no scope of any kind already
  8621. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  8622. directive, $compileNode);
  8623. newIsolateScopeDirective = directive;
  8624. } else {
  8625. // This directive is trying to add a child scope.
  8626. // Check that there is no isolated scope already
  8627. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  8628. $compileNode);
  8629. }
  8630. }
  8631. newScopeDirective = newScopeDirective || directive;
  8632. }
  8633. directiveName = directive.name;
  8634. // If we encounter a condition that can result in transclusion on the directive,
  8635. // then scan ahead in the remaining directives for others that may cause a multiple
  8636. // transclusion error to be thrown during the compilation process. If a matching directive
  8637. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  8638. // compile the `transclude` function rather than doing it lazily in order to throw
  8639. // exceptions at the correct time
  8640. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  8641. || (directive.transclude && !directive.$$tlb))) {
  8642. var candidateDirective;
  8643. for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
  8644. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  8645. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  8646. mightHaveMultipleTransclusionError = true;
  8647. break;
  8648. }
  8649. }
  8650. didScanForMultipleTransclusion = true;
  8651. }
  8652. if (!directive.templateUrl && directive.controller) {
  8653. controllerDirectives = controllerDirectives || createMap();
  8654. assertNoDuplicate('\'' + directiveName + '\' controller',
  8655. controllerDirectives[directiveName], directive, $compileNode);
  8656. controllerDirectives[directiveName] = directive;
  8657. }
  8658. directiveValue = directive.transclude;
  8659. if (directiveValue) {
  8660. hasTranscludeDirective = true;
  8661. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  8662. // This option should only be used by directives that know how to safely handle element transclusion,
  8663. // where the transcluded nodes are added or replaced after linking.
  8664. if (!directive.$$tlb) {
  8665. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  8666. nonTlbTranscludeDirective = directive;
  8667. }
  8668. if (directiveValue === 'element') {
  8669. hasElementTranscludeDirective = true;
  8670. terminalPriority = directive.priority;
  8671. $template = $compileNode;
  8672. $compileNode = templateAttrs.$$element =
  8673. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  8674. compileNode = $compileNode[0];
  8675. replaceWith(jqCollection, sliceArgs($template), compileNode);
  8676. // Support: Chrome < 50
  8677. // https://github.com/angular/angular.js/issues/14041
  8678. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  8679. // in the `replaceWith` function is improperly garbage collected despite still
  8680. // being referenced by the `parentNode` property of all of the child nodes. By adding
  8681. // a reference to the fragment via a different property, we can avoid that incorrect
  8682. // behavior.
  8683. // TODO: remove this line after Chrome 50 has been released
  8684. $template[0].$$parentNode = $template[0].parentNode;
  8685. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  8686. replaceDirective && replaceDirective.name, {
  8687. // Don't pass in:
  8688. // - controllerDirectives - otherwise we'll create duplicates controllers
  8689. // - newIsolateScopeDirective or templateDirective - combining templates with
  8690. // element transclusion doesn't make sense.
  8691. //
  8692. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  8693. // on the same element more than once.
  8694. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8695. });
  8696. } else {
  8697. var slots = createMap();
  8698. if (!isObject(directiveValue)) {
  8699. $template = jqLite(jqLiteClone(compileNode)).contents();
  8700. } else {
  8701. // We have transclusion slots,
  8702. // collect them up, compile them and store their transclusion functions
  8703. $template = [];
  8704. var slotMap = createMap();
  8705. var filledSlots = createMap();
  8706. // Parse the element selectors
  8707. forEach(directiveValue, function(elementSelector, slotName) {
  8708. // If an element selector starts with a ? then it is optional
  8709. var optional = (elementSelector.charAt(0) === '?');
  8710. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  8711. slotMap[elementSelector] = slotName;
  8712. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  8713. // Later when calling boundTransclusion functions with a slot name we only error if the
  8714. // slot is `undefined`
  8715. slots[slotName] = null;
  8716. // filledSlots contains `true` for all slots that are either optional or have been
  8717. // filled. This is used to check that we have not missed any required slots
  8718. filledSlots[slotName] = optional;
  8719. });
  8720. // Add the matching elements into their slot
  8721. forEach($compileNode.contents(), function(node) {
  8722. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  8723. if (slotName) {
  8724. filledSlots[slotName] = true;
  8725. slots[slotName] = slots[slotName] || [];
  8726. slots[slotName].push(node);
  8727. } else {
  8728. $template.push(node);
  8729. }
  8730. });
  8731. // Check for required slots that were not filled
  8732. forEach(filledSlots, function(filled, slotName) {
  8733. if (!filled) {
  8734. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  8735. }
  8736. });
  8737. for (var slotName in slots) {
  8738. if (slots[slotName]) {
  8739. // Only define a transclusion function if the slot was filled
  8740. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  8741. }
  8742. }
  8743. }
  8744. $compileNode.empty(); // clear contents
  8745. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  8746. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  8747. childTranscludeFn.$$slots = slots;
  8748. }
  8749. }
  8750. if (directive.template) {
  8751. hasTemplate = true;
  8752. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8753. templateDirective = directive;
  8754. directiveValue = (isFunction(directive.template))
  8755. ? directive.template($compileNode, templateAttrs)
  8756. : directive.template;
  8757. directiveValue = denormalizeTemplate(directiveValue);
  8758. if (directive.replace) {
  8759. replaceDirective = directive;
  8760. if (jqLiteIsTextNode(directiveValue)) {
  8761. $template = [];
  8762. } else {
  8763. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  8764. }
  8765. compileNode = $template[0];
  8766. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8767. throw $compileMinErr('tplrt',
  8768. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  8769. directiveName, '');
  8770. }
  8771. replaceWith(jqCollection, $compileNode, compileNode);
  8772. var newTemplateAttrs = {$attr: {}};
  8773. // combine directives from the original node and from the template:
  8774. // - take the array of directives for this element
  8775. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  8776. // - collect directives from the template and sort them by priority
  8777. // - combine directives as: processed + template + unprocessed
  8778. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  8779. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  8780. if (newIsolateScopeDirective || newScopeDirective) {
  8781. // The original directive caused the current element to be replaced but this element
  8782. // also needs to have a new scope, so we need to tell the template directives
  8783. // that they would need to get their scope from further up, if they require transclusion
  8784. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  8785. }
  8786. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  8787. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  8788. ii = directives.length;
  8789. } else {
  8790. $compileNode.html(directiveValue);
  8791. }
  8792. }
  8793. if (directive.templateUrl) {
  8794. hasTemplate = true;
  8795. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8796. templateDirective = directive;
  8797. if (directive.replace) {
  8798. replaceDirective = directive;
  8799. }
  8800. // eslint-disable-next-line no-func-assign
  8801. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  8802. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  8803. controllerDirectives: controllerDirectives,
  8804. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  8805. newIsolateScopeDirective: newIsolateScopeDirective,
  8806. templateDirective: templateDirective,
  8807. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8808. });
  8809. ii = directives.length;
  8810. } else if (directive.compile) {
  8811. try {
  8812. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  8813. var context = directive.$$originalDirective || directive;
  8814. if (isFunction(linkFn)) {
  8815. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  8816. } else if (linkFn) {
  8817. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  8818. }
  8819. } catch (e) {
  8820. $exceptionHandler(e, startingTag($compileNode));
  8821. }
  8822. }
  8823. if (directive.terminal) {
  8824. nodeLinkFn.terminal = true;
  8825. terminalPriority = Math.max(terminalPriority, directive.priority);
  8826. }
  8827. }
  8828. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  8829. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  8830. nodeLinkFn.templateOnThisElement = hasTemplate;
  8831. nodeLinkFn.transclude = childTranscludeFn;
  8832. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  8833. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  8834. return nodeLinkFn;
  8835. ////////////////////
  8836. function addLinkFns(pre, post, attrStart, attrEnd) {
  8837. if (pre) {
  8838. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  8839. pre.require = directive.require;
  8840. pre.directiveName = directiveName;
  8841. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8842. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  8843. }
  8844. preLinkFns.push(pre);
  8845. }
  8846. if (post) {
  8847. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  8848. post.require = directive.require;
  8849. post.directiveName = directiveName;
  8850. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8851. post = cloneAndAnnotateFn(post, {isolateScope: true});
  8852. }
  8853. postLinkFns.push(post);
  8854. }
  8855. }
  8856. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8857. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8858. attrs, scopeBindingInfo;
  8859. if (compileNode === linkNode) {
  8860. attrs = templateAttrs;
  8861. $element = templateAttrs.$$element;
  8862. } else {
  8863. $element = jqLite(linkNode);
  8864. attrs = new Attributes($element, templateAttrs);
  8865. }
  8866. controllerScope = scope;
  8867. if (newIsolateScopeDirective) {
  8868. isolateScope = scope.$new(true);
  8869. } else if (newScopeDirective) {
  8870. controllerScope = scope.$parent;
  8871. }
  8872. if (boundTranscludeFn) {
  8873. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8874. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8875. transcludeFn = controllersBoundTransclude;
  8876. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8877. // expose the slots on the `$transclude` function
  8878. transcludeFn.isSlotFilled = function(slotName) {
  8879. return !!boundTranscludeFn.$$slots[slotName];
  8880. };
  8881. }
  8882. if (controllerDirectives) {
  8883. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  8884. }
  8885. if (newIsolateScopeDirective) {
  8886. // Initialize isolate scope bindings for new isolate scope directive.
  8887. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8888. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8889. compile.$$addScopeClass($element, true);
  8890. isolateScope.$$isolateBindings =
  8891. newIsolateScopeDirective.$$isolateBindings;
  8892. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  8893. isolateScope.$$isolateBindings,
  8894. newIsolateScopeDirective);
  8895. if (scopeBindingInfo.removeWatches) {
  8896. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  8897. }
  8898. }
  8899. // Initialize bindToController bindings
  8900. for (var name in elementControllers) {
  8901. var controllerDirective = controllerDirectives[name];
  8902. var controller = elementControllers[name];
  8903. var bindings = controllerDirective.$$bindings.bindToController;
  8904. if (preAssignBindingsEnabled) {
  8905. if (bindings) {
  8906. controller.bindingInfo =
  8907. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8908. } else {
  8909. controller.bindingInfo = {};
  8910. }
  8911. var controllerResult = controller();
  8912. if (controllerResult !== controller.instance) {
  8913. // If the controller constructor has a return value, overwrite the instance
  8914. // from setupControllers
  8915. controller.instance = controllerResult;
  8916. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8917. if (controller.bindingInfo.removeWatches) {
  8918. controller.bindingInfo.removeWatches();
  8919. }
  8920. controller.bindingInfo =
  8921. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8922. }
  8923. } else {
  8924. controller.instance = controller();
  8925. $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
  8926. controller.bindingInfo =
  8927. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8928. }
  8929. }
  8930. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  8931. forEach(controllerDirectives, function(controllerDirective, name) {
  8932. var require = controllerDirective.require;
  8933. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  8934. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  8935. }
  8936. });
  8937. // Handle the init and destroy lifecycle hooks on all controllers that have them
  8938. forEach(elementControllers, function(controller) {
  8939. var controllerInstance = controller.instance;
  8940. if (isFunction(controllerInstance.$onChanges)) {
  8941. try {
  8942. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  8943. } catch (e) {
  8944. $exceptionHandler(e);
  8945. }
  8946. }
  8947. if (isFunction(controllerInstance.$onInit)) {
  8948. try {
  8949. controllerInstance.$onInit();
  8950. } catch (e) {
  8951. $exceptionHandler(e);
  8952. }
  8953. }
  8954. if (isFunction(controllerInstance.$doCheck)) {
  8955. controllerScope.$watch(function() { controllerInstance.$doCheck(); });
  8956. controllerInstance.$doCheck();
  8957. }
  8958. if (isFunction(controllerInstance.$onDestroy)) {
  8959. controllerScope.$on('$destroy', function callOnDestroyHook() {
  8960. controllerInstance.$onDestroy();
  8961. });
  8962. }
  8963. });
  8964. // PRELINKING
  8965. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  8966. linkFn = preLinkFns[i];
  8967. invokeLinkFn(linkFn,
  8968. linkFn.isolateScope ? isolateScope : scope,
  8969. $element,
  8970. attrs,
  8971. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8972. transcludeFn
  8973. );
  8974. }
  8975. // RECURSION
  8976. // We only pass the isolate scope, if the isolate directive has a template,
  8977. // otherwise the child elements do not belong to the isolate directive.
  8978. var scopeToChild = scope;
  8979. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  8980. scopeToChild = isolateScope;
  8981. }
  8982. if (childLinkFn) {
  8983. childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  8984. }
  8985. // POSTLINKING
  8986. for (i = postLinkFns.length - 1; i >= 0; i--) {
  8987. linkFn = postLinkFns[i];
  8988. invokeLinkFn(linkFn,
  8989. linkFn.isolateScope ? isolateScope : scope,
  8990. $element,
  8991. attrs,
  8992. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8993. transcludeFn
  8994. );
  8995. }
  8996. // Trigger $postLink lifecycle hooks
  8997. forEach(elementControllers, function(controller) {
  8998. var controllerInstance = controller.instance;
  8999. if (isFunction(controllerInstance.$postLink)) {
  9000. controllerInstance.$postLink();
  9001. }
  9002. });
  9003. // This is the function that is injected as `$transclude`.
  9004. // Note: all arguments are optional!
  9005. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  9006. var transcludeControllers;
  9007. // No scope passed in:
  9008. if (!isScope(scope)) {
  9009. slotName = futureParentElement;
  9010. futureParentElement = cloneAttachFn;
  9011. cloneAttachFn = scope;
  9012. scope = undefined;
  9013. }
  9014. if (hasElementTranscludeDirective) {
  9015. transcludeControllers = elementControllers;
  9016. }
  9017. if (!futureParentElement) {
  9018. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  9019. }
  9020. if (slotName) {
  9021. // slotTranscludeFn can be one of three things:
  9022. // * a transclude function - a filled slot
  9023. // * `null` - an optional slot that was not filled
  9024. // * `undefined` - a slot that was not declared (i.e. invalid)
  9025. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  9026. if (slotTranscludeFn) {
  9027. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  9028. } else if (isUndefined(slotTranscludeFn)) {
  9029. throw $compileMinErr('noslot',
  9030. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  9031. 'Element: {1}',
  9032. slotName, startingTag($element));
  9033. }
  9034. } else {
  9035. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  9036. }
  9037. }
  9038. }
  9039. }
  9040. function getControllers(directiveName, require, $element, elementControllers) {
  9041. var value;
  9042. if (isString(require)) {
  9043. var match = require.match(REQUIRE_PREFIX_REGEXP);
  9044. var name = require.substring(match[0].length);
  9045. var inheritType = match[1] || match[3];
  9046. var optional = match[2] === '?';
  9047. //If only parents then start at the parent element
  9048. if (inheritType === '^^') {
  9049. $element = $element.parent();
  9050. //Otherwise attempt getting the controller from elementControllers in case
  9051. //the element is transcluded (and has no data) and to avoid .data if possible
  9052. } else {
  9053. value = elementControllers && elementControllers[name];
  9054. value = value && value.instance;
  9055. }
  9056. if (!value) {
  9057. var dataName = '$' + name + 'Controller';
  9058. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  9059. }
  9060. if (!value && !optional) {
  9061. throw $compileMinErr('ctreq',
  9062. 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
  9063. name, directiveName);
  9064. }
  9065. } else if (isArray(require)) {
  9066. value = [];
  9067. for (var i = 0, ii = require.length; i < ii; i++) {
  9068. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  9069. }
  9070. } else if (isObject(require)) {
  9071. value = {};
  9072. forEach(require, function(controller, property) {
  9073. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  9074. });
  9075. }
  9076. return value || null;
  9077. }
  9078. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  9079. var elementControllers = createMap();
  9080. for (var controllerKey in controllerDirectives) {
  9081. var directive = controllerDirectives[controllerKey];
  9082. var locals = {
  9083. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  9084. $element: $element,
  9085. $attrs: attrs,
  9086. $transclude: transcludeFn
  9087. };
  9088. var controller = directive.controller;
  9089. if (controller === '@') {
  9090. controller = attrs[directive.name];
  9091. }
  9092. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  9093. // For directives with element transclusion the element is a comment.
  9094. // In this case .data will not attach any data.
  9095. // Instead, we save the controllers for the element in a local hash and attach to .data
  9096. // later, once we have the actual element.
  9097. elementControllers[directive.name] = controllerInstance;
  9098. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  9099. }
  9100. return elementControllers;
  9101. }
  9102. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  9103. // or child scope created. For instance:
  9104. // * if the directive has been pulled into a template because another directive with a higher priority
  9105. // asked for element transclusion
  9106. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  9107. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  9108. function markDirectiveScope(directives, isolateScope, newScope) {
  9109. for (var j = 0, jj = directives.length; j < jj; j++) {
  9110. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  9111. }
  9112. }
  9113. /**
  9114. * looks up the directive and decorates it with exception handling and proper parameters. We
  9115. * call this the boundDirective.
  9116. *
  9117. * @param {string} name name of the directive to look up.
  9118. * @param {string} location The directive must be found in specific format.
  9119. * String containing any of theses characters:
  9120. *
  9121. * * `E`: element name
  9122. * * `A': attribute
  9123. * * `C`: class
  9124. * * `M`: comment
  9125. * @returns {boolean} true if directive was added.
  9126. */
  9127. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  9128. endAttrName) {
  9129. if (name === ignoreDirective) return null;
  9130. var match = null;
  9131. if (hasDirectives.hasOwnProperty(name)) {
  9132. for (var directive, directives = $injector.get(name + Suffix),
  9133. i = 0, ii = directives.length; i < ii; i++) {
  9134. directive = directives[i];
  9135. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  9136. directive.restrict.indexOf(location) !== -1) {
  9137. if (startAttrName) {
  9138. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  9139. }
  9140. if (!directive.$$bindings) {
  9141. var bindings = directive.$$bindings =
  9142. parseDirectiveBindings(directive, directive.name);
  9143. if (isObject(bindings.isolateScope)) {
  9144. directive.$$isolateBindings = bindings.isolateScope;
  9145. }
  9146. }
  9147. tDirectives.push(directive);
  9148. match = directive;
  9149. }
  9150. }
  9151. }
  9152. return match;
  9153. }
  9154. /**
  9155. * looks up the directive and returns true if it is a multi-element directive,
  9156. * and therefore requires DOM nodes between -start and -end markers to be grouped
  9157. * together.
  9158. *
  9159. * @param {string} name name of the directive to look up.
  9160. * @returns true if directive was registered as multi-element.
  9161. */
  9162. function directiveIsMultiElement(name) {
  9163. if (hasDirectives.hasOwnProperty(name)) {
  9164. for (var directive, directives = $injector.get(name + Suffix),
  9165. i = 0, ii = directives.length; i < ii; i++) {
  9166. directive = directives[i];
  9167. if (directive.multiElement) {
  9168. return true;
  9169. }
  9170. }
  9171. }
  9172. return false;
  9173. }
  9174. /**
  9175. * When the element is replaced with HTML template then the new attributes
  9176. * on the template need to be merged with the existing attributes in the DOM.
  9177. * The desired effect is to have both of the attributes present.
  9178. *
  9179. * @param {object} dst destination attributes (original DOM)
  9180. * @param {object} src source attributes (from the directive template)
  9181. */
  9182. function mergeTemplateAttributes(dst, src) {
  9183. var srcAttr = src.$attr,
  9184. dstAttr = dst.$attr;
  9185. // reapply the old attributes to the new element
  9186. forEach(dst, function(value, key) {
  9187. if (key.charAt(0) !== '$') {
  9188. if (src[key] && src[key] !== value) {
  9189. if (value.length) {
  9190. value += (key === 'style' ? ';' : ' ') + src[key];
  9191. } else {
  9192. value = src[key];
  9193. }
  9194. }
  9195. dst.$set(key, value, true, srcAttr[key]);
  9196. }
  9197. });
  9198. // copy the new attributes on the old attrs object
  9199. forEach(src, function(value, key) {
  9200. // Check if we already set this attribute in the loop above.
  9201. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  9202. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  9203. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  9204. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  9205. dst[key] = value;
  9206. if (key !== 'class' && key !== 'style') {
  9207. dstAttr[key] = srcAttr[key];
  9208. }
  9209. }
  9210. });
  9211. }
  9212. function compileTemplateUrl(directives, $compileNode, tAttrs,
  9213. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  9214. var linkQueue = [],
  9215. afterTemplateNodeLinkFn,
  9216. afterTemplateChildLinkFn,
  9217. beforeTemplateCompileNode = $compileNode[0],
  9218. origAsyncDirective = directives.shift(),
  9219. derivedSyncDirective = inherit(origAsyncDirective, {
  9220. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  9221. }),
  9222. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  9223. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  9224. : origAsyncDirective.templateUrl,
  9225. templateNamespace = origAsyncDirective.templateNamespace;
  9226. $compileNode.empty();
  9227. $templateRequest(templateUrl)
  9228. .then(function(content) {
  9229. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  9230. content = denormalizeTemplate(content);
  9231. if (origAsyncDirective.replace) {
  9232. if (jqLiteIsTextNode(content)) {
  9233. $template = [];
  9234. } else {
  9235. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  9236. }
  9237. compileNode = $template[0];
  9238. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  9239. throw $compileMinErr('tplrt',
  9240. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  9241. origAsyncDirective.name, templateUrl);
  9242. }
  9243. tempTemplateAttrs = {$attr: {}};
  9244. replaceWith($rootElement, $compileNode, compileNode);
  9245. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  9246. if (isObject(origAsyncDirective.scope)) {
  9247. // the original directive that caused the template to be loaded async required
  9248. // an isolate scope
  9249. markDirectiveScope(templateDirectives, true);
  9250. }
  9251. directives = templateDirectives.concat(directives);
  9252. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  9253. } else {
  9254. compileNode = beforeTemplateCompileNode;
  9255. $compileNode.html(content);
  9256. }
  9257. directives.unshift(derivedSyncDirective);
  9258. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  9259. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  9260. previousCompileContext);
  9261. forEach($rootElement, function(node, i) {
  9262. if (node === compileNode) {
  9263. $rootElement[i] = $compileNode[0];
  9264. }
  9265. });
  9266. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  9267. while (linkQueue.length) {
  9268. var scope = linkQueue.shift(),
  9269. beforeTemplateLinkNode = linkQueue.shift(),
  9270. linkRootElement = linkQueue.shift(),
  9271. boundTranscludeFn = linkQueue.shift(),
  9272. linkNode = $compileNode[0];
  9273. if (scope.$$destroyed) continue;
  9274. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  9275. var oldClasses = beforeTemplateLinkNode.className;
  9276. if (!(previousCompileContext.hasElementTranscludeDirective &&
  9277. origAsyncDirective.replace)) {
  9278. // it was cloned therefore we have to clone as well.
  9279. linkNode = jqLiteClone(compileNode);
  9280. }
  9281. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  9282. // Copy in CSS classes from original node
  9283. safeAddClass(jqLite(linkNode), oldClasses);
  9284. }
  9285. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9286. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9287. } else {
  9288. childBoundTranscludeFn = boundTranscludeFn;
  9289. }
  9290. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  9291. childBoundTranscludeFn);
  9292. }
  9293. linkQueue = null;
  9294. }).catch(function(error) {
  9295. if (isError(error)) {
  9296. $exceptionHandler(error);
  9297. }
  9298. });
  9299. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  9300. var childBoundTranscludeFn = boundTranscludeFn;
  9301. if (scope.$$destroyed) return;
  9302. if (linkQueue) {
  9303. linkQueue.push(scope,
  9304. node,
  9305. rootElement,
  9306. childBoundTranscludeFn);
  9307. } else {
  9308. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9309. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9310. }
  9311. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  9312. }
  9313. };
  9314. }
  9315. /**
  9316. * Sorting function for bound directives.
  9317. */
  9318. function byPriority(a, b) {
  9319. var diff = b.priority - a.priority;
  9320. if (diff !== 0) return diff;
  9321. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  9322. return a.index - b.index;
  9323. }
  9324. function assertNoDuplicate(what, previousDirective, directive, element) {
  9325. function wrapModuleNameIfDefined(moduleName) {
  9326. return moduleName ?
  9327. (' (module: ' + moduleName + ')') :
  9328. '';
  9329. }
  9330. if (previousDirective) {
  9331. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  9332. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  9333. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  9334. }
  9335. }
  9336. function addTextInterpolateDirective(directives, text) {
  9337. var interpolateFn = $interpolate(text, true);
  9338. if (interpolateFn) {
  9339. directives.push({
  9340. priority: 0,
  9341. compile: function textInterpolateCompileFn(templateNode) {
  9342. var templateNodeParent = templateNode.parent(),
  9343. hasCompileParent = !!templateNodeParent.length;
  9344. // When transcluding a template that has bindings in the root
  9345. // we don't have a parent and thus need to add the class during linking fn.
  9346. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  9347. return function textInterpolateLinkFn(scope, node) {
  9348. var parent = node.parent();
  9349. if (!hasCompileParent) compile.$$addBindingClass(parent);
  9350. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  9351. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  9352. node[0].nodeValue = value;
  9353. });
  9354. };
  9355. }
  9356. });
  9357. }
  9358. }
  9359. function wrapTemplate(type, template) {
  9360. type = lowercase(type || 'html');
  9361. switch (type) {
  9362. case 'svg':
  9363. case 'math':
  9364. var wrapper = window.document.createElement('div');
  9365. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  9366. return wrapper.childNodes[0].childNodes;
  9367. default:
  9368. return template;
  9369. }
  9370. }
  9371. function getTrustedContext(node, attrNormalizedName) {
  9372. if (attrNormalizedName === 'srcdoc') {
  9373. return $sce.HTML;
  9374. }
  9375. var tag = nodeName_(node);
  9376. // All tags with src attributes require a RESOURCE_URL value, except for
  9377. // img and various html5 media tags.
  9378. if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
  9379. if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) {
  9380. return $sce.RESOURCE_URL;
  9381. }
  9382. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  9383. } else if (attrNormalizedName === 'xlinkHref' ||
  9384. (tag === 'form' && attrNormalizedName === 'action') ||
  9385. // links can be stylesheets or imports, which can run script in the current origin
  9386. (tag === 'link' && attrNormalizedName === 'href')
  9387. ) {
  9388. return $sce.RESOURCE_URL;
  9389. }
  9390. }
  9391. function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {
  9392. var trustedContext = getTrustedContext(node, name);
  9393. var mustHaveExpression = !isNgAttr;
  9394. var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;
  9395. var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
  9396. // no interpolation found -> ignore
  9397. if (!interpolateFn) return;
  9398. if (name === 'multiple' && nodeName_(node) === 'select') {
  9399. throw $compileMinErr('selmulti',
  9400. 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
  9401. startingTag(node));
  9402. }
  9403. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  9404. throw $compileMinErr('nodomevents',
  9405. 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' +
  9406. 'ng- versions (such as ng-click instead of onclick) instead.');
  9407. }
  9408. directives.push({
  9409. priority: 100,
  9410. compile: function() {
  9411. return {
  9412. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  9413. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  9414. // If the attribute has changed since last $interpolate()ed
  9415. var newValue = attr[name];
  9416. if (newValue !== value) {
  9417. // we need to interpolate again since the attribute value has been updated
  9418. // (e.g. by another directive's compile function)
  9419. // ensure unset/empty values make interpolateFn falsy
  9420. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  9421. value = newValue;
  9422. }
  9423. // if attribute was updated so that there is no interpolation going on we don't want to
  9424. // register any observers
  9425. if (!interpolateFn) return;
  9426. // initialize attr object so that it's ready in case we need the value for isolate
  9427. // scope initialization, otherwise the value would not be available from isolate
  9428. // directive's linking fn during linking phase
  9429. attr[name] = interpolateFn(scope);
  9430. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  9431. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  9432. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  9433. //special case for class attribute addition + removal
  9434. //so that class changes can tap into the animation
  9435. //hooks provided by the $animate service. Be sure to
  9436. //skip animations when the first digest occurs (when
  9437. //both the new and the old values are the same) since
  9438. //the CSS classes are the non-interpolated values
  9439. if (name === 'class' && newValue !== oldValue) {
  9440. attr.$updateClass(newValue, oldValue);
  9441. } else {
  9442. attr.$set(name, newValue);
  9443. }
  9444. });
  9445. }
  9446. };
  9447. }
  9448. });
  9449. }
  9450. /**
  9451. * This is a special jqLite.replaceWith, which can replace items which
  9452. * have no parents, provided that the containing jqLite collection is provided.
  9453. *
  9454. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  9455. * in the root of the tree.
  9456. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  9457. * the shell, but replace its DOM node reference.
  9458. * @param {Node} newNode The new DOM node.
  9459. */
  9460. function replaceWith($rootElement, elementsToRemove, newNode) {
  9461. var firstElementToRemove = elementsToRemove[0],
  9462. removeCount = elementsToRemove.length,
  9463. parent = firstElementToRemove.parentNode,
  9464. i, ii;
  9465. if ($rootElement) {
  9466. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  9467. if ($rootElement[i] === firstElementToRemove) {
  9468. $rootElement[i++] = newNode;
  9469. for (var j = i, j2 = j + removeCount - 1,
  9470. jj = $rootElement.length;
  9471. j < jj; j++, j2++) {
  9472. if (j2 < jj) {
  9473. $rootElement[j] = $rootElement[j2];
  9474. } else {
  9475. delete $rootElement[j];
  9476. }
  9477. }
  9478. $rootElement.length -= removeCount - 1;
  9479. // If the replaced element is also the jQuery .context then replace it
  9480. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  9481. // http://api.jquery.com/context/
  9482. if ($rootElement.context === firstElementToRemove) {
  9483. $rootElement.context = newNode;
  9484. }
  9485. break;
  9486. }
  9487. }
  9488. }
  9489. if (parent) {
  9490. parent.replaceChild(newNode, firstElementToRemove);
  9491. }
  9492. // Append all the `elementsToRemove` to a fragment. This will...
  9493. // - remove them from the DOM
  9494. // - allow them to still be traversed with .nextSibling
  9495. // - allow a single fragment.qSA to fetch all elements being removed
  9496. var fragment = window.document.createDocumentFragment();
  9497. for (i = 0; i < removeCount; i++) {
  9498. fragment.appendChild(elementsToRemove[i]);
  9499. }
  9500. if (jqLite.hasData(firstElementToRemove)) {
  9501. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  9502. // data here because there's no public interface in jQuery to do that and copying over
  9503. // event listeners (which is the main use of private data) wouldn't work anyway.
  9504. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  9505. // Remove $destroy event listeners from `firstElementToRemove`
  9506. jqLite(firstElementToRemove).off('$destroy');
  9507. }
  9508. // Cleanup any data/listeners on the elements and children.
  9509. // This includes invoking the $destroy event on any elements with listeners.
  9510. jqLite.cleanData(fragment.querySelectorAll('*'));
  9511. // Update the jqLite collection to only contain the `newNode`
  9512. for (i = 1; i < removeCount; i++) {
  9513. delete elementsToRemove[i];
  9514. }
  9515. elementsToRemove[0] = newNode;
  9516. elementsToRemove.length = 1;
  9517. }
  9518. function cloneAndAnnotateFn(fn, annotation) {
  9519. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  9520. }
  9521. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  9522. try {
  9523. linkFn(scope, $element, attrs, controllers, transcludeFn);
  9524. } catch (e) {
  9525. $exceptionHandler(e, startingTag($element));
  9526. }
  9527. }
  9528. function strictBindingsCheck(attrName, directiveName) {
  9529. if (strictComponentBindingsEnabled) {
  9530. throw $compileMinErr('missingattr',
  9531. 'Attribute \'{0}\' of \'{1}\' is non-optional and must be set!',
  9532. attrName, directiveName);
  9533. }
  9534. }
  9535. // Set up $watches for isolate scope and controller bindings.
  9536. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  9537. var removeWatchCollection = [];
  9538. var initialChanges = {};
  9539. var changes;
  9540. forEach(bindings, function initializeBinding(definition, scopeName) {
  9541. var attrName = definition.attrName,
  9542. optional = definition.optional,
  9543. mode = definition.mode, // @, =, <, or &
  9544. lastValue,
  9545. parentGet, parentSet, compare, removeWatch;
  9546. switch (mode) {
  9547. case '@':
  9548. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  9549. strictBindingsCheck(attrName, directive.name);
  9550. destination[scopeName] = attrs[attrName] = undefined;
  9551. }
  9552. removeWatch = attrs.$observe(attrName, function(value) {
  9553. if (isString(value) || isBoolean(value)) {
  9554. var oldValue = destination[scopeName];
  9555. recordChanges(scopeName, value, oldValue);
  9556. destination[scopeName] = value;
  9557. }
  9558. });
  9559. attrs.$$observers[attrName].$$scope = scope;
  9560. lastValue = attrs[attrName];
  9561. if (isString(lastValue)) {
  9562. // If the attribute has been provided then we trigger an interpolation to ensure
  9563. // the value is there for use in the link fn
  9564. destination[scopeName] = $interpolate(lastValue)(scope);
  9565. } else if (isBoolean(lastValue)) {
  9566. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  9567. // the value to boolean rather than a string, so we special case this situation
  9568. destination[scopeName] = lastValue;
  9569. }
  9570. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9571. removeWatchCollection.push(removeWatch);
  9572. break;
  9573. case '=':
  9574. if (!hasOwnProperty.call(attrs, attrName)) {
  9575. if (optional) break;
  9576. strictBindingsCheck(attrName, directive.name);
  9577. attrs[attrName] = undefined;
  9578. }
  9579. if (optional && !attrs[attrName]) break;
  9580. parentGet = $parse(attrs[attrName]);
  9581. if (parentGet.literal) {
  9582. compare = equals;
  9583. } else {
  9584. compare = simpleCompare;
  9585. }
  9586. parentSet = parentGet.assign || function() {
  9587. // reset the change, or we will throw this exception on every $digest
  9588. lastValue = destination[scopeName] = parentGet(scope);
  9589. throw $compileMinErr('nonassign',
  9590. 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
  9591. attrs[attrName], attrName, directive.name);
  9592. };
  9593. lastValue = destination[scopeName] = parentGet(scope);
  9594. var parentValueWatch = function parentValueWatch(parentValue) {
  9595. if (!compare(parentValue, destination[scopeName])) {
  9596. // we are out of sync and need to copy
  9597. if (!compare(parentValue, lastValue)) {
  9598. // parent changed and it has precedence
  9599. destination[scopeName] = parentValue;
  9600. } else {
  9601. // if the parent can be assigned then do so
  9602. parentSet(scope, parentValue = destination[scopeName]);
  9603. }
  9604. }
  9605. lastValue = parentValue;
  9606. return lastValue;
  9607. };
  9608. parentValueWatch.$stateful = true;
  9609. if (definition.collection) {
  9610. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  9611. } else {
  9612. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  9613. }
  9614. removeWatchCollection.push(removeWatch);
  9615. break;
  9616. case '<':
  9617. if (!hasOwnProperty.call(attrs, attrName)) {
  9618. if (optional) break;
  9619. strictBindingsCheck(attrName, directive.name);
  9620. attrs[attrName] = undefined;
  9621. }
  9622. if (optional && !attrs[attrName]) break;
  9623. parentGet = $parse(attrs[attrName]);
  9624. var deepWatch = parentGet.literal;
  9625. var initialValue = destination[scopeName] = parentGet(scope);
  9626. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9627. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
  9628. if (oldValue === newValue) {
  9629. if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) {
  9630. return;
  9631. }
  9632. oldValue = initialValue;
  9633. }
  9634. recordChanges(scopeName, newValue, oldValue);
  9635. destination[scopeName] = newValue;
  9636. }, deepWatch);
  9637. removeWatchCollection.push(removeWatch);
  9638. break;
  9639. case '&':
  9640. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  9641. strictBindingsCheck(attrName, directive.name);
  9642. }
  9643. // Don't assign Object.prototype method to scope
  9644. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  9645. // Don't assign noop to destination if expression is not valid
  9646. if (parentGet === noop && optional) break;
  9647. destination[scopeName] = function(locals) {
  9648. return parentGet(scope, locals);
  9649. };
  9650. break;
  9651. }
  9652. });
  9653. function recordChanges(key, currentValue, previousValue) {
  9654. if (isFunction(destination.$onChanges) && !simpleCompare(currentValue, previousValue)) {
  9655. // If we have not already scheduled the top level onChangesQueue handler then do so now
  9656. if (!onChangesQueue) {
  9657. scope.$$postDigest(flushOnChangesQueue);
  9658. onChangesQueue = [];
  9659. }
  9660. // If we have not already queued a trigger of onChanges for this controller then do so now
  9661. if (!changes) {
  9662. changes = {};
  9663. onChangesQueue.push(triggerOnChangesHook);
  9664. }
  9665. // If the has been a change on this property already then we need to reuse the previous value
  9666. if (changes[key]) {
  9667. previousValue = changes[key].previousValue;
  9668. }
  9669. // Store this change
  9670. changes[key] = new SimpleChange(previousValue, currentValue);
  9671. }
  9672. }
  9673. function triggerOnChangesHook() {
  9674. destination.$onChanges(changes);
  9675. // Now clear the changes so that we schedule onChanges when more changes arrive
  9676. changes = undefined;
  9677. }
  9678. return {
  9679. initialChanges: initialChanges,
  9680. removeWatches: removeWatchCollection.length && function removeWatches() {
  9681. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  9682. removeWatchCollection[i]();
  9683. }
  9684. }
  9685. };
  9686. }
  9687. }];
  9688. }
  9689. function SimpleChange(previous, current) {
  9690. this.previousValue = previous;
  9691. this.currentValue = current;
  9692. }
  9693. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  9694. var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
  9695. var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
  9696. /**
  9697. * Converts all accepted directives format into proper directive name.
  9698. * @param name Name to normalize
  9699. */
  9700. function directiveNormalize(name) {
  9701. return name
  9702. .replace(PREFIX_REGEXP, '')
  9703. .replace(SPECIAL_CHARS_REGEXP, fnCamelCaseReplace);
  9704. }
  9705. /**
  9706. * @ngdoc type
  9707. * @name $compile.directive.Attributes
  9708. *
  9709. * @description
  9710. * A shared object between directive compile / linking functions which contains normalized DOM
  9711. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  9712. * needed since all of these are treated as equivalent in Angular:
  9713. *
  9714. * ```
  9715. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  9716. * ```
  9717. */
  9718. /**
  9719. * @ngdoc property
  9720. * @name $compile.directive.Attributes#$attr
  9721. *
  9722. * @description
  9723. * A map of DOM element attribute names to the normalized name. This is
  9724. * needed to do reverse lookup from normalized name back to actual name.
  9725. */
  9726. /**
  9727. * @ngdoc method
  9728. * @name $compile.directive.Attributes#$set
  9729. * @kind function
  9730. *
  9731. * @description
  9732. * Set DOM element attribute value.
  9733. *
  9734. *
  9735. * @param {string} name Normalized element attribute name of the property to modify. The name is
  9736. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  9737. * property to the original name.
  9738. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  9739. */
  9740. /**
  9741. * Closure compiler type information
  9742. */
  9743. function nodesetLinkingFn(
  9744. /* angular.Scope */ scope,
  9745. /* NodeList */ nodeList,
  9746. /* Element */ rootElement,
  9747. /* function(Function) */ boundTranscludeFn
  9748. ) {}
  9749. function directiveLinkingFn(
  9750. /* nodesetLinkingFn */ nodesetLinkingFn,
  9751. /* angular.Scope */ scope,
  9752. /* Node */ node,
  9753. /* Element */ rootElement,
  9754. /* function(Function) */ boundTranscludeFn
  9755. ) {}
  9756. function tokenDifference(str1, str2) {
  9757. var values = '',
  9758. tokens1 = str1.split(/\s+/),
  9759. tokens2 = str2.split(/\s+/);
  9760. outer:
  9761. for (var i = 0; i < tokens1.length; i++) {
  9762. var token = tokens1[i];
  9763. for (var j = 0; j < tokens2.length; j++) {
  9764. if (token === tokens2[j]) continue outer;
  9765. }
  9766. values += (values.length > 0 ? ' ' : '') + token;
  9767. }
  9768. return values;
  9769. }
  9770. function removeComments(jqNodes) {
  9771. jqNodes = jqLite(jqNodes);
  9772. var i = jqNodes.length;
  9773. if (i <= 1) {
  9774. return jqNodes;
  9775. }
  9776. while (i--) {
  9777. var node = jqNodes[i];
  9778. if (node.nodeType === NODE_TYPE_COMMENT ||
  9779. (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {
  9780. splice.call(jqNodes, i, 1);
  9781. }
  9782. }
  9783. return jqNodes;
  9784. }
  9785. var $controllerMinErr = minErr('$controller');
  9786. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  9787. function identifierForController(controller, ident) {
  9788. if (ident && isString(ident)) return ident;
  9789. if (isString(controller)) {
  9790. var match = CNTRL_REG.exec(controller);
  9791. if (match) return match[3];
  9792. }
  9793. }
  9794. /**
  9795. * @ngdoc provider
  9796. * @name $controllerProvider
  9797. * @this
  9798. *
  9799. * @description
  9800. * The {@link ng.$controller $controller service} is used by Angular to create new
  9801. * controllers.
  9802. *
  9803. * This provider allows controller registration via the
  9804. * {@link ng.$controllerProvider#register register} method.
  9805. */
  9806. function $ControllerProvider() {
  9807. var controllers = {},
  9808. globals = false;
  9809. /**
  9810. * @ngdoc method
  9811. * @name $controllerProvider#has
  9812. * @param {string} name Controller name to check.
  9813. */
  9814. this.has = function(name) {
  9815. return controllers.hasOwnProperty(name);
  9816. };
  9817. /**
  9818. * @ngdoc method
  9819. * @name $controllerProvider#register
  9820. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  9821. * the names and the values are the constructors.
  9822. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  9823. * annotations in the array notation).
  9824. */
  9825. this.register = function(name, constructor) {
  9826. assertNotHasOwnProperty(name, 'controller');
  9827. if (isObject(name)) {
  9828. extend(controllers, name);
  9829. } else {
  9830. controllers[name] = constructor;
  9831. }
  9832. };
  9833. /**
  9834. * @ngdoc method
  9835. * @name $controllerProvider#allowGlobals
  9836. * @description If called, allows `$controller` to find controller constructors on `window`
  9837. *
  9838. * @deprecated
  9839. * sinceVersion="v1.3.0"
  9840. * removeVersion="v1.7.0"
  9841. * This method of finding controllers has been deprecated.
  9842. */
  9843. this.allowGlobals = function() {
  9844. globals = true;
  9845. };
  9846. this.$get = ['$injector', '$window', function($injector, $window) {
  9847. /**
  9848. * @ngdoc service
  9849. * @name $controller
  9850. * @requires $injector
  9851. *
  9852. * @param {Function|string} constructor If called with a function then it's considered to be the
  9853. * controller constructor function. Otherwise it's considered to be a string which is used
  9854. * to retrieve the controller constructor using the following steps:
  9855. *
  9856. * * check if a controller with given name is registered via `$controllerProvider`
  9857. * * check if evaluating the string on the current scope returns a constructor
  9858. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  9859. * `window` object (deprecated, not recommended)
  9860. *
  9861. * The string can use the `controller as property` syntax, where the controller instance is published
  9862. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  9863. * to work correctly.
  9864. *
  9865. * @param {Object} locals Injection locals for Controller.
  9866. * @return {Object} Instance of given controller.
  9867. *
  9868. * @description
  9869. * `$controller` service is responsible for instantiating controllers.
  9870. *
  9871. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  9872. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  9873. */
  9874. return function $controller(expression, locals, later, ident) {
  9875. // PRIVATE API:
  9876. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  9877. // If true, $controller will allocate the object with the correct
  9878. // prototype chain, but will not invoke the controller until a returned
  9879. // callback is invoked.
  9880. // param `ident` --- An optional label which overrides the label parsed from the controller
  9881. // expression, if any.
  9882. var instance, match, constructor, identifier;
  9883. later = later === true;
  9884. if (ident && isString(ident)) {
  9885. identifier = ident;
  9886. }
  9887. if (isString(expression)) {
  9888. match = expression.match(CNTRL_REG);
  9889. if (!match) {
  9890. throw $controllerMinErr('ctrlfmt',
  9891. 'Badly formed controller string \'{0}\'. ' +
  9892. 'Must match `__name__ as __id__` or `__name__`.', expression);
  9893. }
  9894. constructor = match[1];
  9895. identifier = identifier || match[3];
  9896. expression = controllers.hasOwnProperty(constructor)
  9897. ? controllers[constructor]
  9898. : getter(locals.$scope, constructor, true) ||
  9899. (globals ? getter($window, constructor, true) : undefined);
  9900. if (!expression) {
  9901. throw $controllerMinErr('ctrlreg',
  9902. 'The controller with the name \'{0}\' is not registered.', constructor);
  9903. }
  9904. assertArgFn(expression, constructor, true);
  9905. }
  9906. if (later) {
  9907. // Instantiate controller later:
  9908. // This machinery is used to create an instance of the object before calling the
  9909. // controller's constructor itself.
  9910. //
  9911. // This allows properties to be added to the controller before the constructor is
  9912. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  9913. //
  9914. // This feature is not intended for use by applications, and is thus not documented
  9915. // publicly.
  9916. // Object creation: http://jsperf.com/create-constructor/2
  9917. var controllerPrototype = (isArray(expression) ?
  9918. expression[expression.length - 1] : expression).prototype;
  9919. instance = Object.create(controllerPrototype || null);
  9920. if (identifier) {
  9921. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9922. }
  9923. return extend(function $controllerInit() {
  9924. var result = $injector.invoke(expression, instance, locals, constructor);
  9925. if (result !== instance && (isObject(result) || isFunction(result))) {
  9926. instance = result;
  9927. if (identifier) {
  9928. // If result changed, re-assign controllerAs value to scope.
  9929. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9930. }
  9931. }
  9932. return instance;
  9933. }, {
  9934. instance: instance,
  9935. identifier: identifier
  9936. });
  9937. }
  9938. instance = $injector.instantiate(expression, locals, constructor);
  9939. if (identifier) {
  9940. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9941. }
  9942. return instance;
  9943. };
  9944. function addIdentifier(locals, identifier, instance, name) {
  9945. if (!(locals && isObject(locals.$scope))) {
  9946. throw minErr('$controller')('noscp',
  9947. 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
  9948. name, identifier);
  9949. }
  9950. locals.$scope[identifier] = instance;
  9951. }
  9952. }];
  9953. }
  9954. /**
  9955. * @ngdoc service
  9956. * @name $document
  9957. * @requires $window
  9958. * @this
  9959. *
  9960. * @description
  9961. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  9962. *
  9963. * @example
  9964. <example module="documentExample" name="document">
  9965. <file name="index.html">
  9966. <div ng-controller="ExampleController">
  9967. <p>$document title: <b ng-bind="title"></b></p>
  9968. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  9969. </div>
  9970. </file>
  9971. <file name="script.js">
  9972. angular.module('documentExample', [])
  9973. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  9974. $scope.title = $document[0].title;
  9975. $scope.windowTitle = angular.element(window.document)[0].title;
  9976. }]);
  9977. </file>
  9978. </example>
  9979. */
  9980. function $DocumentProvider() {
  9981. this.$get = ['$window', function(window) {
  9982. return jqLite(window.document);
  9983. }];
  9984. }
  9985. /**
  9986. * @private
  9987. * @this
  9988. * Listens for document visibility change and makes the current status accessible.
  9989. */
  9990. function $$IsDocumentHiddenProvider() {
  9991. this.$get = ['$document', '$rootScope', function($document, $rootScope) {
  9992. var doc = $document[0];
  9993. var hidden = doc && doc.hidden;
  9994. $document.on('visibilitychange', changeListener);
  9995. $rootScope.$on('$destroy', function() {
  9996. $document.off('visibilitychange', changeListener);
  9997. });
  9998. function changeListener() {
  9999. hidden = doc.hidden;
  10000. }
  10001. return function() {
  10002. return hidden;
  10003. };
  10004. }];
  10005. }
  10006. /**
  10007. * @ngdoc service
  10008. * @name $exceptionHandler
  10009. * @requires ng.$log
  10010. * @this
  10011. *
  10012. * @description
  10013. * Any uncaught exception in angular expressions is delegated to this service.
  10014. * The default implementation simply delegates to `$log.error` which logs it into
  10015. * the browser console.
  10016. *
  10017. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  10018. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  10019. *
  10020. * ## Example:
  10021. *
  10022. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  10023. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  10024. * of `$log.error()`.
  10025. *
  10026. * ```js
  10027. * angular.
  10028. * module('exceptionOverwrite', []).
  10029. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  10030. * return function myExceptionHandler(exception, cause) {
  10031. * logErrorsToBackend(exception, cause);
  10032. * $log.warn(exception, cause);
  10033. * };
  10034. * }]);
  10035. * ```
  10036. *
  10037. * <hr />
  10038. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  10039. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  10040. * (unless executed during a digest).
  10041. *
  10042. * If you wish, you can manually delegate exceptions, e.g.
  10043. * `try { ... } catch(e) { $exceptionHandler(e); }`
  10044. *
  10045. * @param {Error} exception Exception associated with the error.
  10046. * @param {string=} cause Optional information about the context in which
  10047. * the error was thrown.
  10048. *
  10049. */
  10050. function $ExceptionHandlerProvider() {
  10051. this.$get = ['$log', function($log) {
  10052. return function(exception, cause) {
  10053. $log.error.apply($log, arguments);
  10054. };
  10055. }];
  10056. }
  10057. var $$ForceReflowProvider = /** @this */ function() {
  10058. this.$get = ['$document', function($document) {
  10059. return function(domNode) {
  10060. //the line below will force the browser to perform a repaint so
  10061. //that all the animated elements within the animation frame will
  10062. //be properly updated and drawn on screen. This is required to
  10063. //ensure that the preparation animation is properly flushed so that
  10064. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  10065. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  10066. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  10067. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  10068. if (domNode) {
  10069. if (!domNode.nodeType && domNode instanceof jqLite) {
  10070. domNode = domNode[0];
  10071. }
  10072. } else {
  10073. domNode = $document[0].body;
  10074. }
  10075. return domNode.offsetWidth + 1;
  10076. };
  10077. }];
  10078. };
  10079. var APPLICATION_JSON = 'application/json';
  10080. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  10081. var JSON_START = /^\[|^\{(?!\{)/;
  10082. var JSON_ENDS = {
  10083. '[': /]$/,
  10084. '{': /}$/
  10085. };
  10086. var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/;
  10087. var $httpMinErr = minErr('$http');
  10088. function serializeValue(v) {
  10089. if (isObject(v)) {
  10090. return isDate(v) ? v.toISOString() : toJson(v);
  10091. }
  10092. return v;
  10093. }
  10094. /** @this */
  10095. function $HttpParamSerializerProvider() {
  10096. /**
  10097. * @ngdoc service
  10098. * @name $httpParamSerializer
  10099. * @description
  10100. *
  10101. * Default {@link $http `$http`} params serializer that converts objects to strings
  10102. * according to the following rules:
  10103. *
  10104. * * `{'foo': 'bar'}` results in `foo=bar`
  10105. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  10106. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  10107. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
  10108. *
  10109. * Note that serializer will sort the request parameters alphabetically.
  10110. * */
  10111. this.$get = function() {
  10112. return function ngParamSerializer(params) {
  10113. if (!params) return '';
  10114. var parts = [];
  10115. forEachSorted(params, function(value, key) {
  10116. if (value === null || isUndefined(value) || isFunction(value)) return;
  10117. if (isArray(value)) {
  10118. forEach(value, function(v) {
  10119. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  10120. });
  10121. } else {
  10122. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  10123. }
  10124. });
  10125. return parts.join('&');
  10126. };
  10127. };
  10128. }
  10129. /** @this */
  10130. function $HttpParamSerializerJQLikeProvider() {
  10131. /**
  10132. * @ngdoc service
  10133. * @name $httpParamSerializerJQLike
  10134. *
  10135. * @description
  10136. *
  10137. * Alternative {@link $http `$http`} params serializer that follows
  10138. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  10139. * The serializer will also sort the params alphabetically.
  10140. *
  10141. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  10142. *
  10143. * ```js
  10144. * $http({
  10145. * url: myUrl,
  10146. * method: 'GET',
  10147. * params: myParams,
  10148. * paramSerializer: '$httpParamSerializerJQLike'
  10149. * });
  10150. * ```
  10151. *
  10152. * It is also possible to set it as the default `paramSerializer` in the
  10153. * {@link $httpProvider#defaults `$httpProvider`}.
  10154. *
  10155. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  10156. * form data for submission:
  10157. *
  10158. * ```js
  10159. * .controller(function($http, $httpParamSerializerJQLike) {
  10160. * //...
  10161. *
  10162. * $http({
  10163. * url: myUrl,
  10164. * method: 'POST',
  10165. * data: $httpParamSerializerJQLike(myData),
  10166. * headers: {
  10167. * 'Content-Type': 'application/x-www-form-urlencoded'
  10168. * }
  10169. * });
  10170. *
  10171. * });
  10172. * ```
  10173. *
  10174. * */
  10175. this.$get = function() {
  10176. return function jQueryLikeParamSerializer(params) {
  10177. if (!params) return '';
  10178. var parts = [];
  10179. serialize(params, '', true);
  10180. return parts.join('&');
  10181. function serialize(toSerialize, prefix, topLevel) {
  10182. if (toSerialize === null || isUndefined(toSerialize)) return;
  10183. if (isArray(toSerialize)) {
  10184. forEach(toSerialize, function(value, index) {
  10185. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  10186. });
  10187. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  10188. forEachSorted(toSerialize, function(value, key) {
  10189. serialize(value, prefix +
  10190. (topLevel ? '' : '[') +
  10191. key +
  10192. (topLevel ? '' : ']'));
  10193. });
  10194. } else {
  10195. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  10196. }
  10197. }
  10198. };
  10199. };
  10200. }
  10201. function defaultHttpResponseTransform(data, headers) {
  10202. if (isString(data)) {
  10203. // Strip json vulnerability protection prefix and trim whitespace
  10204. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  10205. if (tempData) {
  10206. var contentType = headers('Content-Type');
  10207. var hasJsonContentType = contentType && (contentType.indexOf(APPLICATION_JSON) === 0);
  10208. if (hasJsonContentType || isJsonLike(tempData)) {
  10209. try {
  10210. data = fromJson(tempData);
  10211. } catch (e) {
  10212. if (!hasJsonContentType) {
  10213. return data;
  10214. }
  10215. throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' +
  10216. 'Parse error: "{1}"', data, e);
  10217. }
  10218. }
  10219. }
  10220. }
  10221. return data;
  10222. }
  10223. function isJsonLike(str) {
  10224. var jsonStart = str.match(JSON_START);
  10225. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  10226. }
  10227. /**
  10228. * Parse headers into key value object
  10229. *
  10230. * @param {string} headers Raw headers as a string
  10231. * @returns {Object} Parsed headers as key value object
  10232. */
  10233. function parseHeaders(headers) {
  10234. var parsed = createMap(), i;
  10235. function fillInParsed(key, val) {
  10236. if (key) {
  10237. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  10238. }
  10239. }
  10240. if (isString(headers)) {
  10241. forEach(headers.split('\n'), function(line) {
  10242. i = line.indexOf(':');
  10243. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  10244. });
  10245. } else if (isObject(headers)) {
  10246. forEach(headers, function(headerVal, headerKey) {
  10247. fillInParsed(lowercase(headerKey), trim(headerVal));
  10248. });
  10249. }
  10250. return parsed;
  10251. }
  10252. /**
  10253. * Returns a function that provides access to parsed headers.
  10254. *
  10255. * Headers are lazy parsed when first requested.
  10256. * @see parseHeaders
  10257. *
  10258. * @param {(string|Object)} headers Headers to provide access to.
  10259. * @returns {function(string=)} Returns a getter function which if called with:
  10260. *
  10261. * - if called with an argument returns a single header value or null
  10262. * - if called with no arguments returns an object containing all headers.
  10263. */
  10264. function headersGetter(headers) {
  10265. var headersObj;
  10266. return function(name) {
  10267. if (!headersObj) headersObj = parseHeaders(headers);
  10268. if (name) {
  10269. var value = headersObj[lowercase(name)];
  10270. if (value === undefined) {
  10271. value = null;
  10272. }
  10273. return value;
  10274. }
  10275. return headersObj;
  10276. };
  10277. }
  10278. /**
  10279. * Chain all given functions
  10280. *
  10281. * This function is used for both request and response transforming
  10282. *
  10283. * @param {*} data Data to transform.
  10284. * @param {function(string=)} headers HTTP headers getter fn.
  10285. * @param {number} status HTTP status code of the response.
  10286. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  10287. * @returns {*} Transformed data.
  10288. */
  10289. function transformData(data, headers, status, fns) {
  10290. if (isFunction(fns)) {
  10291. return fns(data, headers, status);
  10292. }
  10293. forEach(fns, function(fn) {
  10294. data = fn(data, headers, status);
  10295. });
  10296. return data;
  10297. }
  10298. function isSuccess(status) {
  10299. return 200 <= status && status < 300;
  10300. }
  10301. /**
  10302. * @ngdoc provider
  10303. * @name $httpProvider
  10304. * @this
  10305. *
  10306. * @description
  10307. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  10308. * */
  10309. function $HttpProvider() {
  10310. /**
  10311. * @ngdoc property
  10312. * @name $httpProvider#defaults
  10313. * @description
  10314. *
  10315. * Object containing default values for all {@link ng.$http $http} requests.
  10316. *
  10317. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  10318. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  10319. * by default. See {@link $http#caching $http Caching} for more information.
  10320. *
  10321. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  10322. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  10323. * setting default headers.
  10324. * - **`defaults.headers.common`**
  10325. * - **`defaults.headers.post`**
  10326. * - **`defaults.headers.put`**
  10327. * - **`defaults.headers.patch`**
  10328. *
  10329. * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the
  10330. * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the
  10331. * {@link $jsonpCallbacks} service. Defaults to `'callback'`.
  10332. *
  10333. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  10334. * used to the prepare string representation of request parameters (specified as an object).
  10335. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  10336. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  10337. *
  10338. * - **`defaults.transformRequest`** -
  10339. * `{Array<function(data, headersGetter)>|function(data, headersGetter)}` -
  10340. * An array of functions (or a single function) which are applied to the request data.
  10341. * By default, this is an array with one request transformation function:
  10342. *
  10343. * - If the `data` property of the request configuration object contains an object, serialize it
  10344. * into JSON format.
  10345. *
  10346. * - **`defaults.transformResponse`** -
  10347. * `{Array<function(data, headersGetter, status)>|function(data, headersGetter, status)}` -
  10348. * An array of functions (or a single function) which are applied to the response data. By default,
  10349. * this is an array which applies one response transformation function that does two things:
  10350. *
  10351. * - If XSRF prefix is detected, strip it
  10352. * (see {@link ng.$http#security-considerations Security Considerations in the $http docs}).
  10353. * - If the `Content-Type` is `application/json` or the response looks like JSON,
  10354. * deserialize it using a JSON parser.
  10355. *
  10356. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  10357. * Defaults value is `'XSRF-TOKEN'`.
  10358. *
  10359. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  10360. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  10361. *
  10362. **/
  10363. var defaults = this.defaults = {
  10364. // transform incoming response data
  10365. transformResponse: [defaultHttpResponseTransform],
  10366. // transform outgoing request data
  10367. transformRequest: [function(d) {
  10368. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  10369. }],
  10370. // default headers
  10371. headers: {
  10372. common: {
  10373. 'Accept': 'application/json, text/plain, */*'
  10374. },
  10375. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10376. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10377. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  10378. },
  10379. xsrfCookieName: 'XSRF-TOKEN',
  10380. xsrfHeaderName: 'X-XSRF-TOKEN',
  10381. paramSerializer: '$httpParamSerializer',
  10382. jsonpCallbackParam: 'callback'
  10383. };
  10384. var useApplyAsync = false;
  10385. /**
  10386. * @ngdoc method
  10387. * @name $httpProvider#useApplyAsync
  10388. * @description
  10389. *
  10390. * Configure $http service to combine processing of multiple http responses received at around
  10391. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  10392. * significant performance improvement for bigger applications that make many HTTP requests
  10393. * concurrently (common during application bootstrap).
  10394. *
  10395. * Defaults to false. If no value is specified, returns the current configured value.
  10396. *
  10397. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  10398. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  10399. * to load and share the same digest cycle.
  10400. *
  10401. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  10402. * otherwise, returns the current configured value.
  10403. **/
  10404. this.useApplyAsync = function(value) {
  10405. if (isDefined(value)) {
  10406. useApplyAsync = !!value;
  10407. return this;
  10408. }
  10409. return useApplyAsync;
  10410. };
  10411. /**
  10412. * @ngdoc property
  10413. * @name $httpProvider#interceptors
  10414. * @description
  10415. *
  10416. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  10417. * pre-processing of request or postprocessing of responses.
  10418. *
  10419. * These service factories are ordered by request, i.e. they are applied in the same order as the
  10420. * array, on request, but reverse order, on response.
  10421. *
  10422. * {@link ng.$http#interceptors Interceptors detailed info}
  10423. **/
  10424. var interceptorFactories = this.interceptors = [];
  10425. this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
  10426. function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {
  10427. var defaultCache = $cacheFactory('$http');
  10428. /**
  10429. * Make sure that default param serializer is exposed as a function
  10430. */
  10431. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  10432. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  10433. /**
  10434. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  10435. * The reversal is needed so that we can build up the interception chain around the
  10436. * server request.
  10437. */
  10438. var reversedInterceptors = [];
  10439. forEach(interceptorFactories, function(interceptorFactory) {
  10440. reversedInterceptors.unshift(isString(interceptorFactory)
  10441. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  10442. });
  10443. /**
  10444. * @ngdoc service
  10445. * @kind function
  10446. * @name $http
  10447. * @requires ng.$httpBackend
  10448. * @requires $cacheFactory
  10449. * @requires $rootScope
  10450. * @requires $q
  10451. * @requires $injector
  10452. *
  10453. * @description
  10454. * The `$http` service is a core Angular service that facilitates communication with the remote
  10455. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  10456. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  10457. *
  10458. * For unit testing applications that use `$http` service, see
  10459. * {@link ngMock.$httpBackend $httpBackend mock}.
  10460. *
  10461. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  10462. * $resource} service.
  10463. *
  10464. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  10465. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  10466. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  10467. *
  10468. *
  10469. * ## General usage
  10470. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  10471. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  10472. *
  10473. * ```js
  10474. * // Simple GET request example:
  10475. * $http({
  10476. * method: 'GET',
  10477. * url: '/someUrl'
  10478. * }).then(function successCallback(response) {
  10479. * // this callback will be called asynchronously
  10480. * // when the response is available
  10481. * }, function errorCallback(response) {
  10482. * // called asynchronously if an error occurs
  10483. * // or server returns response with an error status.
  10484. * });
  10485. * ```
  10486. *
  10487. * The response object has these properties:
  10488. *
  10489. * - **data** – `{string|Object}` – The response body transformed with the transform
  10490. * functions.
  10491. * - **status** – `{number}` – HTTP status code of the response.
  10492. * - **headers** – `{function([headerName])}` – Header getter function.
  10493. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  10494. * - **statusText** – `{string}` – HTTP status text of the response.
  10495. * - **xhrStatus** – `{string}` – Status of the XMLHttpRequest (`complete`, `error`, `timeout` or `abort`).
  10496. *
  10497. * A response status code between 200 and 299 is considered a success status and will result in
  10498. * the success callback being called. Any response status code outside of that range is
  10499. * considered an error status and will result in the error callback being called.
  10500. * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
  10501. * aborted, e.g. using a `config.timeout`.
  10502. * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
  10503. * that the outcome (success or error) will be determined by the final response status code.
  10504. *
  10505. *
  10506. * ## Shortcut methods
  10507. *
  10508. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  10509. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  10510. * last argument.
  10511. *
  10512. * ```js
  10513. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  10514. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  10515. * ```
  10516. *
  10517. * Complete list of shortcut methods:
  10518. *
  10519. * - {@link ng.$http#get $http.get}
  10520. * - {@link ng.$http#head $http.head}
  10521. * - {@link ng.$http#post $http.post}
  10522. * - {@link ng.$http#put $http.put}
  10523. * - {@link ng.$http#delete $http.delete}
  10524. * - {@link ng.$http#jsonp $http.jsonp}
  10525. * - {@link ng.$http#patch $http.patch}
  10526. *
  10527. *
  10528. * ## Writing Unit Tests that use $http
  10529. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  10530. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  10531. * request using trained responses.
  10532. *
  10533. * ```
  10534. * $httpBackend.expectGET(...);
  10535. * $http.get(...);
  10536. * $httpBackend.flush();
  10537. * ```
  10538. *
  10539. * ## Setting HTTP Headers
  10540. *
  10541. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  10542. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  10543. * object, which currently contains this default configuration:
  10544. *
  10545. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  10546. * - <code>Accept: application/json, text/plain, \*&#65279;/&#65279;\*</code>
  10547. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  10548. * - `Content-Type: application/json`
  10549. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  10550. * - `Content-Type: application/json`
  10551. *
  10552. * To add or overwrite these defaults, simply add or remove a property from these configuration
  10553. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  10554. * with the lowercased HTTP method name as the key, e.g.
  10555. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  10556. *
  10557. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  10558. * fashion. For example:
  10559. *
  10560. * ```
  10561. * module.run(function($http) {
  10562. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  10563. * });
  10564. * ```
  10565. *
  10566. * In addition, you can supply a `headers` property in the config object passed when
  10567. * calling `$http(config)`, which overrides the defaults without changing them globally.
  10568. *
  10569. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  10570. * Use the `headers` property, setting the desired header to `undefined`. For example:
  10571. *
  10572. * ```js
  10573. * var req = {
  10574. * method: 'POST',
  10575. * url: 'http://example.com',
  10576. * headers: {
  10577. * 'Content-Type': undefined
  10578. * },
  10579. * data: { test: 'test' }
  10580. * }
  10581. *
  10582. * $http(req).then(function(){...}, function(){...});
  10583. * ```
  10584. *
  10585. * ## Transforming Requests and Responses
  10586. *
  10587. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  10588. * and `transformResponse`. These properties can be a single function that returns
  10589. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  10590. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  10591. *
  10592. * <div class="alert alert-warning">
  10593. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  10594. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  10595. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  10596. * function will be reflected on the scope and in any templates where the object is data-bound.
  10597. * To prevent this, transform functions should have no side-effects.
  10598. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  10599. * </div>
  10600. *
  10601. * ### Default Transformations
  10602. *
  10603. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  10604. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  10605. * then these will be applied.
  10606. *
  10607. * You can augment or replace the default transformations by modifying these properties by adding to or
  10608. * replacing the array.
  10609. *
  10610. * Angular provides the following default transformations:
  10611. *
  10612. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`) is
  10613. * an array with one function that does the following:
  10614. *
  10615. * - If the `data` property of the request configuration object contains an object, serialize it
  10616. * into JSON format.
  10617. *
  10618. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`) is
  10619. * an array with one function that does the following:
  10620. *
  10621. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  10622. * - If the `Content-Type` is `application/json` or the response looks like JSON,
  10623. * deserialize it using a JSON parser.
  10624. *
  10625. *
  10626. * ### Overriding the Default Transformations Per Request
  10627. *
  10628. * If you wish to override the request/response transformations only for a single request then provide
  10629. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  10630. * into `$http`.
  10631. *
  10632. * Note that if you provide these properties on the config object the default transformations will be
  10633. * overwritten. If you wish to augment the default transformations then you must include them in your
  10634. * local transformation array.
  10635. *
  10636. * The following code demonstrates adding a new response transformation to be run after the default response
  10637. * transformations have been run.
  10638. *
  10639. * ```js
  10640. * function appendTransform(defaults, transform) {
  10641. *
  10642. * // We can't guarantee that the default transformation is an array
  10643. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  10644. *
  10645. * // Append the new transformation to the defaults
  10646. * return defaults.concat(transform);
  10647. * }
  10648. *
  10649. * $http({
  10650. * url: '...',
  10651. * method: 'GET',
  10652. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  10653. * return doTransform(value);
  10654. * })
  10655. * });
  10656. * ```
  10657. *
  10658. *
  10659. * ## Caching
  10660. *
  10661. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  10662. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  10663. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  10664. * precedence over the default cache value.
  10665. *
  10666. * In order to:
  10667. * * cache all responses - set the default cache value to TRUE or to a cache object
  10668. * * cache a specific response - set config.cache value to TRUE or to a cache object
  10669. *
  10670. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  10671. * then the default `$cacheFactory("$http")` object is used.
  10672. *
  10673. * The default cache value can be set by updating the
  10674. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  10675. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  10676. *
  10677. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  10678. * the relevant cache object. The next time the same request is made, the response is returned
  10679. * from the cache without sending a request to the server.
  10680. *
  10681. * Take note that:
  10682. *
  10683. * * Only GET and JSONP requests are cached.
  10684. * * The cache key is the request URL including search parameters; headers are not considered.
  10685. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  10686. * * If multiple identical requests are made using the same cache, which is not yet populated,
  10687. * one request will be made to the server and remaining requests will return the same response.
  10688. * * A cache-control header on the response does not affect if or how responses are cached.
  10689. *
  10690. *
  10691. * ## Interceptors
  10692. *
  10693. * Before you start creating interceptors, be sure to understand the
  10694. * {@link ng.$q $q and deferred/promise APIs}.
  10695. *
  10696. * For purposes of global error handling, authentication, or any kind of synchronous or
  10697. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  10698. * able to intercept requests before they are handed to the server and
  10699. * responses before they are handed over to the application code that
  10700. * initiated these requests. The interceptors leverage the {@link ng.$q
  10701. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  10702. *
  10703. * The interceptors are service factories that are registered with the `$httpProvider` by
  10704. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  10705. * injected with dependencies (if specified) and returns the interceptor.
  10706. *
  10707. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  10708. *
  10709. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  10710. * modify the `config` object or create a new one. The function needs to return the `config`
  10711. * object directly, or a promise containing the `config` or a new `config` object.
  10712. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  10713. * resolved with a rejection.
  10714. * * `response`: interceptors get called with http `response` object. The function is free to
  10715. * modify the `response` object or create a new one. The function needs to return the `response`
  10716. * object directly, or as a promise containing the `response` or a new `response` object.
  10717. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  10718. * resolved with a rejection.
  10719. *
  10720. *
  10721. * ```js
  10722. * // register the interceptor as a service
  10723. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  10724. * return {
  10725. * // optional method
  10726. * 'request': function(config) {
  10727. * // do something on success
  10728. * return config;
  10729. * },
  10730. *
  10731. * // optional method
  10732. * 'requestError': function(rejection) {
  10733. * // do something on error
  10734. * if (canRecover(rejection)) {
  10735. * return responseOrNewPromise
  10736. * }
  10737. * return $q.reject(rejection);
  10738. * },
  10739. *
  10740. *
  10741. *
  10742. * // optional method
  10743. * 'response': function(response) {
  10744. * // do something on success
  10745. * return response;
  10746. * },
  10747. *
  10748. * // optional method
  10749. * 'responseError': function(rejection) {
  10750. * // do something on error
  10751. * if (canRecover(rejection)) {
  10752. * return responseOrNewPromise
  10753. * }
  10754. * return $q.reject(rejection);
  10755. * }
  10756. * };
  10757. * });
  10758. *
  10759. * $httpProvider.interceptors.push('myHttpInterceptor');
  10760. *
  10761. *
  10762. * // alternatively, register the interceptor via an anonymous factory
  10763. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  10764. * return {
  10765. * 'request': function(config) {
  10766. * // same as above
  10767. * },
  10768. *
  10769. * 'response': function(response) {
  10770. * // same as above
  10771. * }
  10772. * };
  10773. * });
  10774. * ```
  10775. *
  10776. * ## Security Considerations
  10777. *
  10778. * When designing web applications, consider security threats from:
  10779. *
  10780. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10781. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  10782. *
  10783. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  10784. * pre-configured with strategies that address these issues, but for this to work backend server
  10785. * cooperation is required.
  10786. *
  10787. * ### JSON Vulnerability Protection
  10788. *
  10789. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10790. * allows third party website to turn your JSON resource URL into
  10791. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  10792. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  10793. * Angular will automatically strip the prefix before processing it as JSON.
  10794. *
  10795. * For example if your server needs to return:
  10796. * ```js
  10797. * ['one','two']
  10798. * ```
  10799. *
  10800. * which is vulnerable to attack, your server can return:
  10801. * ```js
  10802. * )]}',
  10803. * ['one','two']
  10804. * ```
  10805. *
  10806. * Angular will strip the prefix, before processing the JSON.
  10807. *
  10808. *
  10809. * ### Cross Site Request Forgery (XSRF) Protection
  10810. *
  10811. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  10812. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  10813. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  10814. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  10815. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  10816. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  10817. * The header will not be set for cross-domain requests.
  10818. *
  10819. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  10820. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  10821. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  10822. * that only JavaScript running on your domain could have sent the request. The token must be
  10823. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  10824. * making up its own tokens). We recommend that the token is a digest of your site's
  10825. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  10826. * for added security.
  10827. *
  10828. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  10829. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  10830. * or the per-request config object.
  10831. *
  10832. * In order to prevent collisions in environments where multiple Angular apps share the
  10833. * same domain or subdomain, we recommend that each application uses unique cookie name.
  10834. *
  10835. * @param {object} config Object describing the request to be made and how it should be
  10836. * processed. The object has following properties:
  10837. *
  10838. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  10839. * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;
  10840. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10841. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  10842. * with the `paramSerializer` and appended as GET parameters.
  10843. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  10844. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  10845. * HTTP headers to send to the server. If the return value of a function is null, the
  10846. * header will not be sent. Functions accept a config object as an argument.
  10847. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  10848. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  10849. * The handler will be called in the context of a `$apply` block.
  10850. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  10851. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  10852. * The handler will be called in the context of a `$apply` block.
  10853. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  10854. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  10855. * - **transformRequest** –
  10856. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  10857. * transform function or an array of such functions. The transform function takes the http
  10858. * request body and headers and returns its transformed (typically serialized) version.
  10859. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10860. * Overriding the Default Transformations}
  10861. * - **transformResponse** –
  10862. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  10863. * transform function or an array of such functions. The transform function takes the http
  10864. * response body, headers and status and returns its transformed (typically deserialized) version.
  10865. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10866. * Overriding the Default Transformations}
  10867. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  10868. * prepare the string representation of request parameters (specified as an object).
  10869. * If specified as string, it is interpreted as function registered with the
  10870. * {@link $injector $injector}, which means you can create your own serializer
  10871. * by registering it as a {@link auto.$provide#service service}.
  10872. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  10873. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  10874. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  10875. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  10876. * See {@link $http#caching $http Caching} for more information.
  10877. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  10878. * that should abort the request when resolved.
  10879. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  10880. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  10881. * for more information.
  10882. * - **responseType** - `{string}` - see
  10883. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  10884. *
  10885. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  10886. * when the request succeeds or fails.
  10887. *
  10888. *
  10889. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  10890. * requests. This is primarily meant to be used for debugging purposes.
  10891. *
  10892. *
  10893. * @example
  10894. <example module="httpExample" name="http-service">
  10895. <file name="index.html">
  10896. <div ng-controller="FetchController">
  10897. <select ng-model="method" aria-label="Request method">
  10898. <option>GET</option>
  10899. <option>JSONP</option>
  10900. </select>
  10901. <input type="text" ng-model="url" size="80" aria-label="URL" />
  10902. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  10903. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  10904. <button id="samplejsonpbtn"
  10905. ng-click="updateModel('JSONP',
  10906. 'https://angularjs.org/greet.php?name=Super%20Hero')">
  10907. Sample JSONP
  10908. </button>
  10909. <button id="invalidjsonpbtn"
  10910. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')">
  10911. Invalid JSONP
  10912. </button>
  10913. <pre>http status code: {{status}}</pre>
  10914. <pre>http response data: {{data}}</pre>
  10915. </div>
  10916. </file>
  10917. <file name="script.js">
  10918. angular.module('httpExample', [])
  10919. .config(['$sceDelegateProvider', function($sceDelegateProvider) {
  10920. // We must whitelist the JSONP endpoint that we are using to show that we trust it
  10921. $sceDelegateProvider.resourceUrlWhitelist([
  10922. 'self',
  10923. 'https://angularjs.org/**'
  10924. ]);
  10925. }])
  10926. .controller('FetchController', ['$scope', '$http', '$templateCache',
  10927. function($scope, $http, $templateCache) {
  10928. $scope.method = 'GET';
  10929. $scope.url = 'http-hello.html';
  10930. $scope.fetch = function() {
  10931. $scope.code = null;
  10932. $scope.response = null;
  10933. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  10934. then(function(response) {
  10935. $scope.status = response.status;
  10936. $scope.data = response.data;
  10937. }, function(response) {
  10938. $scope.data = response.data || 'Request failed';
  10939. $scope.status = response.status;
  10940. });
  10941. };
  10942. $scope.updateModel = function(method, url) {
  10943. $scope.method = method;
  10944. $scope.url = url;
  10945. };
  10946. }]);
  10947. </file>
  10948. <file name="http-hello.html">
  10949. Hello, $http!
  10950. </file>
  10951. <file name="protractor.js" type="protractor">
  10952. var status = element(by.binding('status'));
  10953. var data = element(by.binding('data'));
  10954. var fetchBtn = element(by.id('fetchbtn'));
  10955. var sampleGetBtn = element(by.id('samplegetbtn'));
  10956. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  10957. it('should make an xhr GET request', function() {
  10958. sampleGetBtn.click();
  10959. fetchBtn.click();
  10960. expect(status.getText()).toMatch('200');
  10961. expect(data.getText()).toMatch(/Hello, \$http!/);
  10962. });
  10963. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  10964. // it('should make a JSONP request to angularjs.org', function() {
  10965. // var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  10966. // sampleJsonpBtn.click();
  10967. // fetchBtn.click();
  10968. // expect(status.getText()).toMatch('200');
  10969. // expect(data.getText()).toMatch(/Super Hero!/);
  10970. // });
  10971. it('should make JSONP request to invalid URL and invoke the error handler',
  10972. function() {
  10973. invalidJsonpBtn.click();
  10974. fetchBtn.click();
  10975. expect(status.getText()).toMatch('0');
  10976. expect(data.getText()).toMatch('Request failed');
  10977. });
  10978. </file>
  10979. </example>
  10980. */
  10981. function $http(requestConfig) {
  10982. if (!isObject(requestConfig)) {
  10983. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  10984. }
  10985. if (!isString($sce.valueOf(requestConfig.url))) {
  10986. throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);
  10987. }
  10988. var config = extend({
  10989. method: 'get',
  10990. transformRequest: defaults.transformRequest,
  10991. transformResponse: defaults.transformResponse,
  10992. paramSerializer: defaults.paramSerializer,
  10993. jsonpCallbackParam: defaults.jsonpCallbackParam
  10994. }, requestConfig);
  10995. config.headers = mergeHeaders(requestConfig);
  10996. config.method = uppercase(config.method);
  10997. config.paramSerializer = isString(config.paramSerializer) ?
  10998. $injector.get(config.paramSerializer) : config.paramSerializer;
  10999. $browser.$$incOutstandingRequestCount();
  11000. var requestInterceptors = [];
  11001. var responseInterceptors = [];
  11002. var promise = $q.resolve(config);
  11003. // apply interceptors
  11004. forEach(reversedInterceptors, function(interceptor) {
  11005. if (interceptor.request || interceptor.requestError) {
  11006. requestInterceptors.unshift(interceptor.request, interceptor.requestError);
  11007. }
  11008. if (interceptor.response || interceptor.responseError) {
  11009. responseInterceptors.push(interceptor.response, interceptor.responseError);
  11010. }
  11011. });
  11012. promise = chainInterceptors(promise, requestInterceptors);
  11013. promise = promise.then(serverRequest);
  11014. promise = chainInterceptors(promise, responseInterceptors);
  11015. promise = promise.finally(completeOutstandingRequest);
  11016. return promise;
  11017. function chainInterceptors(promise, interceptors) {
  11018. for (var i = 0, ii = interceptors.length; i < ii;) {
  11019. var thenFn = interceptors[i++];
  11020. var rejectFn = interceptors[i++];
  11021. promise = promise.then(thenFn, rejectFn);
  11022. }
  11023. interceptors.length = 0;
  11024. return promise;
  11025. }
  11026. function completeOutstandingRequest() {
  11027. $browser.$$completeOutstandingRequest(noop);
  11028. }
  11029. function executeHeaderFns(headers, config) {
  11030. var headerContent, processedHeaders = {};
  11031. forEach(headers, function(headerFn, header) {
  11032. if (isFunction(headerFn)) {
  11033. headerContent = headerFn(config);
  11034. if (headerContent != null) {
  11035. processedHeaders[header] = headerContent;
  11036. }
  11037. } else {
  11038. processedHeaders[header] = headerFn;
  11039. }
  11040. });
  11041. return processedHeaders;
  11042. }
  11043. function mergeHeaders(config) {
  11044. var defHeaders = defaults.headers,
  11045. reqHeaders = extend({}, config.headers),
  11046. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  11047. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  11048. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  11049. defaultHeadersIteration:
  11050. for (defHeaderName in defHeaders) {
  11051. lowercaseDefHeaderName = lowercase(defHeaderName);
  11052. for (reqHeaderName in reqHeaders) {
  11053. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  11054. continue defaultHeadersIteration;
  11055. }
  11056. }
  11057. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  11058. }
  11059. // execute if header value is a function for merged headers
  11060. return executeHeaderFns(reqHeaders, shallowCopy(config));
  11061. }
  11062. function serverRequest(config) {
  11063. var headers = config.headers;
  11064. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  11065. // strip content-type if data is undefined
  11066. if (isUndefined(reqData)) {
  11067. forEach(headers, function(value, header) {
  11068. if (lowercase(header) === 'content-type') {
  11069. delete headers[header];
  11070. }
  11071. });
  11072. }
  11073. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  11074. config.withCredentials = defaults.withCredentials;
  11075. }
  11076. // send request
  11077. return sendReq(config, reqData).then(transformResponse, transformResponse);
  11078. }
  11079. function transformResponse(response) {
  11080. // make a copy since the response must be cacheable
  11081. var resp = extend({}, response);
  11082. resp.data = transformData(response.data, response.headers, response.status,
  11083. config.transformResponse);
  11084. return (isSuccess(response.status))
  11085. ? resp
  11086. : $q.reject(resp);
  11087. }
  11088. }
  11089. $http.pendingRequests = [];
  11090. /**
  11091. * @ngdoc method
  11092. * @name $http#get
  11093. *
  11094. * @description
  11095. * Shortcut method to perform `GET` request.
  11096. *
  11097. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11098. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11099. * @param {Object=} config Optional configuration object
  11100. * @returns {HttpPromise} Future object
  11101. */
  11102. /**
  11103. * @ngdoc method
  11104. * @name $http#delete
  11105. *
  11106. * @description
  11107. * Shortcut method to perform `DELETE` request.
  11108. *
  11109. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11110. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11111. * @param {Object=} config Optional configuration object
  11112. * @returns {HttpPromise} Future object
  11113. */
  11114. /**
  11115. * @ngdoc method
  11116. * @name $http#head
  11117. *
  11118. * @description
  11119. * Shortcut method to perform `HEAD` request.
  11120. *
  11121. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11122. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11123. * @param {Object=} config Optional configuration object
  11124. * @returns {HttpPromise} Future object
  11125. */
  11126. /**
  11127. * @ngdoc method
  11128. * @name $http#jsonp
  11129. *
  11130. * @description
  11131. * Shortcut method to perform `JSONP` request.
  11132. *
  11133. * Note that, since JSONP requests are sensitive because the response is given full access to the browser,
  11134. * the url must be declared, via {@link $sce} as a trusted resource URL.
  11135. * You can trust a URL by adding it to the whitelist via
  11136. * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or
  11137. * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.
  11138. *
  11139. * JSONP requests must specify a callback to be used in the response from the server. This callback
  11140. * is passed as a query parameter in the request. You must specify the name of this parameter by
  11141. * setting the `jsonpCallbackParam` property on the request config object.
  11142. *
  11143. * ```
  11144. * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
  11145. * ```
  11146. *
  11147. * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.
  11148. * Initially this is set to `'callback'`.
  11149. *
  11150. * <div class="alert alert-danger">
  11151. * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback
  11152. * parameter value should go.
  11153. * </div>
  11154. *
  11155. * If you would like to customise where and how the callbacks are stored then try overriding
  11156. * or decorating the {@link $jsonpCallbacks} service.
  11157. *
  11158. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11159. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11160. * @param {Object=} config Optional configuration object
  11161. * @returns {HttpPromise} Future object
  11162. */
  11163. createShortMethods('get', 'delete', 'head', 'jsonp');
  11164. /**
  11165. * @ngdoc method
  11166. * @name $http#post
  11167. *
  11168. * @description
  11169. * Shortcut method to perform `POST` request.
  11170. *
  11171. * @param {string} url Relative or absolute URL specifying the destination of the request
  11172. * @param {*} data Request content
  11173. * @param {Object=} config Optional configuration object
  11174. * @returns {HttpPromise} Future object
  11175. */
  11176. /**
  11177. * @ngdoc method
  11178. * @name $http#put
  11179. *
  11180. * @description
  11181. * Shortcut method to perform `PUT` request.
  11182. *
  11183. * @param {string} url Relative or absolute URL specifying the destination of the request
  11184. * @param {*} data Request content
  11185. * @param {Object=} config Optional configuration object
  11186. * @returns {HttpPromise} Future object
  11187. */
  11188. /**
  11189. * @ngdoc method
  11190. * @name $http#patch
  11191. *
  11192. * @description
  11193. * Shortcut method to perform `PATCH` request.
  11194. *
  11195. * @param {string} url Relative or absolute URL specifying the destination of the request
  11196. * @param {*} data Request content
  11197. * @param {Object=} config Optional configuration object
  11198. * @returns {HttpPromise} Future object
  11199. */
  11200. createShortMethodsWithData('post', 'put', 'patch');
  11201. /**
  11202. * @ngdoc property
  11203. * @name $http#defaults
  11204. *
  11205. * @description
  11206. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  11207. * default headers, withCredentials as well as request and response transformations.
  11208. *
  11209. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  11210. */
  11211. $http.defaults = defaults;
  11212. return $http;
  11213. function createShortMethods(names) {
  11214. forEach(arguments, function(name) {
  11215. $http[name] = function(url, config) {
  11216. return $http(extend({}, config || {}, {
  11217. method: name,
  11218. url: url
  11219. }));
  11220. };
  11221. });
  11222. }
  11223. function createShortMethodsWithData(name) {
  11224. forEach(arguments, function(name) {
  11225. $http[name] = function(url, data, config) {
  11226. return $http(extend({}, config || {}, {
  11227. method: name,
  11228. url: url,
  11229. data: data
  11230. }));
  11231. };
  11232. });
  11233. }
  11234. /**
  11235. * Makes the request.
  11236. *
  11237. * !!! ACCESSES CLOSURE VARS:
  11238. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  11239. */
  11240. function sendReq(config, reqData) {
  11241. var deferred = $q.defer(),
  11242. promise = deferred.promise,
  11243. cache,
  11244. cachedResp,
  11245. reqHeaders = config.headers,
  11246. isJsonp = lowercase(config.method) === 'jsonp',
  11247. url = config.url;
  11248. if (isJsonp) {
  11249. // JSONP is a pretty sensitive operation where we're allowing a script to have full access to
  11250. // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.
  11251. url = $sce.getTrustedResourceUrl(url);
  11252. } else if (!isString(url)) {
  11253. // If it is not a string then the URL must be a $sce trusted object
  11254. url = $sce.valueOf(url);
  11255. }
  11256. url = buildUrl(url, config.paramSerializer(config.params));
  11257. if (isJsonp) {
  11258. // Check the url and add the JSONP callback placeholder
  11259. url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);
  11260. }
  11261. $http.pendingRequests.push(config);
  11262. promise.then(removePendingReq, removePendingReq);
  11263. if ((config.cache || defaults.cache) && config.cache !== false &&
  11264. (config.method === 'GET' || config.method === 'JSONP')) {
  11265. cache = isObject(config.cache) ? config.cache
  11266. : isObject(/** @type {?} */ (defaults).cache)
  11267. ? /** @type {?} */ (defaults).cache
  11268. : defaultCache;
  11269. }
  11270. if (cache) {
  11271. cachedResp = cache.get(url);
  11272. if (isDefined(cachedResp)) {
  11273. if (isPromiseLike(cachedResp)) {
  11274. // cached request has already been sent, but there is no response yet
  11275. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  11276. } else {
  11277. // serving from cache
  11278. if (isArray(cachedResp)) {
  11279. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3], cachedResp[4]);
  11280. } else {
  11281. resolvePromise(cachedResp, 200, {}, 'OK', 'complete');
  11282. }
  11283. }
  11284. } else {
  11285. // put the promise for the non-transformed response into cache as a placeholder
  11286. cache.put(url, promise);
  11287. }
  11288. }
  11289. // if we won't have the response in cache, set the xsrf headers and
  11290. // send the request to the backend
  11291. if (isUndefined(cachedResp)) {
  11292. var xsrfValue = urlIsSameOrigin(config.url)
  11293. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  11294. : undefined;
  11295. if (xsrfValue) {
  11296. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  11297. }
  11298. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  11299. config.withCredentials, config.responseType,
  11300. createApplyHandlers(config.eventHandlers),
  11301. createApplyHandlers(config.uploadEventHandlers));
  11302. }
  11303. return promise;
  11304. function createApplyHandlers(eventHandlers) {
  11305. if (eventHandlers) {
  11306. var applyHandlers = {};
  11307. forEach(eventHandlers, function(eventHandler, key) {
  11308. applyHandlers[key] = function(event) {
  11309. if (useApplyAsync) {
  11310. $rootScope.$applyAsync(callEventHandler);
  11311. } else if ($rootScope.$$phase) {
  11312. callEventHandler();
  11313. } else {
  11314. $rootScope.$apply(callEventHandler);
  11315. }
  11316. function callEventHandler() {
  11317. eventHandler(event);
  11318. }
  11319. };
  11320. });
  11321. return applyHandlers;
  11322. }
  11323. }
  11324. /**
  11325. * Callback registered to $httpBackend():
  11326. * - caches the response if desired
  11327. * - resolves the raw $http promise
  11328. * - calls $apply
  11329. */
  11330. function done(status, response, headersString, statusText, xhrStatus) {
  11331. if (cache) {
  11332. if (isSuccess(status)) {
  11333. cache.put(url, [status, response, parseHeaders(headersString), statusText, xhrStatus]);
  11334. } else {
  11335. // remove promise from the cache
  11336. cache.remove(url);
  11337. }
  11338. }
  11339. function resolveHttpPromise() {
  11340. resolvePromise(response, status, headersString, statusText, xhrStatus);
  11341. }
  11342. if (useApplyAsync) {
  11343. $rootScope.$applyAsync(resolveHttpPromise);
  11344. } else {
  11345. resolveHttpPromise();
  11346. if (!$rootScope.$$phase) $rootScope.$apply();
  11347. }
  11348. }
  11349. /**
  11350. * Resolves the raw $http promise.
  11351. */
  11352. function resolvePromise(response, status, headers, statusText, xhrStatus) {
  11353. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  11354. status = status >= -1 ? status : 0;
  11355. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  11356. data: response,
  11357. status: status,
  11358. headers: headersGetter(headers),
  11359. config: config,
  11360. statusText: statusText,
  11361. xhrStatus: xhrStatus
  11362. });
  11363. }
  11364. function resolvePromiseWithResult(result) {
  11365. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText, result.xhrStatus);
  11366. }
  11367. function removePendingReq() {
  11368. var idx = $http.pendingRequests.indexOf(config);
  11369. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  11370. }
  11371. }
  11372. function buildUrl(url, serializedParams) {
  11373. if (serializedParams.length > 0) {
  11374. url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
  11375. }
  11376. return url;
  11377. }
  11378. function sanitizeJsonpCallbackParam(url, key) {
  11379. if (/[&?][^=]+=JSON_CALLBACK/.test(url)) {
  11380. // Throw if the url already contains a reference to JSON_CALLBACK
  11381. throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url);
  11382. }
  11383. var callbackParamRegex = new RegExp('[&?]' + key + '=');
  11384. if (callbackParamRegex.test(url)) {
  11385. // Throw if the callback param was already provided
  11386. throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', key, url);
  11387. }
  11388. // Add in the JSON_CALLBACK callback param value
  11389. url += ((url.indexOf('?') === -1) ? '?' : '&') + key + '=JSON_CALLBACK';
  11390. return url;
  11391. }
  11392. }];
  11393. }
  11394. /**
  11395. * @ngdoc service
  11396. * @name $xhrFactory
  11397. * @this
  11398. *
  11399. * @description
  11400. * Factory function used to create XMLHttpRequest objects.
  11401. *
  11402. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  11403. *
  11404. * ```
  11405. * angular.module('myApp', [])
  11406. * .factory('$xhrFactory', function() {
  11407. * return function createXhr(method, url) {
  11408. * return new window.XMLHttpRequest({mozSystem: true});
  11409. * };
  11410. * });
  11411. * ```
  11412. *
  11413. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  11414. * @param {string} url URL of the request.
  11415. */
  11416. function $xhrFactoryProvider() {
  11417. this.$get = function() {
  11418. return function createXhr() {
  11419. return new window.XMLHttpRequest();
  11420. };
  11421. };
  11422. }
  11423. /**
  11424. * @ngdoc service
  11425. * @name $httpBackend
  11426. * @requires $jsonpCallbacks
  11427. * @requires $document
  11428. * @requires $xhrFactory
  11429. * @this
  11430. *
  11431. * @description
  11432. * HTTP backend used by the {@link ng.$http service} that delegates to
  11433. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  11434. *
  11435. * You should never need to use this service directly, instead use the higher-level abstractions:
  11436. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  11437. *
  11438. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  11439. * $httpBackend} which can be trained with responses.
  11440. */
  11441. function $HttpBackendProvider() {
  11442. this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
  11443. return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
  11444. }];
  11445. }
  11446. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  11447. // TODO(vojta): fix the signature
  11448. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  11449. url = url || $browser.url();
  11450. if (lowercase(method) === 'jsonp') {
  11451. var callbackPath = callbacks.createCallback(url);
  11452. var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
  11453. // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
  11454. var response = (status === 200) && callbacks.getResponse(callbackPath);
  11455. completeRequest(callback, status, response, '', text, 'complete');
  11456. callbacks.removeCallback(callbackPath);
  11457. });
  11458. } else {
  11459. var xhr = createXhr(method, url);
  11460. xhr.open(method, url, true);
  11461. forEach(headers, function(value, key) {
  11462. if (isDefined(value)) {
  11463. xhr.setRequestHeader(key, value);
  11464. }
  11465. });
  11466. xhr.onload = function requestLoaded() {
  11467. var statusText = xhr.statusText || '';
  11468. // responseText is the old-school way of retrieving response (supported by IE9)
  11469. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  11470. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  11471. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  11472. var status = xhr.status === 1223 ? 204 : xhr.status;
  11473. // fix status code when it is 0 (0 status is undocumented).
  11474. // Occurs when accessing file resources or on Android 4.1 stock browser
  11475. // while retrieving files from application cache.
  11476. if (status === 0) {
  11477. status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
  11478. }
  11479. completeRequest(callback,
  11480. status,
  11481. response,
  11482. xhr.getAllResponseHeaders(),
  11483. statusText,
  11484. 'complete');
  11485. };
  11486. var requestError = function() {
  11487. // The response is always empty
  11488. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  11489. completeRequest(callback, -1, null, null, '', 'error');
  11490. };
  11491. var requestAborted = function() {
  11492. completeRequest(callback, -1, null, null, '', 'abort');
  11493. };
  11494. var requestTimeout = function() {
  11495. // The response is always empty
  11496. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  11497. completeRequest(callback, -1, null, null, '', 'timeout');
  11498. };
  11499. xhr.onerror = requestError;
  11500. xhr.onabort = requestAborted;
  11501. xhr.ontimeout = requestTimeout;
  11502. forEach(eventHandlers, function(value, key) {
  11503. xhr.addEventListener(key, value);
  11504. });
  11505. forEach(uploadEventHandlers, function(value, key) {
  11506. xhr.upload.addEventListener(key, value);
  11507. });
  11508. if (withCredentials) {
  11509. xhr.withCredentials = true;
  11510. }
  11511. if (responseType) {
  11512. try {
  11513. xhr.responseType = responseType;
  11514. } catch (e) {
  11515. // WebKit added support for the json responseType value on 09/03/2013
  11516. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  11517. // known to throw when setting the value "json" as the response type. Other older
  11518. // browsers implementing the responseType
  11519. //
  11520. // The json response type can be ignored if not supported, because JSON payloads are
  11521. // parsed on the client-side regardless.
  11522. if (responseType !== 'json') {
  11523. throw e;
  11524. }
  11525. }
  11526. }
  11527. xhr.send(isUndefined(post) ? null : post);
  11528. }
  11529. if (timeout > 0) {
  11530. var timeoutId = $browserDefer(timeoutRequest, timeout);
  11531. } else if (isPromiseLike(timeout)) {
  11532. timeout.then(timeoutRequest);
  11533. }
  11534. function timeoutRequest() {
  11535. if (jsonpDone) {
  11536. jsonpDone();
  11537. }
  11538. if (xhr) {
  11539. xhr.abort();
  11540. }
  11541. }
  11542. function completeRequest(callback, status, response, headersString, statusText, xhrStatus) {
  11543. // cancel timeout and subsequent timeout promise resolution
  11544. if (isDefined(timeoutId)) {
  11545. $browserDefer.cancel(timeoutId);
  11546. }
  11547. jsonpDone = xhr = null;
  11548. callback(status, response, headersString, statusText, xhrStatus);
  11549. }
  11550. };
  11551. function jsonpReq(url, callbackPath, done) {
  11552. url = url.replace('JSON_CALLBACK', callbackPath);
  11553. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  11554. // - fetches local scripts via XHR and evals them
  11555. // - adds and immediately removes script elements from the document
  11556. var script = rawDocument.createElement('script'), callback = null;
  11557. script.type = 'text/javascript';
  11558. script.src = url;
  11559. script.async = true;
  11560. callback = function(event) {
  11561. script.removeEventListener('load', callback);
  11562. script.removeEventListener('error', callback);
  11563. rawDocument.body.removeChild(script);
  11564. script = null;
  11565. var status = -1;
  11566. var text = 'unknown';
  11567. if (event) {
  11568. if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
  11569. event = { type: 'error' };
  11570. }
  11571. text = event.type;
  11572. status = event.type === 'error' ? 404 : 200;
  11573. }
  11574. if (done) {
  11575. done(status, text);
  11576. }
  11577. };
  11578. script.addEventListener('load', callback);
  11579. script.addEventListener('error', callback);
  11580. rawDocument.body.appendChild(script);
  11581. return callback;
  11582. }
  11583. }
  11584. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  11585. $interpolateMinErr.throwNoconcat = function(text) {
  11586. throw $interpolateMinErr('noconcat',
  11587. 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
  11588. 'interpolations that concatenate multiple expressions when a trusted value is ' +
  11589. 'required. See http://docs.angularjs.org/api/ng.$sce', text);
  11590. };
  11591. $interpolateMinErr.interr = function(text, err) {
  11592. return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
  11593. };
  11594. /**
  11595. * @ngdoc provider
  11596. * @name $interpolateProvider
  11597. * @this
  11598. *
  11599. * @description
  11600. *
  11601. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  11602. *
  11603. * <div class="alert alert-danger">
  11604. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  11605. * template within a Python Jinja template (or any other template language). Mixing templating
  11606. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  11607. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  11608. * security bugs!
  11609. * </div>
  11610. *
  11611. * @example
  11612. <example name="custom-interpolation-markup" module="customInterpolationApp">
  11613. <file name="index.html">
  11614. <script>
  11615. var customInterpolationApp = angular.module('customInterpolationApp', []);
  11616. customInterpolationApp.config(function($interpolateProvider) {
  11617. $interpolateProvider.startSymbol('//');
  11618. $interpolateProvider.endSymbol('//');
  11619. });
  11620. customInterpolationApp.controller('DemoController', function() {
  11621. this.label = "This binding is brought you by // interpolation symbols.";
  11622. });
  11623. </script>
  11624. <div ng-controller="DemoController as demo">
  11625. //demo.label//
  11626. </div>
  11627. </file>
  11628. <file name="protractor.js" type="protractor">
  11629. it('should interpolate binding with custom symbols', function() {
  11630. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  11631. });
  11632. </file>
  11633. </example>
  11634. */
  11635. function $InterpolateProvider() {
  11636. var startSymbol = '{{';
  11637. var endSymbol = '}}';
  11638. /**
  11639. * @ngdoc method
  11640. * @name $interpolateProvider#startSymbol
  11641. * @description
  11642. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  11643. *
  11644. * @param {string=} value new value to set the starting symbol to.
  11645. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11646. */
  11647. this.startSymbol = function(value) {
  11648. if (value) {
  11649. startSymbol = value;
  11650. return this;
  11651. } else {
  11652. return startSymbol;
  11653. }
  11654. };
  11655. /**
  11656. * @ngdoc method
  11657. * @name $interpolateProvider#endSymbol
  11658. * @description
  11659. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11660. *
  11661. * @param {string=} value new value to set the ending symbol to.
  11662. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11663. */
  11664. this.endSymbol = function(value) {
  11665. if (value) {
  11666. endSymbol = value;
  11667. return this;
  11668. } else {
  11669. return endSymbol;
  11670. }
  11671. };
  11672. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  11673. var startSymbolLength = startSymbol.length,
  11674. endSymbolLength = endSymbol.length,
  11675. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  11676. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  11677. function escape(ch) {
  11678. return '\\\\\\' + ch;
  11679. }
  11680. function unescapeText(text) {
  11681. return text.replace(escapedStartRegexp, startSymbol).
  11682. replace(escapedEndRegexp, endSymbol);
  11683. }
  11684. // TODO: this is the same as the constantWatchDelegate in parse.js
  11685. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  11686. var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  11687. unwatch();
  11688. return constantInterp(scope);
  11689. }, listener, objectEquality);
  11690. return unwatch;
  11691. }
  11692. /**
  11693. * @ngdoc service
  11694. * @name $interpolate
  11695. * @kind function
  11696. *
  11697. * @requires $parse
  11698. * @requires $sce
  11699. *
  11700. * @description
  11701. *
  11702. * Compiles a string with markup into an interpolation function. This service is used by the
  11703. * HTML {@link ng.$compile $compile} service for data binding. See
  11704. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  11705. * interpolation markup.
  11706. *
  11707. *
  11708. * ```js
  11709. * var $interpolate = ...; // injected
  11710. * var exp = $interpolate('Hello {{name | uppercase}}!');
  11711. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  11712. * ```
  11713. *
  11714. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  11715. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  11716. * evaluate to a value other than `undefined`.
  11717. *
  11718. * ```js
  11719. * var $interpolate = ...; // injected
  11720. * var context = {greeting: 'Hello', name: undefined };
  11721. *
  11722. * // default "forgiving" mode
  11723. * var exp = $interpolate('{{greeting}} {{name}}!');
  11724. * expect(exp(context)).toEqual('Hello !');
  11725. *
  11726. * // "allOrNothing" mode
  11727. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  11728. * expect(exp(context)).toBeUndefined();
  11729. * context.name = 'Angular';
  11730. * expect(exp(context)).toEqual('Hello Angular!');
  11731. * ```
  11732. *
  11733. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  11734. *
  11735. * #### Escaped Interpolation
  11736. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  11737. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  11738. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  11739. * or binding.
  11740. *
  11741. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  11742. * degree, while also enabling code examples to work without relying on the
  11743. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  11744. *
  11745. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  11746. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  11747. * interpolation start/end markers with their escaped counterparts.**
  11748. *
  11749. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  11750. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  11751. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  11752. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  11753. * this is typically useful only when user-data is used in rendering a template from the server, or
  11754. * when otherwise untrusted data is used by a directive.
  11755. *
  11756. * <example name="interpolation">
  11757. * <file name="index.html">
  11758. * <div ng-init="username='A user'">
  11759. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  11760. * </p>
  11761. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  11762. * application, but fails to accomplish their task, because the server has correctly
  11763. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  11764. * characters.</p>
  11765. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  11766. * from the database by an administrator.</p>
  11767. * </div>
  11768. * </file>
  11769. * </example>
  11770. *
  11771. * @knownIssue
  11772. * It is currently not possible for an interpolated expression to contain the interpolation end
  11773. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  11774. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  11775. *
  11776. * @knownIssue
  11777. * All directives and components must use the standard `{{` `}}` interpolation symbols
  11778. * in their templates. If you change the application interpolation symbols the {@link $compile}
  11779. * service will attempt to denormalize the standard symbols to the custom symbols.
  11780. * The denormalization process is not clever enough to know not to replace instances of the standard
  11781. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  11782. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  11783. *
  11784. * ```
  11785. * <div data-context='{"context":{"id":3,"type":"page"}}">
  11786. * ```
  11787. *
  11788. * The workaround is to ensure that such instances are separated by whitespace:
  11789. * ```
  11790. * <div data-context='{"context":{"id":3,"type":"page"} }">
  11791. * ```
  11792. *
  11793. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  11794. *
  11795. * @param {string} text The text with markup to interpolate.
  11796. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  11797. * embedded expression in order to return an interpolation function. Strings with no
  11798. * embedded expression will return null for the interpolation function.
  11799. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  11800. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  11801. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  11802. * provides Strict Contextual Escaping for details.
  11803. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  11804. * unless all embedded expressions evaluate to a value other than `undefined`.
  11805. * @returns {function(context)} an interpolation function which is used to compute the
  11806. * interpolated string. The function has these parameters:
  11807. *
  11808. * - `context`: evaluation context for all expressions embedded in the interpolated text
  11809. */
  11810. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  11811. // Provide a quick exit and simplified result function for text with no interpolation
  11812. if (!text.length || text.indexOf(startSymbol) === -1) {
  11813. var constantInterp;
  11814. if (!mustHaveExpression) {
  11815. var unescapedText = unescapeText(text);
  11816. constantInterp = valueFn(unescapedText);
  11817. constantInterp.exp = text;
  11818. constantInterp.expressions = [];
  11819. constantInterp.$$watchDelegate = constantWatchDelegate;
  11820. }
  11821. return constantInterp;
  11822. }
  11823. allOrNothing = !!allOrNothing;
  11824. var startIndex,
  11825. endIndex,
  11826. index = 0,
  11827. expressions = [],
  11828. parseFns = [],
  11829. textLength = text.length,
  11830. exp,
  11831. concat = [],
  11832. expressionPositions = [];
  11833. while (index < textLength) {
  11834. if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
  11835. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
  11836. if (index !== startIndex) {
  11837. concat.push(unescapeText(text.substring(index, startIndex)));
  11838. }
  11839. exp = text.substring(startIndex + startSymbolLength, endIndex);
  11840. expressions.push(exp);
  11841. parseFns.push($parse(exp, parseStringifyInterceptor));
  11842. index = endIndex + endSymbolLength;
  11843. expressionPositions.push(concat.length);
  11844. concat.push('');
  11845. } else {
  11846. // we did not find an interpolation, so we have to add the remainder to the separators array
  11847. if (index !== textLength) {
  11848. concat.push(unescapeText(text.substring(index)));
  11849. }
  11850. break;
  11851. }
  11852. }
  11853. // Concatenating expressions makes it hard to reason about whether some combination of
  11854. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  11855. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  11856. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  11857. // make it obvious that you bound the value to some user controlled value. This helps reduce
  11858. // the load when auditing for XSS issues.
  11859. if (trustedContext && concat.length > 1) {
  11860. $interpolateMinErr.throwNoconcat(text);
  11861. }
  11862. if (!mustHaveExpression || expressions.length) {
  11863. var compute = function(values) {
  11864. for (var i = 0, ii = expressions.length; i < ii; i++) {
  11865. if (allOrNothing && isUndefined(values[i])) return;
  11866. concat[expressionPositions[i]] = values[i];
  11867. }
  11868. return concat.join('');
  11869. };
  11870. var getValue = function(value) {
  11871. return trustedContext ?
  11872. $sce.getTrusted(trustedContext, value) :
  11873. $sce.valueOf(value);
  11874. };
  11875. return extend(function interpolationFn(context) {
  11876. var i = 0;
  11877. var ii = expressions.length;
  11878. var values = new Array(ii);
  11879. try {
  11880. for (; i < ii; i++) {
  11881. values[i] = parseFns[i](context);
  11882. }
  11883. return compute(values);
  11884. } catch (err) {
  11885. $exceptionHandler($interpolateMinErr.interr(text, err));
  11886. }
  11887. }, {
  11888. // all of these properties are undocumented for now
  11889. exp: text, //just for compatibility with regular watchers created via $watch
  11890. expressions: expressions,
  11891. $$watchDelegate: function(scope, listener) {
  11892. var lastValue;
  11893. return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
  11894. var currValue = compute(values);
  11895. if (isFunction(listener)) {
  11896. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  11897. }
  11898. lastValue = currValue;
  11899. });
  11900. }
  11901. });
  11902. }
  11903. function parseStringifyInterceptor(value) {
  11904. try {
  11905. value = getValue(value);
  11906. return allOrNothing && !isDefined(value) ? value : stringify(value);
  11907. } catch (err) {
  11908. $exceptionHandler($interpolateMinErr.interr(text, err));
  11909. }
  11910. }
  11911. }
  11912. /**
  11913. * @ngdoc method
  11914. * @name $interpolate#startSymbol
  11915. * @description
  11916. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  11917. *
  11918. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  11919. * the symbol.
  11920. *
  11921. * @returns {string} start symbol.
  11922. */
  11923. $interpolate.startSymbol = function() {
  11924. return startSymbol;
  11925. };
  11926. /**
  11927. * @ngdoc method
  11928. * @name $interpolate#endSymbol
  11929. * @description
  11930. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11931. *
  11932. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  11933. * the symbol.
  11934. *
  11935. * @returns {string} end symbol.
  11936. */
  11937. $interpolate.endSymbol = function() {
  11938. return endSymbol;
  11939. };
  11940. return $interpolate;
  11941. }];
  11942. }
  11943. /** @this */
  11944. function $IntervalProvider() {
  11945. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  11946. function($rootScope, $window, $q, $$q, $browser) {
  11947. var intervals = {};
  11948. /**
  11949. * @ngdoc service
  11950. * @name $interval
  11951. *
  11952. * @description
  11953. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  11954. * milliseconds.
  11955. *
  11956. * The return value of registering an interval function is a promise. This promise will be
  11957. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  11958. * run indefinitely if `count` is not defined. The value of the notification will be the
  11959. * number of iterations that have run.
  11960. * To cancel an interval, call `$interval.cancel(promise)`.
  11961. *
  11962. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  11963. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  11964. * time.
  11965. *
  11966. * <div class="alert alert-warning">
  11967. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  11968. * with them. In particular they are not automatically destroyed when a controller's scope or a
  11969. * directive's element are destroyed.
  11970. * You should take this into consideration and make sure to always cancel the interval at the
  11971. * appropriate moment. See the example below for more details on how and when to do this.
  11972. * </div>
  11973. *
  11974. * @param {function()} fn A function that should be called repeatedly. If no additional arguments
  11975. * are passed (see below), the function is called with the current iteration count.
  11976. * @param {number} delay Number of milliseconds between each function call.
  11977. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  11978. * indefinitely.
  11979. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  11980. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  11981. * @param {...*=} Pass additional parameters to the executed function.
  11982. * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete.
  11983. *
  11984. * @example
  11985. * <example module="intervalExample" name="interval-service">
  11986. * <file name="index.html">
  11987. * <script>
  11988. * angular.module('intervalExample', [])
  11989. * .controller('ExampleController', ['$scope', '$interval',
  11990. * function($scope, $interval) {
  11991. * $scope.format = 'M/d/yy h:mm:ss a';
  11992. * $scope.blood_1 = 100;
  11993. * $scope.blood_2 = 120;
  11994. *
  11995. * var stop;
  11996. * $scope.fight = function() {
  11997. * // Don't start a new fight if we are already fighting
  11998. * if ( angular.isDefined(stop) ) return;
  11999. *
  12000. * stop = $interval(function() {
  12001. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  12002. * $scope.blood_1 = $scope.blood_1 - 3;
  12003. * $scope.blood_2 = $scope.blood_2 - 4;
  12004. * } else {
  12005. * $scope.stopFight();
  12006. * }
  12007. * }, 100);
  12008. * };
  12009. *
  12010. * $scope.stopFight = function() {
  12011. * if (angular.isDefined(stop)) {
  12012. * $interval.cancel(stop);
  12013. * stop = undefined;
  12014. * }
  12015. * };
  12016. *
  12017. * $scope.resetFight = function() {
  12018. * $scope.blood_1 = 100;
  12019. * $scope.blood_2 = 120;
  12020. * };
  12021. *
  12022. * $scope.$on('$destroy', function() {
  12023. * // Make sure that the interval is destroyed too
  12024. * $scope.stopFight();
  12025. * });
  12026. * }])
  12027. * // Register the 'myCurrentTime' directive factory method.
  12028. * // We inject $interval and dateFilter service since the factory method is DI.
  12029. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  12030. * function($interval, dateFilter) {
  12031. * // return the directive link function. (compile function not needed)
  12032. * return function(scope, element, attrs) {
  12033. * var format, // date format
  12034. * stopTime; // so that we can cancel the time updates
  12035. *
  12036. * // used to update the UI
  12037. * function updateTime() {
  12038. * element.text(dateFilter(new Date(), format));
  12039. * }
  12040. *
  12041. * // watch the expression, and update the UI on change.
  12042. * scope.$watch(attrs.myCurrentTime, function(value) {
  12043. * format = value;
  12044. * updateTime();
  12045. * });
  12046. *
  12047. * stopTime = $interval(updateTime, 1000);
  12048. *
  12049. * // listen on DOM destroy (removal) event, and cancel the next UI update
  12050. * // to prevent updating time after the DOM element was removed.
  12051. * element.on('$destroy', function() {
  12052. * $interval.cancel(stopTime);
  12053. * });
  12054. * }
  12055. * }]);
  12056. * </script>
  12057. *
  12058. * <div>
  12059. * <div ng-controller="ExampleController">
  12060. * <label>Date format: <input ng-model="format"></label> <hr/>
  12061. * Current time is: <span my-current-time="format"></span>
  12062. * <hr/>
  12063. * Blood 1 : <font color='red'>{{blood_1}}</font>
  12064. * Blood 2 : <font color='red'>{{blood_2}}</font>
  12065. * <button type="button" data-ng-click="fight()">Fight</button>
  12066. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  12067. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  12068. * </div>
  12069. * </div>
  12070. *
  12071. * </file>
  12072. * </example>
  12073. */
  12074. function interval(fn, delay, count, invokeApply) {
  12075. var hasParams = arguments.length > 4,
  12076. args = hasParams ? sliceArgs(arguments, 4) : [],
  12077. setInterval = $window.setInterval,
  12078. clearInterval = $window.clearInterval,
  12079. iteration = 0,
  12080. skipApply = (isDefined(invokeApply) && !invokeApply),
  12081. deferred = (skipApply ? $$q : $q).defer(),
  12082. promise = deferred.promise;
  12083. count = isDefined(count) ? count : 0;
  12084. promise.$$intervalId = setInterval(function tick() {
  12085. if (skipApply) {
  12086. $browser.defer(callback);
  12087. } else {
  12088. $rootScope.$evalAsync(callback);
  12089. }
  12090. deferred.notify(iteration++);
  12091. if (count > 0 && iteration >= count) {
  12092. deferred.resolve(iteration);
  12093. clearInterval(promise.$$intervalId);
  12094. delete intervals[promise.$$intervalId];
  12095. }
  12096. if (!skipApply) $rootScope.$apply();
  12097. }, delay);
  12098. intervals[promise.$$intervalId] = deferred;
  12099. return promise;
  12100. function callback() {
  12101. if (!hasParams) {
  12102. fn(iteration);
  12103. } else {
  12104. fn.apply(null, args);
  12105. }
  12106. }
  12107. }
  12108. /**
  12109. * @ngdoc method
  12110. * @name $interval#cancel
  12111. *
  12112. * @description
  12113. * Cancels a task associated with the `promise`.
  12114. *
  12115. * @param {Promise=} promise returned by the `$interval` function.
  12116. * @returns {boolean} Returns `true` if the task was successfully canceled.
  12117. */
  12118. interval.cancel = function(promise) {
  12119. if (promise && promise.$$intervalId in intervals) {
  12120. // Interval cancels should not report as unhandled promise.
  12121. markQExceptionHandled(intervals[promise.$$intervalId].promise);
  12122. intervals[promise.$$intervalId].reject('canceled');
  12123. $window.clearInterval(promise.$$intervalId);
  12124. delete intervals[promise.$$intervalId];
  12125. return true;
  12126. }
  12127. return false;
  12128. };
  12129. return interval;
  12130. }];
  12131. }
  12132. /**
  12133. * @ngdoc service
  12134. * @name $jsonpCallbacks
  12135. * @requires $window
  12136. * @description
  12137. * This service handles the lifecycle of callbacks to handle JSONP requests.
  12138. * Override this service if you wish to customise where the callbacks are stored and
  12139. * how they vary compared to the requested url.
  12140. */
  12141. var $jsonpCallbacksProvider = /** @this */ function() {
  12142. this.$get = function() {
  12143. var callbacks = angular.callbacks;
  12144. var callbackMap = {};
  12145. function createCallback(callbackId) {
  12146. var callback = function(data) {
  12147. callback.data = data;
  12148. callback.called = true;
  12149. };
  12150. callback.id = callbackId;
  12151. return callback;
  12152. }
  12153. return {
  12154. /**
  12155. * @ngdoc method
  12156. * @name $jsonpCallbacks#createCallback
  12157. * @param {string} url the url of the JSONP request
  12158. * @returns {string} the callback path to send to the server as part of the JSONP request
  12159. * @description
  12160. * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
  12161. * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
  12162. */
  12163. createCallback: function(url) {
  12164. var callbackId = '_' + (callbacks.$$counter++).toString(36);
  12165. var callbackPath = 'angular.callbacks.' + callbackId;
  12166. var callback = createCallback(callbackId);
  12167. callbackMap[callbackPath] = callbacks[callbackId] = callback;
  12168. return callbackPath;
  12169. },
  12170. /**
  12171. * @ngdoc method
  12172. * @name $jsonpCallbacks#wasCalled
  12173. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12174. * @returns {boolean} whether the callback has been called, as a result of the JSONP response
  12175. * @description
  12176. * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
  12177. * callback that was passed in the request.
  12178. */
  12179. wasCalled: function(callbackPath) {
  12180. return callbackMap[callbackPath].called;
  12181. },
  12182. /**
  12183. * @ngdoc method
  12184. * @name $jsonpCallbacks#getResponse
  12185. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12186. * @returns {*} the data received from the response via the registered callback
  12187. * @description
  12188. * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
  12189. * in the JSONP response.
  12190. */
  12191. getResponse: function(callbackPath) {
  12192. return callbackMap[callbackPath].data;
  12193. },
  12194. /**
  12195. * @ngdoc method
  12196. * @name $jsonpCallbacks#removeCallback
  12197. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12198. * @description
  12199. * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
  12200. * completed or timed-out.
  12201. */
  12202. removeCallback: function(callbackPath) {
  12203. var callback = callbackMap[callbackPath];
  12204. delete callbacks[callback.id];
  12205. delete callbackMap[callbackPath];
  12206. }
  12207. };
  12208. };
  12209. };
  12210. /**
  12211. * @ngdoc service
  12212. * @name $locale
  12213. *
  12214. * @description
  12215. * $locale service provides localization rules for various Angular components. As of right now the
  12216. * only public api is:
  12217. *
  12218. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  12219. */
  12220. var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
  12221. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  12222. var $locationMinErr = minErr('$location');
  12223. /**
  12224. * Encode path using encodeUriSegment, ignoring forward slashes
  12225. *
  12226. * @param {string} path Path to encode
  12227. * @returns {string}
  12228. */
  12229. function encodePath(path) {
  12230. var segments = path.split('/'),
  12231. i = segments.length;
  12232. while (i--) {
  12233. segments[i] = encodeUriSegment(segments[i]);
  12234. }
  12235. return segments.join('/');
  12236. }
  12237. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  12238. var parsedUrl = urlResolve(absoluteUrl);
  12239. locationObj.$$protocol = parsedUrl.protocol;
  12240. locationObj.$$host = parsedUrl.hostname;
  12241. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  12242. }
  12243. var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
  12244. function parseAppUrl(url, locationObj) {
  12245. if (DOUBLE_SLASH_REGEX.test(url)) {
  12246. throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
  12247. }
  12248. var prefixed = (url.charAt(0) !== '/');
  12249. if (prefixed) {
  12250. url = '/' + url;
  12251. }
  12252. var match = urlResolve(url);
  12253. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  12254. match.pathname.substring(1) : match.pathname);
  12255. locationObj.$$search = parseKeyValue(match.search);
  12256. locationObj.$$hash = decodeURIComponent(match.hash);
  12257. // make sure path starts with '/';
  12258. if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
  12259. locationObj.$$path = '/' + locationObj.$$path;
  12260. }
  12261. }
  12262. function startsWith(str, search) {
  12263. return str.slice(0, search.length) === search;
  12264. }
  12265. /**
  12266. *
  12267. * @param {string} base
  12268. * @param {string} url
  12269. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  12270. * the expected string.
  12271. */
  12272. function stripBaseUrl(base, url) {
  12273. if (startsWith(url, base)) {
  12274. return url.substr(base.length);
  12275. }
  12276. }
  12277. function stripHash(url) {
  12278. var index = url.indexOf('#');
  12279. return index === -1 ? url : url.substr(0, index);
  12280. }
  12281. function trimEmptyHash(url) {
  12282. return url.replace(/(#.+)|#$/, '$1');
  12283. }
  12284. function stripFile(url) {
  12285. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  12286. }
  12287. /* return the server only (scheme://host:port) */
  12288. function serverBase(url) {
  12289. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  12290. }
  12291. /**
  12292. * LocationHtml5Url represents a URL
  12293. * This object is exposed as $location service when HTML5 mode is enabled and supported
  12294. *
  12295. * @constructor
  12296. * @param {string} appBase application base URL
  12297. * @param {string} appBaseNoFile application base URL stripped of any filename
  12298. * @param {string} basePrefix URL path prefix
  12299. */
  12300. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  12301. this.$$html5 = true;
  12302. basePrefix = basePrefix || '';
  12303. parseAbsoluteUrl(appBase, this);
  12304. /**
  12305. * Parse given HTML5 (regular) URL string into properties
  12306. * @param {string} url HTML5 URL
  12307. * @private
  12308. */
  12309. this.$$parse = function(url) {
  12310. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  12311. if (!isString(pathUrl)) {
  12312. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  12313. appBaseNoFile);
  12314. }
  12315. parseAppUrl(pathUrl, this);
  12316. if (!this.$$path) {
  12317. this.$$path = '/';
  12318. }
  12319. this.$$compose();
  12320. };
  12321. /**
  12322. * Compose url and update `absUrl` property
  12323. * @private
  12324. */
  12325. this.$$compose = function() {
  12326. var search = toKeyValue(this.$$search),
  12327. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12328. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12329. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  12330. this.$$urlUpdatedByLocation = true;
  12331. };
  12332. this.$$parseLinkUrl = function(url, relHref) {
  12333. if (relHref && relHref[0] === '#') {
  12334. // special case for links to hash fragments:
  12335. // keep the old url and only replace the hash fragment
  12336. this.hash(relHref.slice(1));
  12337. return true;
  12338. }
  12339. var appUrl, prevAppUrl;
  12340. var rewrittenUrl;
  12341. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  12342. prevAppUrl = appUrl;
  12343. if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  12344. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  12345. } else {
  12346. rewrittenUrl = appBase + prevAppUrl;
  12347. }
  12348. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12349. rewrittenUrl = appBaseNoFile + appUrl;
  12350. } else if (appBaseNoFile === url + '/') {
  12351. rewrittenUrl = appBaseNoFile;
  12352. }
  12353. if (rewrittenUrl) {
  12354. this.$$parse(rewrittenUrl);
  12355. }
  12356. return !!rewrittenUrl;
  12357. };
  12358. }
  12359. /**
  12360. * LocationHashbangUrl represents URL
  12361. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  12362. * It also serves as the base class for html5 mode fallback on legacy browsers.
  12363. *
  12364. * @constructor
  12365. * @param {string} appBase application base URL
  12366. * @param {string} appBaseNoFile application base URL stripped of any filename
  12367. * @param {string} hashPrefix hashbang prefix
  12368. */
  12369. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  12370. parseAbsoluteUrl(appBase, this);
  12371. /**
  12372. * Parse given hashbang URL into properties
  12373. * @param {string} url Hashbang URL
  12374. * @private
  12375. */
  12376. this.$$parse = function(url) {
  12377. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  12378. var withoutHashUrl;
  12379. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  12380. // The rest of the URL starts with a hash so we have
  12381. // got either a hashbang path or a plain hash fragment
  12382. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  12383. if (isUndefined(withoutHashUrl)) {
  12384. // There was no hashbang prefix so we just have a hash fragment
  12385. withoutHashUrl = withoutBaseUrl;
  12386. }
  12387. } else {
  12388. // There was no hashbang path nor hash fragment:
  12389. // If we are in HTML5 mode we use what is left as the path;
  12390. // Otherwise we ignore what is left
  12391. if (this.$$html5) {
  12392. withoutHashUrl = withoutBaseUrl;
  12393. } else {
  12394. withoutHashUrl = '';
  12395. if (isUndefined(withoutBaseUrl)) {
  12396. appBase = url;
  12397. /** @type {?} */ (this).replace();
  12398. }
  12399. }
  12400. }
  12401. parseAppUrl(withoutHashUrl, this);
  12402. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  12403. this.$$compose();
  12404. /*
  12405. * In Windows, on an anchor node on documents loaded from
  12406. * the filesystem, the browser will return a pathname
  12407. * prefixed with the drive name ('/C:/path') when a
  12408. * pathname without a drive is set:
  12409. * * a.setAttribute('href', '/foo')
  12410. * * a.pathname === '/C:/foo' //true
  12411. *
  12412. * Inside of Angular, we're always using pathnames that
  12413. * do not include drive names for routing.
  12414. */
  12415. function removeWindowsDriveName(path, url, base) {
  12416. /*
  12417. Matches paths for file protocol on windows,
  12418. such as /C:/foo/bar, and captures only /foo/bar.
  12419. */
  12420. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  12421. var firstPathSegmentMatch;
  12422. //Get the relative path from the input URL.
  12423. if (startsWith(url, base)) {
  12424. url = url.replace(base, '');
  12425. }
  12426. // The input URL intentionally contains a first path segment that ends with a colon.
  12427. if (windowsFilePathExp.exec(url)) {
  12428. return path;
  12429. }
  12430. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  12431. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  12432. }
  12433. };
  12434. /**
  12435. * Compose hashbang URL and update `absUrl` property
  12436. * @private
  12437. */
  12438. this.$$compose = function() {
  12439. var search = toKeyValue(this.$$search),
  12440. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12441. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12442. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  12443. this.$$urlUpdatedByLocation = true;
  12444. };
  12445. this.$$parseLinkUrl = function(url, relHref) {
  12446. if (stripHash(appBase) === stripHash(url)) {
  12447. this.$$parse(url);
  12448. return true;
  12449. }
  12450. return false;
  12451. };
  12452. }
  12453. /**
  12454. * LocationHashbangUrl represents URL
  12455. * This object is exposed as $location service when html5 history api is enabled but the browser
  12456. * does not support it.
  12457. *
  12458. * @constructor
  12459. * @param {string} appBase application base URL
  12460. * @param {string} appBaseNoFile application base URL stripped of any filename
  12461. * @param {string} hashPrefix hashbang prefix
  12462. */
  12463. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  12464. this.$$html5 = true;
  12465. LocationHashbangUrl.apply(this, arguments);
  12466. this.$$parseLinkUrl = function(url, relHref) {
  12467. if (relHref && relHref[0] === '#') {
  12468. // special case for links to hash fragments:
  12469. // keep the old url and only replace the hash fragment
  12470. this.hash(relHref.slice(1));
  12471. return true;
  12472. }
  12473. var rewrittenUrl;
  12474. var appUrl;
  12475. if (appBase === stripHash(url)) {
  12476. rewrittenUrl = url;
  12477. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12478. rewrittenUrl = appBase + hashPrefix + appUrl;
  12479. } else if (appBaseNoFile === url + '/') {
  12480. rewrittenUrl = appBaseNoFile;
  12481. }
  12482. if (rewrittenUrl) {
  12483. this.$$parse(rewrittenUrl);
  12484. }
  12485. return !!rewrittenUrl;
  12486. };
  12487. this.$$compose = function() {
  12488. var search = toKeyValue(this.$$search),
  12489. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12490. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12491. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  12492. this.$$absUrl = appBase + hashPrefix + this.$$url;
  12493. this.$$urlUpdatedByLocation = true;
  12494. };
  12495. }
  12496. var locationPrototype = {
  12497. /**
  12498. * Ensure absolute URL is initialized.
  12499. * @private
  12500. */
  12501. $$absUrl:'',
  12502. /**
  12503. * Are we in html5 mode?
  12504. * @private
  12505. */
  12506. $$html5: false,
  12507. /**
  12508. * Has any change been replacing?
  12509. * @private
  12510. */
  12511. $$replace: false,
  12512. /**
  12513. * @ngdoc method
  12514. * @name $location#absUrl
  12515. *
  12516. * @description
  12517. * This method is getter only.
  12518. *
  12519. * Return full URL representation with all segments encoded according to rules specified in
  12520. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  12521. *
  12522. *
  12523. * ```js
  12524. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12525. * var absUrl = $location.absUrl();
  12526. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  12527. * ```
  12528. *
  12529. * @return {string} full URL
  12530. */
  12531. absUrl: locationGetter('$$absUrl'),
  12532. /**
  12533. * @ngdoc method
  12534. * @name $location#url
  12535. *
  12536. * @description
  12537. * This method is getter / setter.
  12538. *
  12539. * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
  12540. *
  12541. * Change path, search and hash, when called with parameter and return `$location`.
  12542. *
  12543. *
  12544. * ```js
  12545. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12546. * var url = $location.url();
  12547. * // => "/some/path?foo=bar&baz=xoxo"
  12548. * ```
  12549. *
  12550. * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
  12551. * @return {string} url
  12552. */
  12553. url: function(url) {
  12554. if (isUndefined(url)) {
  12555. return this.$$url;
  12556. }
  12557. var match = PATH_MATCH.exec(url);
  12558. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  12559. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  12560. this.hash(match[5] || '');
  12561. return this;
  12562. },
  12563. /**
  12564. * @ngdoc method
  12565. * @name $location#protocol
  12566. *
  12567. * @description
  12568. * This method is getter only.
  12569. *
  12570. * Return protocol of current URL.
  12571. *
  12572. *
  12573. * ```js
  12574. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12575. * var protocol = $location.protocol();
  12576. * // => "http"
  12577. * ```
  12578. *
  12579. * @return {string} protocol of current URL
  12580. */
  12581. protocol: locationGetter('$$protocol'),
  12582. /**
  12583. * @ngdoc method
  12584. * @name $location#host
  12585. *
  12586. * @description
  12587. * This method is getter only.
  12588. *
  12589. * Return host of current URL.
  12590. *
  12591. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  12592. *
  12593. *
  12594. * ```js
  12595. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12596. * var host = $location.host();
  12597. * // => "example.com"
  12598. *
  12599. * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  12600. * host = $location.host();
  12601. * // => "example.com"
  12602. * host = location.host;
  12603. * // => "example.com:8080"
  12604. * ```
  12605. *
  12606. * @return {string} host of current URL.
  12607. */
  12608. host: locationGetter('$$host'),
  12609. /**
  12610. * @ngdoc method
  12611. * @name $location#port
  12612. *
  12613. * @description
  12614. * This method is getter only.
  12615. *
  12616. * Return port of current URL.
  12617. *
  12618. *
  12619. * ```js
  12620. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12621. * var port = $location.port();
  12622. * // => 80
  12623. * ```
  12624. *
  12625. * @return {Number} port
  12626. */
  12627. port: locationGetter('$$port'),
  12628. /**
  12629. * @ngdoc method
  12630. * @name $location#path
  12631. *
  12632. * @description
  12633. * This method is getter / setter.
  12634. *
  12635. * Return path of current URL when called without any parameter.
  12636. *
  12637. * Change path when called with parameter and return `$location`.
  12638. *
  12639. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  12640. * if it is missing.
  12641. *
  12642. *
  12643. * ```js
  12644. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12645. * var path = $location.path();
  12646. * // => "/some/path"
  12647. * ```
  12648. *
  12649. * @param {(string|number)=} path New path
  12650. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  12651. */
  12652. path: locationGetterSetter('$$path', function(path) {
  12653. path = path !== null ? path.toString() : '';
  12654. return path.charAt(0) === '/' ? path : '/' + path;
  12655. }),
  12656. /**
  12657. * @ngdoc method
  12658. * @name $location#search
  12659. *
  12660. * @description
  12661. * This method is getter / setter.
  12662. *
  12663. * Return search part (as object) of current URL when called without any parameter.
  12664. *
  12665. * Change search part when called with parameter and return `$location`.
  12666. *
  12667. *
  12668. * ```js
  12669. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12670. * var searchObject = $location.search();
  12671. * // => {foo: 'bar', baz: 'xoxo'}
  12672. *
  12673. * // set foo to 'yipee'
  12674. * $location.search('foo', 'yipee');
  12675. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  12676. * ```
  12677. *
  12678. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  12679. * hash object.
  12680. *
  12681. * When called with a single argument the method acts as a setter, setting the `search` component
  12682. * of `$location` to the specified value.
  12683. *
  12684. * If the argument is a hash object containing an array of values, these values will be encoded
  12685. * as duplicate search parameters in the URL.
  12686. *
  12687. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  12688. * will override only a single search property.
  12689. *
  12690. * If `paramValue` is an array, it will override the property of the `search` component of
  12691. * `$location` specified via the first argument.
  12692. *
  12693. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  12694. *
  12695. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  12696. * value nor trailing equal sign.
  12697. *
  12698. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  12699. * one or more arguments returns `$location` object itself.
  12700. */
  12701. search: function(search, paramValue) {
  12702. switch (arguments.length) {
  12703. case 0:
  12704. return this.$$search;
  12705. case 1:
  12706. if (isString(search) || isNumber(search)) {
  12707. search = search.toString();
  12708. this.$$search = parseKeyValue(search);
  12709. } else if (isObject(search)) {
  12710. search = copy(search, {});
  12711. // remove object undefined or null properties
  12712. forEach(search, function(value, key) {
  12713. if (value == null) delete search[key];
  12714. });
  12715. this.$$search = search;
  12716. } else {
  12717. throw $locationMinErr('isrcharg',
  12718. 'The first argument of the `$location#search()` call must be a string or an object.');
  12719. }
  12720. break;
  12721. default:
  12722. if (isUndefined(paramValue) || paramValue === null) {
  12723. delete this.$$search[search];
  12724. } else {
  12725. this.$$search[search] = paramValue;
  12726. }
  12727. }
  12728. this.$$compose();
  12729. return this;
  12730. },
  12731. /**
  12732. * @ngdoc method
  12733. * @name $location#hash
  12734. *
  12735. * @description
  12736. * This method is getter / setter.
  12737. *
  12738. * Returns the hash fragment when called without any parameters.
  12739. *
  12740. * Changes the hash fragment when called with a parameter and returns `$location`.
  12741. *
  12742. *
  12743. * ```js
  12744. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  12745. * var hash = $location.hash();
  12746. * // => "hashValue"
  12747. * ```
  12748. *
  12749. * @param {(string|number)=} hash New hash fragment
  12750. * @return {string} hash
  12751. */
  12752. hash: locationGetterSetter('$$hash', function(hash) {
  12753. return hash !== null ? hash.toString() : '';
  12754. }),
  12755. /**
  12756. * @ngdoc method
  12757. * @name $location#replace
  12758. *
  12759. * @description
  12760. * If called, all changes to $location during the current `$digest` will replace the current history
  12761. * record, instead of adding a new one.
  12762. */
  12763. replace: function() {
  12764. this.$$replace = true;
  12765. return this;
  12766. }
  12767. };
  12768. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  12769. Location.prototype = Object.create(locationPrototype);
  12770. /**
  12771. * @ngdoc method
  12772. * @name $location#state
  12773. *
  12774. * @description
  12775. * This method is getter / setter.
  12776. *
  12777. * Return the history state object when called without any parameter.
  12778. *
  12779. * Change the history state object when called with one parameter and return `$location`.
  12780. * The state object is later passed to `pushState` or `replaceState`.
  12781. *
  12782. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  12783. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  12784. * older browsers (like IE9 or Android < 4.0), don't use this method.
  12785. *
  12786. * @param {object=} state State object for pushState or replaceState
  12787. * @return {object} state
  12788. */
  12789. Location.prototype.state = function(state) {
  12790. if (!arguments.length) {
  12791. return this.$$state;
  12792. }
  12793. if (Location !== LocationHtml5Url || !this.$$html5) {
  12794. throw $locationMinErr('nostate', 'History API state support is available only ' +
  12795. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  12796. }
  12797. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  12798. // but we're changing the $$state reference to $browser.state() during the $digest
  12799. // so the modification window is narrow.
  12800. this.$$state = isUndefined(state) ? null : state;
  12801. this.$$urlUpdatedByLocation = true;
  12802. return this;
  12803. };
  12804. });
  12805. function locationGetter(property) {
  12806. return /** @this */ function() {
  12807. return this[property];
  12808. };
  12809. }
  12810. function locationGetterSetter(property, preprocess) {
  12811. return /** @this */ function(value) {
  12812. if (isUndefined(value)) {
  12813. return this[property];
  12814. }
  12815. this[property] = preprocess(value);
  12816. this.$$compose();
  12817. return this;
  12818. };
  12819. }
  12820. /**
  12821. * @ngdoc service
  12822. * @name $location
  12823. *
  12824. * @requires $rootElement
  12825. *
  12826. * @description
  12827. * The $location service parses the URL in the browser address bar (based on the
  12828. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  12829. * available to your application. Changes to the URL in the address bar are reflected into
  12830. * $location service and changes to $location are reflected into the browser address bar.
  12831. *
  12832. * **The $location service:**
  12833. *
  12834. * - Exposes the current URL in the browser address bar, so you can
  12835. * - Watch and observe the URL.
  12836. * - Change the URL.
  12837. * - Synchronizes the URL with the browser when the user
  12838. * - Changes the address bar.
  12839. * - Clicks the back or forward button (or clicks a History link).
  12840. * - Clicks on a link.
  12841. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  12842. *
  12843. * For more information see {@link guide/$location Developer Guide: Using $location}
  12844. */
  12845. /**
  12846. * @ngdoc provider
  12847. * @name $locationProvider
  12848. * @this
  12849. *
  12850. * @description
  12851. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  12852. */
  12853. function $LocationProvider() {
  12854. var hashPrefix = '!',
  12855. html5Mode = {
  12856. enabled: false,
  12857. requireBase: true,
  12858. rewriteLinks: true
  12859. };
  12860. /**
  12861. * @ngdoc method
  12862. * @name $locationProvider#hashPrefix
  12863. * @description
  12864. * The default value for the prefix is `'!'`.
  12865. * @param {string=} prefix Prefix for hash part (containing path and search)
  12866. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12867. */
  12868. this.hashPrefix = function(prefix) {
  12869. if (isDefined(prefix)) {
  12870. hashPrefix = prefix;
  12871. return this;
  12872. } else {
  12873. return hashPrefix;
  12874. }
  12875. };
  12876. /**
  12877. * @ngdoc method
  12878. * @name $locationProvider#html5Mode
  12879. * @description
  12880. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  12881. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  12882. * properties:
  12883. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  12884. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  12885. * support `pushState`.
  12886. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  12887. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  12888. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  12889. * See the {@link guide/$location $location guide for more information}
  12890. * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
  12891. * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
  12892. * only happen on links with an attribute that matches the given string. For example, if set
  12893. * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
  12894. * Note that [attribute name normalization](guide/directive#normalization) does not apply
  12895. * here, so `'internalLink'` will **not** match `'internal-link'`.
  12896. *
  12897. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  12898. */
  12899. this.html5Mode = function(mode) {
  12900. if (isBoolean(mode)) {
  12901. html5Mode.enabled = mode;
  12902. return this;
  12903. } else if (isObject(mode)) {
  12904. if (isBoolean(mode.enabled)) {
  12905. html5Mode.enabled = mode.enabled;
  12906. }
  12907. if (isBoolean(mode.requireBase)) {
  12908. html5Mode.requireBase = mode.requireBase;
  12909. }
  12910. if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
  12911. html5Mode.rewriteLinks = mode.rewriteLinks;
  12912. }
  12913. return this;
  12914. } else {
  12915. return html5Mode;
  12916. }
  12917. };
  12918. /**
  12919. * @ngdoc event
  12920. * @name $location#$locationChangeStart
  12921. * @eventType broadcast on root scope
  12922. * @description
  12923. * Broadcasted before a URL will change.
  12924. *
  12925. * This change can be prevented by calling
  12926. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  12927. * details about event object. Upon successful change
  12928. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  12929. *
  12930. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12931. * the browser supports the HTML5 History API.
  12932. *
  12933. * @param {Object} angularEvent Synthetic event object.
  12934. * @param {string} newUrl New URL
  12935. * @param {string=} oldUrl URL that was before it was changed.
  12936. * @param {string=} newState New history state object
  12937. * @param {string=} oldState History state object that was before it was changed.
  12938. */
  12939. /**
  12940. * @ngdoc event
  12941. * @name $location#$locationChangeSuccess
  12942. * @eventType broadcast on root scope
  12943. * @description
  12944. * Broadcasted after a URL was changed.
  12945. *
  12946. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12947. * the browser supports the HTML5 History API.
  12948. *
  12949. * @param {Object} angularEvent Synthetic event object.
  12950. * @param {string} newUrl New URL
  12951. * @param {string=} oldUrl URL that was before it was changed.
  12952. * @param {string=} newState New history state object
  12953. * @param {string=} oldState History state object that was before it was changed.
  12954. */
  12955. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  12956. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  12957. var $location,
  12958. LocationMode,
  12959. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  12960. initialUrl = $browser.url(),
  12961. appBase;
  12962. if (html5Mode.enabled) {
  12963. if (!baseHref && html5Mode.requireBase) {
  12964. throw $locationMinErr('nobase',
  12965. '$location in HTML5 mode requires a <base> tag to be present!');
  12966. }
  12967. appBase = serverBase(initialUrl) + (baseHref || '/');
  12968. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  12969. } else {
  12970. appBase = stripHash(initialUrl);
  12971. LocationMode = LocationHashbangUrl;
  12972. }
  12973. var appBaseNoFile = stripFile(appBase);
  12974. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  12975. $location.$$parseLinkUrl(initialUrl, initialUrl);
  12976. $location.$$state = $browser.state();
  12977. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  12978. function setBrowserUrlWithFallback(url, replace, state) {
  12979. var oldUrl = $location.url();
  12980. var oldState = $location.$$state;
  12981. try {
  12982. $browser.url(url, replace, state);
  12983. // Make sure $location.state() returns referentially identical (not just deeply equal)
  12984. // state object; this makes possible quick checking if the state changed in the digest
  12985. // loop. Checking deep equality would be too expensive.
  12986. $location.$$state = $browser.state();
  12987. } catch (e) {
  12988. // Restore old values if pushState fails
  12989. $location.url(oldUrl);
  12990. $location.$$state = oldState;
  12991. throw e;
  12992. }
  12993. }
  12994. $rootElement.on('click', function(event) {
  12995. var rewriteLinks = html5Mode.rewriteLinks;
  12996. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  12997. // currently we open nice url link and redirect then
  12998. if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
  12999. var elm = jqLite(event.target);
  13000. // traverse the DOM up to find first A tag
  13001. while (nodeName_(elm[0]) !== 'a') {
  13002. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  13003. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  13004. }
  13005. if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
  13006. var absHref = elm.prop('href');
  13007. // get the actual href attribute - see
  13008. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  13009. var relHref = elm.attr('href') || elm.attr('xlink:href');
  13010. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  13011. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  13012. // an animation.
  13013. absHref = urlResolve(absHref.animVal).href;
  13014. }
  13015. // Ignore when url is started with javascript: or mailto:
  13016. if (IGNORE_URI_REGEXP.test(absHref)) return;
  13017. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  13018. if ($location.$$parseLinkUrl(absHref, relHref)) {
  13019. // We do a preventDefault for all urls that are part of the angular application,
  13020. // in html5mode and also without, so that we are able to abort navigation without
  13021. // getting double entries in the location history.
  13022. event.preventDefault();
  13023. // update location manually
  13024. if ($location.absUrl() !== $browser.url()) {
  13025. $rootScope.$apply();
  13026. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  13027. $window.angular['ff-684208-preventDefault'] = true;
  13028. }
  13029. }
  13030. }
  13031. });
  13032. // rewrite hashbang url <> html5 url
  13033. if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {
  13034. $browser.url($location.absUrl(), true);
  13035. }
  13036. var initializing = true;
  13037. // update $location when $browser url changes
  13038. $browser.onUrlChange(function(newUrl, newState) {
  13039. if (!startsWith(newUrl, appBaseNoFile)) {
  13040. // If we are navigating outside of the app then force a reload
  13041. $window.location.href = newUrl;
  13042. return;
  13043. }
  13044. $rootScope.$evalAsync(function() {
  13045. var oldUrl = $location.absUrl();
  13046. var oldState = $location.$$state;
  13047. var defaultPrevented;
  13048. newUrl = trimEmptyHash(newUrl);
  13049. $location.$$parse(newUrl);
  13050. $location.$$state = newState;
  13051. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  13052. newState, oldState).defaultPrevented;
  13053. // if the location was changed by a `$locationChangeStart` handler then stop
  13054. // processing this location change
  13055. if ($location.absUrl() !== newUrl) return;
  13056. if (defaultPrevented) {
  13057. $location.$$parse(oldUrl);
  13058. $location.$$state = oldState;
  13059. setBrowserUrlWithFallback(oldUrl, false, oldState);
  13060. } else {
  13061. initializing = false;
  13062. afterLocationChange(oldUrl, oldState);
  13063. }
  13064. });
  13065. if (!$rootScope.$$phase) $rootScope.$digest();
  13066. });
  13067. // update browser
  13068. $rootScope.$watch(function $locationWatch() {
  13069. if (initializing || $location.$$urlUpdatedByLocation) {
  13070. $location.$$urlUpdatedByLocation = false;
  13071. var oldUrl = trimEmptyHash($browser.url());
  13072. var newUrl = trimEmptyHash($location.absUrl());
  13073. var oldState = $browser.state();
  13074. var currentReplace = $location.$$replace;
  13075. var urlOrStateChanged = oldUrl !== newUrl ||
  13076. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  13077. if (initializing || urlOrStateChanged) {
  13078. initializing = false;
  13079. $rootScope.$evalAsync(function() {
  13080. var newUrl = $location.absUrl();
  13081. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  13082. $location.$$state, oldState).defaultPrevented;
  13083. // if the location was changed by a `$locationChangeStart` handler then stop
  13084. // processing this location change
  13085. if ($location.absUrl() !== newUrl) return;
  13086. if (defaultPrevented) {
  13087. $location.$$parse(oldUrl);
  13088. $location.$$state = oldState;
  13089. } else {
  13090. if (urlOrStateChanged) {
  13091. setBrowserUrlWithFallback(newUrl, currentReplace,
  13092. oldState === $location.$$state ? null : $location.$$state);
  13093. }
  13094. afterLocationChange(oldUrl, oldState);
  13095. }
  13096. });
  13097. }
  13098. }
  13099. $location.$$replace = false;
  13100. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  13101. // there is a change
  13102. });
  13103. return $location;
  13104. function afterLocationChange(oldUrl, oldState) {
  13105. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  13106. $location.$$state, oldState);
  13107. }
  13108. }];
  13109. }
  13110. /**
  13111. * @ngdoc service
  13112. * @name $log
  13113. * @requires $window
  13114. *
  13115. * @description
  13116. * Simple service for logging. Default implementation safely writes the message
  13117. * into the browser's console (if present).
  13118. *
  13119. * The main purpose of this service is to simplify debugging and troubleshooting.
  13120. *
  13121. * To reveal the location of the calls to `$log` in the JavaScript console,
  13122. * you can "blackbox" the AngularJS source in your browser:
  13123. *
  13124. * [Mozilla description of blackboxing](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Black_box_a_source).
  13125. * [Chrome description of blackboxing](https://developer.chrome.com/devtools/docs/blackboxing).
  13126. *
  13127. * Note: Not all browsers support blackboxing.
  13128. *
  13129. * The default is to log `debug` messages. You can use
  13130. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  13131. *
  13132. * @example
  13133. <example module="logExample" name="log-service">
  13134. <file name="script.js">
  13135. angular.module('logExample', [])
  13136. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  13137. $scope.$log = $log;
  13138. $scope.message = 'Hello World!';
  13139. }]);
  13140. </file>
  13141. <file name="index.html">
  13142. <div ng-controller="LogController">
  13143. <p>Reload this page with open console, enter text and hit the log button...</p>
  13144. <label>Message:
  13145. <input type="text" ng-model="message" /></label>
  13146. <button ng-click="$log.log(message)">log</button>
  13147. <button ng-click="$log.warn(message)">warn</button>
  13148. <button ng-click="$log.info(message)">info</button>
  13149. <button ng-click="$log.error(message)">error</button>
  13150. <button ng-click="$log.debug(message)">debug</button>
  13151. </div>
  13152. </file>
  13153. </example>
  13154. */
  13155. /**
  13156. * @ngdoc provider
  13157. * @name $logProvider
  13158. * @this
  13159. *
  13160. * @description
  13161. * Use the `$logProvider` to configure how the application logs messages
  13162. */
  13163. function $LogProvider() {
  13164. var debug = true,
  13165. self = this;
  13166. /**
  13167. * @ngdoc method
  13168. * @name $logProvider#debugEnabled
  13169. * @description
  13170. * @param {boolean=} flag enable or disable debug level messages
  13171. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  13172. */
  13173. this.debugEnabled = function(flag) {
  13174. if (isDefined(flag)) {
  13175. debug = flag;
  13176. return this;
  13177. } else {
  13178. return debug;
  13179. }
  13180. };
  13181. this.$get = ['$window', function($window) {
  13182. // Support: IE 9-11, Edge 12-14+
  13183. // IE/Edge display errors in such a way that it requires the user to click in 4 places
  13184. // to see the stack trace. There is no way to feature-detect it so there's a chance
  13185. // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't
  13186. // break apps. Other browsers display errors in a sensible way and some of them map stack
  13187. // traces along source maps if available so it makes sense to let browsers display it
  13188. // as they want.
  13189. var formatStackTrace = msie || /\bEdge\//.test($window.navigator && $window.navigator.userAgent);
  13190. return {
  13191. /**
  13192. * @ngdoc method
  13193. * @name $log#log
  13194. *
  13195. * @description
  13196. * Write a log message
  13197. */
  13198. log: consoleLog('log'),
  13199. /**
  13200. * @ngdoc method
  13201. * @name $log#info
  13202. *
  13203. * @description
  13204. * Write an information message
  13205. */
  13206. info: consoleLog('info'),
  13207. /**
  13208. * @ngdoc method
  13209. * @name $log#warn
  13210. *
  13211. * @description
  13212. * Write a warning message
  13213. */
  13214. warn: consoleLog('warn'),
  13215. /**
  13216. * @ngdoc method
  13217. * @name $log#error
  13218. *
  13219. * @description
  13220. * Write an error message
  13221. */
  13222. error: consoleLog('error'),
  13223. /**
  13224. * @ngdoc method
  13225. * @name $log#debug
  13226. *
  13227. * @description
  13228. * Write a debug message
  13229. */
  13230. debug: (function() {
  13231. var fn = consoleLog('debug');
  13232. return function() {
  13233. if (debug) {
  13234. fn.apply(self, arguments);
  13235. }
  13236. };
  13237. })()
  13238. };
  13239. function formatError(arg) {
  13240. if (isError(arg)) {
  13241. if (arg.stack && formatStackTrace) {
  13242. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  13243. ? 'Error: ' + arg.message + '\n' + arg.stack
  13244. : arg.stack;
  13245. } else if (arg.sourceURL) {
  13246. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  13247. }
  13248. }
  13249. return arg;
  13250. }
  13251. function consoleLog(type) {
  13252. var console = $window.console || {},
  13253. logFn = console[type] || console.log || noop;
  13254. return function() {
  13255. var args = [];
  13256. forEach(arguments, function(arg) {
  13257. args.push(formatError(arg));
  13258. });
  13259. // Support: IE 9 only
  13260. // console methods don't inherit from Function.prototype in IE 9 so we can't
  13261. // call `logFn.apply(console, args)` directly.
  13262. return Function.prototype.apply.call(logFn, console, args);
  13263. };
  13264. }
  13265. }];
  13266. }
  13267. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  13268. * Any commits to this file should be reviewed with security in mind. *
  13269. * Changes to this file can potentially create security vulnerabilities. *
  13270. * An approval from 2 Core members with history of modifying *
  13271. * this file is required. *
  13272. * *
  13273. * Does the change somehow allow for arbitrary javascript to be executed? *
  13274. * Or allows for someone to change the prototype of built-in objects? *
  13275. * Or gives undesired access to variables likes document or window? *
  13276. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  13277. var $parseMinErr = minErr('$parse');
  13278. var objectValueOf = {}.constructor.prototype.valueOf;
  13279. // Sandboxing Angular Expressions
  13280. // ------------------------------
  13281. // Angular expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by
  13282. // various means such as obtaining a reference to native JS functions like the Function constructor.
  13283. //
  13284. // As an example, consider the following Angular expression:
  13285. //
  13286. // {}.toString.constructor('alert("evil JS code")')
  13287. //
  13288. // It is important to realize that if you create an expression from a string that contains user provided
  13289. // content then it is possible that your application contains a security vulnerability to an XSS style attack.
  13290. //
  13291. // See https://docs.angularjs.org/guide/security
  13292. function getStringValue(name) {
  13293. // Property names must be strings. This means that non-string objects cannot be used
  13294. // as keys in an object. Any non-string object, including a number, is typecasted
  13295. // into a string via the toString method.
  13296. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  13297. //
  13298. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  13299. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  13300. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  13301. //
  13302. // TypeError: Cannot convert object to primitive value
  13303. //
  13304. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  13305. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  13306. // such a 'broken' object as a key.
  13307. return name + '';
  13308. }
  13309. var OPERATORS = createMap();
  13310. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  13311. var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
  13312. /////////////////////////////////////////
  13313. /**
  13314. * @constructor
  13315. */
  13316. var Lexer = function Lexer(options) {
  13317. this.options = options;
  13318. };
  13319. Lexer.prototype = {
  13320. constructor: Lexer,
  13321. lex: function(text) {
  13322. this.text = text;
  13323. this.index = 0;
  13324. this.tokens = [];
  13325. while (this.index < this.text.length) {
  13326. var ch = this.text.charAt(this.index);
  13327. if (ch === '"' || ch === '\'') {
  13328. this.readString(ch);
  13329. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  13330. this.readNumber();
  13331. } else if (this.isIdentifierStart(this.peekMultichar())) {
  13332. this.readIdent();
  13333. } else if (this.is(ch, '(){}[].,;:?')) {
  13334. this.tokens.push({index: this.index, text: ch});
  13335. this.index++;
  13336. } else if (this.isWhitespace(ch)) {
  13337. this.index++;
  13338. } else {
  13339. var ch2 = ch + this.peek();
  13340. var ch3 = ch2 + this.peek(2);
  13341. var op1 = OPERATORS[ch];
  13342. var op2 = OPERATORS[ch2];
  13343. var op3 = OPERATORS[ch3];
  13344. if (op1 || op2 || op3) {
  13345. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  13346. this.tokens.push({index: this.index, text: token, operator: true});
  13347. this.index += token.length;
  13348. } else {
  13349. this.throwError('Unexpected next character ', this.index, this.index + 1);
  13350. }
  13351. }
  13352. }
  13353. return this.tokens;
  13354. },
  13355. is: function(ch, chars) {
  13356. return chars.indexOf(ch) !== -1;
  13357. },
  13358. peek: function(i) {
  13359. var num = i || 1;
  13360. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  13361. },
  13362. isNumber: function(ch) {
  13363. return ('0' <= ch && ch <= '9') && typeof ch === 'string';
  13364. },
  13365. isWhitespace: function(ch) {
  13366. // IE treats non-breaking space as \u00A0
  13367. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  13368. ch === '\n' || ch === '\v' || ch === '\u00A0');
  13369. },
  13370. isIdentifierStart: function(ch) {
  13371. return this.options.isIdentifierStart ?
  13372. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  13373. this.isValidIdentifierStart(ch);
  13374. },
  13375. isValidIdentifierStart: function(ch) {
  13376. return ('a' <= ch && ch <= 'z' ||
  13377. 'A' <= ch && ch <= 'Z' ||
  13378. '_' === ch || ch === '$');
  13379. },
  13380. isIdentifierContinue: function(ch) {
  13381. return this.options.isIdentifierContinue ?
  13382. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  13383. this.isValidIdentifierContinue(ch);
  13384. },
  13385. isValidIdentifierContinue: function(ch, cp) {
  13386. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  13387. },
  13388. codePointAt: function(ch) {
  13389. if (ch.length === 1) return ch.charCodeAt(0);
  13390. // eslint-disable-next-line no-bitwise
  13391. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  13392. },
  13393. peekMultichar: function() {
  13394. var ch = this.text.charAt(this.index);
  13395. var peek = this.peek();
  13396. if (!peek) {
  13397. return ch;
  13398. }
  13399. var cp1 = ch.charCodeAt(0);
  13400. var cp2 = peek.charCodeAt(0);
  13401. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  13402. return ch + peek;
  13403. }
  13404. return ch;
  13405. },
  13406. isExpOperator: function(ch) {
  13407. return (ch === '-' || ch === '+' || this.isNumber(ch));
  13408. },
  13409. throwError: function(error, start, end) {
  13410. end = end || this.index;
  13411. var colStr = (isDefined(start)
  13412. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  13413. : ' ' + end);
  13414. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  13415. error, colStr, this.text);
  13416. },
  13417. readNumber: function() {
  13418. var number = '';
  13419. var start = this.index;
  13420. while (this.index < this.text.length) {
  13421. var ch = lowercase(this.text.charAt(this.index));
  13422. if (ch === '.' || this.isNumber(ch)) {
  13423. number += ch;
  13424. } else {
  13425. var peekCh = this.peek();
  13426. if (ch === 'e' && this.isExpOperator(peekCh)) {
  13427. number += ch;
  13428. } else if (this.isExpOperator(ch) &&
  13429. peekCh && this.isNumber(peekCh) &&
  13430. number.charAt(number.length - 1) === 'e') {
  13431. number += ch;
  13432. } else if (this.isExpOperator(ch) &&
  13433. (!peekCh || !this.isNumber(peekCh)) &&
  13434. number.charAt(number.length - 1) === 'e') {
  13435. this.throwError('Invalid exponent');
  13436. } else {
  13437. break;
  13438. }
  13439. }
  13440. this.index++;
  13441. }
  13442. this.tokens.push({
  13443. index: start,
  13444. text: number,
  13445. constant: true,
  13446. value: Number(number)
  13447. });
  13448. },
  13449. readIdent: function() {
  13450. var start = this.index;
  13451. this.index += this.peekMultichar().length;
  13452. while (this.index < this.text.length) {
  13453. var ch = this.peekMultichar();
  13454. if (!this.isIdentifierContinue(ch)) {
  13455. break;
  13456. }
  13457. this.index += ch.length;
  13458. }
  13459. this.tokens.push({
  13460. index: start,
  13461. text: this.text.slice(start, this.index),
  13462. identifier: true
  13463. });
  13464. },
  13465. readString: function(quote) {
  13466. var start = this.index;
  13467. this.index++;
  13468. var string = '';
  13469. var rawString = quote;
  13470. var escape = false;
  13471. while (this.index < this.text.length) {
  13472. var ch = this.text.charAt(this.index);
  13473. rawString += ch;
  13474. if (escape) {
  13475. if (ch === 'u') {
  13476. var hex = this.text.substring(this.index + 1, this.index + 5);
  13477. if (!hex.match(/[\da-f]{4}/i)) {
  13478. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  13479. }
  13480. this.index += 4;
  13481. string += String.fromCharCode(parseInt(hex, 16));
  13482. } else {
  13483. var rep = ESCAPE[ch];
  13484. string = string + (rep || ch);
  13485. }
  13486. escape = false;
  13487. } else if (ch === '\\') {
  13488. escape = true;
  13489. } else if (ch === quote) {
  13490. this.index++;
  13491. this.tokens.push({
  13492. index: start,
  13493. text: rawString,
  13494. constant: true,
  13495. value: string
  13496. });
  13497. return;
  13498. } else {
  13499. string += ch;
  13500. }
  13501. this.index++;
  13502. }
  13503. this.throwError('Unterminated quote', start);
  13504. }
  13505. };
  13506. var AST = function AST(lexer, options) {
  13507. this.lexer = lexer;
  13508. this.options = options;
  13509. };
  13510. AST.Program = 'Program';
  13511. AST.ExpressionStatement = 'ExpressionStatement';
  13512. AST.AssignmentExpression = 'AssignmentExpression';
  13513. AST.ConditionalExpression = 'ConditionalExpression';
  13514. AST.LogicalExpression = 'LogicalExpression';
  13515. AST.BinaryExpression = 'BinaryExpression';
  13516. AST.UnaryExpression = 'UnaryExpression';
  13517. AST.CallExpression = 'CallExpression';
  13518. AST.MemberExpression = 'MemberExpression';
  13519. AST.Identifier = 'Identifier';
  13520. AST.Literal = 'Literal';
  13521. AST.ArrayExpression = 'ArrayExpression';
  13522. AST.Property = 'Property';
  13523. AST.ObjectExpression = 'ObjectExpression';
  13524. AST.ThisExpression = 'ThisExpression';
  13525. AST.LocalsExpression = 'LocalsExpression';
  13526. // Internal use only
  13527. AST.NGValueParameter = 'NGValueParameter';
  13528. AST.prototype = {
  13529. ast: function(text) {
  13530. this.text = text;
  13531. this.tokens = this.lexer.lex(text);
  13532. var value = this.program();
  13533. if (this.tokens.length !== 0) {
  13534. this.throwError('is an unexpected token', this.tokens[0]);
  13535. }
  13536. return value;
  13537. },
  13538. program: function() {
  13539. var body = [];
  13540. while (true) {
  13541. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  13542. body.push(this.expressionStatement());
  13543. if (!this.expect(';')) {
  13544. return { type: AST.Program, body: body};
  13545. }
  13546. }
  13547. },
  13548. expressionStatement: function() {
  13549. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  13550. },
  13551. filterChain: function() {
  13552. var left = this.expression();
  13553. while (this.expect('|')) {
  13554. left = this.filter(left);
  13555. }
  13556. return left;
  13557. },
  13558. expression: function() {
  13559. return this.assignment();
  13560. },
  13561. assignment: function() {
  13562. var result = this.ternary();
  13563. if (this.expect('=')) {
  13564. if (!isAssignable(result)) {
  13565. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  13566. }
  13567. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  13568. }
  13569. return result;
  13570. },
  13571. ternary: function() {
  13572. var test = this.logicalOR();
  13573. var alternate;
  13574. var consequent;
  13575. if (this.expect('?')) {
  13576. alternate = this.expression();
  13577. if (this.consume(':')) {
  13578. consequent = this.expression();
  13579. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  13580. }
  13581. }
  13582. return test;
  13583. },
  13584. logicalOR: function() {
  13585. var left = this.logicalAND();
  13586. while (this.expect('||')) {
  13587. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  13588. }
  13589. return left;
  13590. },
  13591. logicalAND: function() {
  13592. var left = this.equality();
  13593. while (this.expect('&&')) {
  13594. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  13595. }
  13596. return left;
  13597. },
  13598. equality: function() {
  13599. var left = this.relational();
  13600. var token;
  13601. while ((token = this.expect('==','!=','===','!=='))) {
  13602. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  13603. }
  13604. return left;
  13605. },
  13606. relational: function() {
  13607. var left = this.additive();
  13608. var token;
  13609. while ((token = this.expect('<', '>', '<=', '>='))) {
  13610. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  13611. }
  13612. return left;
  13613. },
  13614. additive: function() {
  13615. var left = this.multiplicative();
  13616. var token;
  13617. while ((token = this.expect('+','-'))) {
  13618. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  13619. }
  13620. return left;
  13621. },
  13622. multiplicative: function() {
  13623. var left = this.unary();
  13624. var token;
  13625. while ((token = this.expect('*','/','%'))) {
  13626. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  13627. }
  13628. return left;
  13629. },
  13630. unary: function() {
  13631. var token;
  13632. if ((token = this.expect('+', '-', '!'))) {
  13633. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  13634. } else {
  13635. return this.primary();
  13636. }
  13637. },
  13638. primary: function() {
  13639. var primary;
  13640. if (this.expect('(')) {
  13641. primary = this.filterChain();
  13642. this.consume(')');
  13643. } else if (this.expect('[')) {
  13644. primary = this.arrayDeclaration();
  13645. } else if (this.expect('{')) {
  13646. primary = this.object();
  13647. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  13648. primary = copy(this.selfReferential[this.consume().text]);
  13649. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  13650. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  13651. } else if (this.peek().identifier) {
  13652. primary = this.identifier();
  13653. } else if (this.peek().constant) {
  13654. primary = this.constant();
  13655. } else {
  13656. this.throwError('not a primary expression', this.peek());
  13657. }
  13658. var next;
  13659. while ((next = this.expect('(', '[', '.'))) {
  13660. if (next.text === '(') {
  13661. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  13662. this.consume(')');
  13663. } else if (next.text === '[') {
  13664. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  13665. this.consume(']');
  13666. } else if (next.text === '.') {
  13667. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  13668. } else {
  13669. this.throwError('IMPOSSIBLE');
  13670. }
  13671. }
  13672. return primary;
  13673. },
  13674. filter: function(baseExpression) {
  13675. var args = [baseExpression];
  13676. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  13677. while (this.expect(':')) {
  13678. args.push(this.expression());
  13679. }
  13680. return result;
  13681. },
  13682. parseArguments: function() {
  13683. var args = [];
  13684. if (this.peekToken().text !== ')') {
  13685. do {
  13686. args.push(this.filterChain());
  13687. } while (this.expect(','));
  13688. }
  13689. return args;
  13690. },
  13691. identifier: function() {
  13692. var token = this.consume();
  13693. if (!token.identifier) {
  13694. this.throwError('is not a valid identifier', token);
  13695. }
  13696. return { type: AST.Identifier, name: token.text };
  13697. },
  13698. constant: function() {
  13699. // TODO check that it is a constant
  13700. return { type: AST.Literal, value: this.consume().value };
  13701. },
  13702. arrayDeclaration: function() {
  13703. var elements = [];
  13704. if (this.peekToken().text !== ']') {
  13705. do {
  13706. if (this.peek(']')) {
  13707. // Support trailing commas per ES5.1.
  13708. break;
  13709. }
  13710. elements.push(this.expression());
  13711. } while (this.expect(','));
  13712. }
  13713. this.consume(']');
  13714. return { type: AST.ArrayExpression, elements: elements };
  13715. },
  13716. object: function() {
  13717. var properties = [], property;
  13718. if (this.peekToken().text !== '}') {
  13719. do {
  13720. if (this.peek('}')) {
  13721. // Support trailing commas per ES5.1.
  13722. break;
  13723. }
  13724. property = {type: AST.Property, kind: 'init'};
  13725. if (this.peek().constant) {
  13726. property.key = this.constant();
  13727. property.computed = false;
  13728. this.consume(':');
  13729. property.value = this.expression();
  13730. } else if (this.peek().identifier) {
  13731. property.key = this.identifier();
  13732. property.computed = false;
  13733. if (this.peek(':')) {
  13734. this.consume(':');
  13735. property.value = this.expression();
  13736. } else {
  13737. property.value = property.key;
  13738. }
  13739. } else if (this.peek('[')) {
  13740. this.consume('[');
  13741. property.key = this.expression();
  13742. this.consume(']');
  13743. property.computed = true;
  13744. this.consume(':');
  13745. property.value = this.expression();
  13746. } else {
  13747. this.throwError('invalid key', this.peek());
  13748. }
  13749. properties.push(property);
  13750. } while (this.expect(','));
  13751. }
  13752. this.consume('}');
  13753. return {type: AST.ObjectExpression, properties: properties };
  13754. },
  13755. throwError: function(msg, token) {
  13756. throw $parseMinErr('syntax',
  13757. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  13758. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  13759. },
  13760. consume: function(e1) {
  13761. if (this.tokens.length === 0) {
  13762. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13763. }
  13764. var token = this.expect(e1);
  13765. if (!token) {
  13766. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  13767. }
  13768. return token;
  13769. },
  13770. peekToken: function() {
  13771. if (this.tokens.length === 0) {
  13772. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13773. }
  13774. return this.tokens[0];
  13775. },
  13776. peek: function(e1, e2, e3, e4) {
  13777. return this.peekAhead(0, e1, e2, e3, e4);
  13778. },
  13779. peekAhead: function(i, e1, e2, e3, e4) {
  13780. if (this.tokens.length > i) {
  13781. var token = this.tokens[i];
  13782. var t = token.text;
  13783. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  13784. (!e1 && !e2 && !e3 && !e4)) {
  13785. return token;
  13786. }
  13787. }
  13788. return false;
  13789. },
  13790. expect: function(e1, e2, e3, e4) {
  13791. var token = this.peek(e1, e2, e3, e4);
  13792. if (token) {
  13793. this.tokens.shift();
  13794. return token;
  13795. }
  13796. return false;
  13797. },
  13798. selfReferential: {
  13799. 'this': {type: AST.ThisExpression },
  13800. '$locals': {type: AST.LocalsExpression }
  13801. }
  13802. };
  13803. function ifDefined(v, d) {
  13804. return typeof v !== 'undefined' ? v : d;
  13805. }
  13806. function plusFn(l, r) {
  13807. if (typeof l === 'undefined') return r;
  13808. if (typeof r === 'undefined') return l;
  13809. return l + r;
  13810. }
  13811. function isStateless($filter, filterName) {
  13812. var fn = $filter(filterName);
  13813. return !fn.$stateful;
  13814. }
  13815. var PURITY_ABSOLUTE = 1;
  13816. var PURITY_RELATIVE = 2;
  13817. // Detect nodes which could depend on non-shallow state of objects
  13818. function isPure(node, parentIsPure) {
  13819. switch (node.type) {
  13820. // Computed members might invoke a stateful toString()
  13821. case AST.MemberExpression:
  13822. if (node.computed) {
  13823. return false;
  13824. }
  13825. break;
  13826. // Unary always convert to primative
  13827. case AST.UnaryExpression:
  13828. return PURITY_ABSOLUTE;
  13829. // The binary + operator can invoke a stateful toString().
  13830. case AST.BinaryExpression:
  13831. return node.operator !== '+' ? PURITY_ABSOLUTE : false;
  13832. // Functions / filters probably read state from within objects
  13833. case AST.CallExpression:
  13834. return false;
  13835. }
  13836. return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure;
  13837. }
  13838. function findConstantAndWatchExpressions(ast, $filter, parentIsPure) {
  13839. var allConstants;
  13840. var argsToWatch;
  13841. var isStatelessFilter;
  13842. var astIsPure = ast.isPure = isPure(ast, parentIsPure);
  13843. switch (ast.type) {
  13844. case AST.Program:
  13845. allConstants = true;
  13846. forEach(ast.body, function(expr) {
  13847. findConstantAndWatchExpressions(expr.expression, $filter, astIsPure);
  13848. allConstants = allConstants && expr.expression.constant;
  13849. });
  13850. ast.constant = allConstants;
  13851. break;
  13852. case AST.Literal:
  13853. ast.constant = true;
  13854. ast.toWatch = [];
  13855. break;
  13856. case AST.UnaryExpression:
  13857. findConstantAndWatchExpressions(ast.argument, $filter, astIsPure);
  13858. ast.constant = ast.argument.constant;
  13859. ast.toWatch = ast.argument.toWatch;
  13860. break;
  13861. case AST.BinaryExpression:
  13862. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  13863. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  13864. ast.constant = ast.left.constant && ast.right.constant;
  13865. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  13866. break;
  13867. case AST.LogicalExpression:
  13868. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  13869. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  13870. ast.constant = ast.left.constant && ast.right.constant;
  13871. ast.toWatch = ast.constant ? [] : [ast];
  13872. break;
  13873. case AST.ConditionalExpression:
  13874. findConstantAndWatchExpressions(ast.test, $filter, astIsPure);
  13875. findConstantAndWatchExpressions(ast.alternate, $filter, astIsPure);
  13876. findConstantAndWatchExpressions(ast.consequent, $filter, astIsPure);
  13877. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  13878. ast.toWatch = ast.constant ? [] : [ast];
  13879. break;
  13880. case AST.Identifier:
  13881. ast.constant = false;
  13882. ast.toWatch = [ast];
  13883. break;
  13884. case AST.MemberExpression:
  13885. findConstantAndWatchExpressions(ast.object, $filter, astIsPure);
  13886. if (ast.computed) {
  13887. findConstantAndWatchExpressions(ast.property, $filter, astIsPure);
  13888. }
  13889. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  13890. ast.toWatch = ast.constant ? [] : [ast];
  13891. break;
  13892. case AST.CallExpression:
  13893. isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
  13894. allConstants = isStatelessFilter;
  13895. argsToWatch = [];
  13896. forEach(ast.arguments, function(expr) {
  13897. findConstantAndWatchExpressions(expr, $filter, astIsPure);
  13898. allConstants = allConstants && expr.constant;
  13899. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13900. });
  13901. ast.constant = allConstants;
  13902. ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
  13903. break;
  13904. case AST.AssignmentExpression:
  13905. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  13906. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  13907. ast.constant = ast.left.constant && ast.right.constant;
  13908. ast.toWatch = [ast];
  13909. break;
  13910. case AST.ArrayExpression:
  13911. allConstants = true;
  13912. argsToWatch = [];
  13913. forEach(ast.elements, function(expr) {
  13914. findConstantAndWatchExpressions(expr, $filter, astIsPure);
  13915. allConstants = allConstants && expr.constant;
  13916. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13917. });
  13918. ast.constant = allConstants;
  13919. ast.toWatch = argsToWatch;
  13920. break;
  13921. case AST.ObjectExpression:
  13922. allConstants = true;
  13923. argsToWatch = [];
  13924. forEach(ast.properties, function(property) {
  13925. findConstantAndWatchExpressions(property.value, $filter, astIsPure);
  13926. allConstants = allConstants && property.value.constant;
  13927. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  13928. if (property.computed) {
  13929. //`{[key]: value}` implicitly does `key.toString()` which may be non-pure
  13930. findConstantAndWatchExpressions(property.key, $filter, /*parentIsPure=*/false);
  13931. allConstants = allConstants && property.key.constant;
  13932. argsToWatch.push.apply(argsToWatch, property.key.toWatch);
  13933. }
  13934. });
  13935. ast.constant = allConstants;
  13936. ast.toWatch = argsToWatch;
  13937. break;
  13938. case AST.ThisExpression:
  13939. ast.constant = false;
  13940. ast.toWatch = [];
  13941. break;
  13942. case AST.LocalsExpression:
  13943. ast.constant = false;
  13944. ast.toWatch = [];
  13945. break;
  13946. }
  13947. }
  13948. function getInputs(body) {
  13949. if (body.length !== 1) return;
  13950. var lastExpression = body[0].expression;
  13951. var candidate = lastExpression.toWatch;
  13952. if (candidate.length !== 1) return candidate;
  13953. return candidate[0] !== lastExpression ? candidate : undefined;
  13954. }
  13955. function isAssignable(ast) {
  13956. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  13957. }
  13958. function assignableAST(ast) {
  13959. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  13960. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  13961. }
  13962. }
  13963. function isLiteral(ast) {
  13964. return ast.body.length === 0 ||
  13965. ast.body.length === 1 && (
  13966. ast.body[0].expression.type === AST.Literal ||
  13967. ast.body[0].expression.type === AST.ArrayExpression ||
  13968. ast.body[0].expression.type === AST.ObjectExpression);
  13969. }
  13970. function isConstant(ast) {
  13971. return ast.constant;
  13972. }
  13973. function ASTCompiler($filter) {
  13974. this.$filter = $filter;
  13975. }
  13976. ASTCompiler.prototype = {
  13977. compile: function(ast) {
  13978. var self = this;
  13979. this.state = {
  13980. nextId: 0,
  13981. filters: {},
  13982. fn: {vars: [], body: [], own: {}},
  13983. assign: {vars: [], body: [], own: {}},
  13984. inputs: []
  13985. };
  13986. findConstantAndWatchExpressions(ast, self.$filter);
  13987. var extra = '';
  13988. var assignable;
  13989. this.stage = 'assign';
  13990. if ((assignable = assignableAST(ast))) {
  13991. this.state.computing = 'assign';
  13992. var result = this.nextId();
  13993. this.recurse(assignable, result);
  13994. this.return_(result);
  13995. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  13996. }
  13997. var toWatch = getInputs(ast.body);
  13998. self.stage = 'inputs';
  13999. forEach(toWatch, function(watch, key) {
  14000. var fnKey = 'fn' + key;
  14001. self.state[fnKey] = {vars: [], body: [], own: {}};
  14002. self.state.computing = fnKey;
  14003. var intoId = self.nextId();
  14004. self.recurse(watch, intoId);
  14005. self.return_(intoId);
  14006. self.state.inputs.push({name: fnKey, isPure: watch.isPure});
  14007. watch.watchId = key;
  14008. });
  14009. this.state.computing = 'fn';
  14010. this.stage = 'main';
  14011. this.recurse(ast);
  14012. var fnString =
  14013. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  14014. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  14015. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  14016. this.filterPrefix() +
  14017. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  14018. extra +
  14019. this.watchFns() +
  14020. 'return fn;';
  14021. // eslint-disable-next-line no-new-func
  14022. var fn = (new Function('$filter',
  14023. 'getStringValue',
  14024. 'ifDefined',
  14025. 'plus',
  14026. fnString))(
  14027. this.$filter,
  14028. getStringValue,
  14029. ifDefined,
  14030. plusFn);
  14031. this.state = this.stage = undefined;
  14032. return fn;
  14033. },
  14034. USE: 'use',
  14035. STRICT: 'strict',
  14036. watchFns: function() {
  14037. var result = [];
  14038. var inputs = this.state.inputs;
  14039. var self = this;
  14040. forEach(inputs, function(input) {
  14041. result.push('var ' + input.name + '=' + self.generateFunction(input.name, 's'));
  14042. if (input.isPure) {
  14043. result.push(input.name, '.isPure=' + JSON.stringify(input.isPure) + ';');
  14044. }
  14045. });
  14046. if (inputs.length) {
  14047. result.push('fn.inputs=[' + inputs.map(function(i) { return i.name; }).join(',') + '];');
  14048. }
  14049. return result.join('');
  14050. },
  14051. generateFunction: function(name, params) {
  14052. return 'function(' + params + '){' +
  14053. this.varsPrefix(name) +
  14054. this.body(name) +
  14055. '};';
  14056. },
  14057. filterPrefix: function() {
  14058. var parts = [];
  14059. var self = this;
  14060. forEach(this.state.filters, function(id, filter) {
  14061. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  14062. });
  14063. if (parts.length) return 'var ' + parts.join(',') + ';';
  14064. return '';
  14065. },
  14066. varsPrefix: function(section) {
  14067. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  14068. },
  14069. body: function(section) {
  14070. return this.state[section].body.join('');
  14071. },
  14072. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14073. var left, right, self = this, args, expression, computed;
  14074. recursionFn = recursionFn || noop;
  14075. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  14076. intoId = intoId || this.nextId();
  14077. this.if_('i',
  14078. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  14079. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  14080. );
  14081. return;
  14082. }
  14083. switch (ast.type) {
  14084. case AST.Program:
  14085. forEach(ast.body, function(expression, pos) {
  14086. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  14087. if (pos !== ast.body.length - 1) {
  14088. self.current().body.push(right, ';');
  14089. } else {
  14090. self.return_(right);
  14091. }
  14092. });
  14093. break;
  14094. case AST.Literal:
  14095. expression = this.escape(ast.value);
  14096. this.assign(intoId, expression);
  14097. recursionFn(intoId || expression);
  14098. break;
  14099. case AST.UnaryExpression:
  14100. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  14101. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  14102. this.assign(intoId, expression);
  14103. recursionFn(expression);
  14104. break;
  14105. case AST.BinaryExpression:
  14106. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  14107. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  14108. if (ast.operator === '+') {
  14109. expression = this.plus(left, right);
  14110. } else if (ast.operator === '-') {
  14111. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  14112. } else {
  14113. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  14114. }
  14115. this.assign(intoId, expression);
  14116. recursionFn(expression);
  14117. break;
  14118. case AST.LogicalExpression:
  14119. intoId = intoId || this.nextId();
  14120. self.recurse(ast.left, intoId);
  14121. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  14122. recursionFn(intoId);
  14123. break;
  14124. case AST.ConditionalExpression:
  14125. intoId = intoId || this.nextId();
  14126. self.recurse(ast.test, intoId);
  14127. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  14128. recursionFn(intoId);
  14129. break;
  14130. case AST.Identifier:
  14131. intoId = intoId || this.nextId();
  14132. if (nameId) {
  14133. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  14134. nameId.computed = false;
  14135. nameId.name = ast.name;
  14136. }
  14137. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  14138. function() {
  14139. self.if_(self.stage === 'inputs' || 's', function() {
  14140. if (create && create !== 1) {
  14141. self.if_(
  14142. self.isNull(self.nonComputedMember('s', ast.name)),
  14143. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  14144. }
  14145. self.assign(intoId, self.nonComputedMember('s', ast.name));
  14146. });
  14147. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  14148. );
  14149. recursionFn(intoId);
  14150. break;
  14151. case AST.MemberExpression:
  14152. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  14153. intoId = intoId || this.nextId();
  14154. self.recurse(ast.object, left, undefined, function() {
  14155. self.if_(self.notNull(left), function() {
  14156. if (ast.computed) {
  14157. right = self.nextId();
  14158. self.recurse(ast.property, right);
  14159. self.getStringValue(right);
  14160. if (create && create !== 1) {
  14161. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  14162. }
  14163. expression = self.computedMember(left, right);
  14164. self.assign(intoId, expression);
  14165. if (nameId) {
  14166. nameId.computed = true;
  14167. nameId.name = right;
  14168. }
  14169. } else {
  14170. if (create && create !== 1) {
  14171. self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  14172. }
  14173. expression = self.nonComputedMember(left, ast.property.name);
  14174. self.assign(intoId, expression);
  14175. if (nameId) {
  14176. nameId.computed = false;
  14177. nameId.name = ast.property.name;
  14178. }
  14179. }
  14180. }, function() {
  14181. self.assign(intoId, 'undefined');
  14182. });
  14183. recursionFn(intoId);
  14184. }, !!create);
  14185. break;
  14186. case AST.CallExpression:
  14187. intoId = intoId || this.nextId();
  14188. if (ast.filter) {
  14189. right = self.filter(ast.callee.name);
  14190. args = [];
  14191. forEach(ast.arguments, function(expr) {
  14192. var argument = self.nextId();
  14193. self.recurse(expr, argument);
  14194. args.push(argument);
  14195. });
  14196. expression = right + '(' + args.join(',') + ')';
  14197. self.assign(intoId, expression);
  14198. recursionFn(intoId);
  14199. } else {
  14200. right = self.nextId();
  14201. left = {};
  14202. args = [];
  14203. self.recurse(ast.callee, right, left, function() {
  14204. self.if_(self.notNull(right), function() {
  14205. forEach(ast.arguments, function(expr) {
  14206. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  14207. args.push(argument);
  14208. });
  14209. });
  14210. if (left.name) {
  14211. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  14212. } else {
  14213. expression = right + '(' + args.join(',') + ')';
  14214. }
  14215. self.assign(intoId, expression);
  14216. }, function() {
  14217. self.assign(intoId, 'undefined');
  14218. });
  14219. recursionFn(intoId);
  14220. });
  14221. }
  14222. break;
  14223. case AST.AssignmentExpression:
  14224. right = this.nextId();
  14225. left = {};
  14226. this.recurse(ast.left, undefined, left, function() {
  14227. self.if_(self.notNull(left.context), function() {
  14228. self.recurse(ast.right, right);
  14229. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  14230. self.assign(intoId, expression);
  14231. recursionFn(intoId || expression);
  14232. });
  14233. }, 1);
  14234. break;
  14235. case AST.ArrayExpression:
  14236. args = [];
  14237. forEach(ast.elements, function(expr) {
  14238. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  14239. args.push(argument);
  14240. });
  14241. });
  14242. expression = '[' + args.join(',') + ']';
  14243. this.assign(intoId, expression);
  14244. recursionFn(intoId || expression);
  14245. break;
  14246. case AST.ObjectExpression:
  14247. args = [];
  14248. computed = false;
  14249. forEach(ast.properties, function(property) {
  14250. if (property.computed) {
  14251. computed = true;
  14252. }
  14253. });
  14254. if (computed) {
  14255. intoId = intoId || this.nextId();
  14256. this.assign(intoId, '{}');
  14257. forEach(ast.properties, function(property) {
  14258. if (property.computed) {
  14259. left = self.nextId();
  14260. self.recurse(property.key, left);
  14261. } else {
  14262. left = property.key.type === AST.Identifier ?
  14263. property.key.name :
  14264. ('' + property.key.value);
  14265. }
  14266. right = self.nextId();
  14267. self.recurse(property.value, right);
  14268. self.assign(self.member(intoId, left, property.computed), right);
  14269. });
  14270. } else {
  14271. forEach(ast.properties, function(property) {
  14272. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  14273. args.push(self.escape(
  14274. property.key.type === AST.Identifier ? property.key.name :
  14275. ('' + property.key.value)) +
  14276. ':' + expr);
  14277. });
  14278. });
  14279. expression = '{' + args.join(',') + '}';
  14280. this.assign(intoId, expression);
  14281. }
  14282. recursionFn(intoId || expression);
  14283. break;
  14284. case AST.ThisExpression:
  14285. this.assign(intoId, 's');
  14286. recursionFn(intoId || 's');
  14287. break;
  14288. case AST.LocalsExpression:
  14289. this.assign(intoId, 'l');
  14290. recursionFn(intoId || 'l');
  14291. break;
  14292. case AST.NGValueParameter:
  14293. this.assign(intoId, 'v');
  14294. recursionFn(intoId || 'v');
  14295. break;
  14296. }
  14297. },
  14298. getHasOwnProperty: function(element, property) {
  14299. var key = element + '.' + property;
  14300. var own = this.current().own;
  14301. if (!own.hasOwnProperty(key)) {
  14302. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  14303. }
  14304. return own[key];
  14305. },
  14306. assign: function(id, value) {
  14307. if (!id) return;
  14308. this.current().body.push(id, '=', value, ';');
  14309. return id;
  14310. },
  14311. filter: function(filterName) {
  14312. if (!this.state.filters.hasOwnProperty(filterName)) {
  14313. this.state.filters[filterName] = this.nextId(true);
  14314. }
  14315. return this.state.filters[filterName];
  14316. },
  14317. ifDefined: function(id, defaultValue) {
  14318. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  14319. },
  14320. plus: function(left, right) {
  14321. return 'plus(' + left + ',' + right + ')';
  14322. },
  14323. return_: function(id) {
  14324. this.current().body.push('return ', id, ';');
  14325. },
  14326. if_: function(test, alternate, consequent) {
  14327. if (test === true) {
  14328. alternate();
  14329. } else {
  14330. var body = this.current().body;
  14331. body.push('if(', test, '){');
  14332. alternate();
  14333. body.push('}');
  14334. if (consequent) {
  14335. body.push('else{');
  14336. consequent();
  14337. body.push('}');
  14338. }
  14339. }
  14340. },
  14341. not: function(expression) {
  14342. return '!(' + expression + ')';
  14343. },
  14344. isNull: function(expression) {
  14345. return expression + '==null';
  14346. },
  14347. notNull: function(expression) {
  14348. return expression + '!=null';
  14349. },
  14350. nonComputedMember: function(left, right) {
  14351. var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
  14352. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  14353. if (SAFE_IDENTIFIER.test(right)) {
  14354. return left + '.' + right;
  14355. } else {
  14356. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  14357. }
  14358. },
  14359. computedMember: function(left, right) {
  14360. return left + '[' + right + ']';
  14361. },
  14362. member: function(left, right, computed) {
  14363. if (computed) return this.computedMember(left, right);
  14364. return this.nonComputedMember(left, right);
  14365. },
  14366. getStringValue: function(item) {
  14367. this.assign(item, 'getStringValue(' + item + ')');
  14368. },
  14369. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14370. var self = this;
  14371. return function() {
  14372. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  14373. };
  14374. },
  14375. lazyAssign: function(id, value) {
  14376. var self = this;
  14377. return function() {
  14378. self.assign(id, value);
  14379. };
  14380. },
  14381. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  14382. stringEscapeFn: function(c) {
  14383. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  14384. },
  14385. escape: function(value) {
  14386. if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
  14387. if (isNumber(value)) return value.toString();
  14388. if (value === true) return 'true';
  14389. if (value === false) return 'false';
  14390. if (value === null) return 'null';
  14391. if (typeof value === 'undefined') return 'undefined';
  14392. throw $parseMinErr('esc', 'IMPOSSIBLE');
  14393. },
  14394. nextId: function(skip, init) {
  14395. var id = 'v' + (this.state.nextId++);
  14396. if (!skip) {
  14397. this.current().vars.push(id + (init ? '=' + init : ''));
  14398. }
  14399. return id;
  14400. },
  14401. current: function() {
  14402. return this.state[this.state.computing];
  14403. }
  14404. };
  14405. function ASTInterpreter($filter) {
  14406. this.$filter = $filter;
  14407. }
  14408. ASTInterpreter.prototype = {
  14409. compile: function(ast) {
  14410. var self = this;
  14411. findConstantAndWatchExpressions(ast, self.$filter);
  14412. var assignable;
  14413. var assign;
  14414. if ((assignable = assignableAST(ast))) {
  14415. assign = this.recurse(assignable);
  14416. }
  14417. var toWatch = getInputs(ast.body);
  14418. var inputs;
  14419. if (toWatch) {
  14420. inputs = [];
  14421. forEach(toWatch, function(watch, key) {
  14422. var input = self.recurse(watch);
  14423. input.isPure = watch.isPure;
  14424. watch.input = input;
  14425. inputs.push(input);
  14426. watch.watchId = key;
  14427. });
  14428. }
  14429. var expressions = [];
  14430. forEach(ast.body, function(expression) {
  14431. expressions.push(self.recurse(expression.expression));
  14432. });
  14433. var fn = ast.body.length === 0 ? noop :
  14434. ast.body.length === 1 ? expressions[0] :
  14435. function(scope, locals) {
  14436. var lastValue;
  14437. forEach(expressions, function(exp) {
  14438. lastValue = exp(scope, locals);
  14439. });
  14440. return lastValue;
  14441. };
  14442. if (assign) {
  14443. fn.assign = function(scope, value, locals) {
  14444. return assign(scope, locals, value);
  14445. };
  14446. }
  14447. if (inputs) {
  14448. fn.inputs = inputs;
  14449. }
  14450. return fn;
  14451. },
  14452. recurse: function(ast, context, create) {
  14453. var left, right, self = this, args;
  14454. if (ast.input) {
  14455. return this.inputs(ast.input, ast.watchId);
  14456. }
  14457. switch (ast.type) {
  14458. case AST.Literal:
  14459. return this.value(ast.value, context);
  14460. case AST.UnaryExpression:
  14461. right = this.recurse(ast.argument);
  14462. return this['unary' + ast.operator](right, context);
  14463. case AST.BinaryExpression:
  14464. left = this.recurse(ast.left);
  14465. right = this.recurse(ast.right);
  14466. return this['binary' + ast.operator](left, right, context);
  14467. case AST.LogicalExpression:
  14468. left = this.recurse(ast.left);
  14469. right = this.recurse(ast.right);
  14470. return this['binary' + ast.operator](left, right, context);
  14471. case AST.ConditionalExpression:
  14472. return this['ternary?:'](
  14473. this.recurse(ast.test),
  14474. this.recurse(ast.alternate),
  14475. this.recurse(ast.consequent),
  14476. context
  14477. );
  14478. case AST.Identifier:
  14479. return self.identifier(ast.name, context, create);
  14480. case AST.MemberExpression:
  14481. left = this.recurse(ast.object, false, !!create);
  14482. if (!ast.computed) {
  14483. right = ast.property.name;
  14484. }
  14485. if (ast.computed) right = this.recurse(ast.property);
  14486. return ast.computed ?
  14487. this.computedMember(left, right, context, create) :
  14488. this.nonComputedMember(left, right, context, create);
  14489. case AST.CallExpression:
  14490. args = [];
  14491. forEach(ast.arguments, function(expr) {
  14492. args.push(self.recurse(expr));
  14493. });
  14494. if (ast.filter) right = this.$filter(ast.callee.name);
  14495. if (!ast.filter) right = this.recurse(ast.callee, true);
  14496. return ast.filter ?
  14497. function(scope, locals, assign, inputs) {
  14498. var values = [];
  14499. for (var i = 0; i < args.length; ++i) {
  14500. values.push(args[i](scope, locals, assign, inputs));
  14501. }
  14502. var value = right.apply(undefined, values, inputs);
  14503. return context ? {context: undefined, name: undefined, value: value} : value;
  14504. } :
  14505. function(scope, locals, assign, inputs) {
  14506. var rhs = right(scope, locals, assign, inputs);
  14507. var value;
  14508. if (rhs.value != null) {
  14509. var values = [];
  14510. for (var i = 0; i < args.length; ++i) {
  14511. values.push(args[i](scope, locals, assign, inputs));
  14512. }
  14513. value = rhs.value.apply(rhs.context, values);
  14514. }
  14515. return context ? {value: value} : value;
  14516. };
  14517. case AST.AssignmentExpression:
  14518. left = this.recurse(ast.left, true, 1);
  14519. right = this.recurse(ast.right);
  14520. return function(scope, locals, assign, inputs) {
  14521. var lhs = left(scope, locals, assign, inputs);
  14522. var rhs = right(scope, locals, assign, inputs);
  14523. lhs.context[lhs.name] = rhs;
  14524. return context ? {value: rhs} : rhs;
  14525. };
  14526. case AST.ArrayExpression:
  14527. args = [];
  14528. forEach(ast.elements, function(expr) {
  14529. args.push(self.recurse(expr));
  14530. });
  14531. return function(scope, locals, assign, inputs) {
  14532. var value = [];
  14533. for (var i = 0; i < args.length; ++i) {
  14534. value.push(args[i](scope, locals, assign, inputs));
  14535. }
  14536. return context ? {value: value} : value;
  14537. };
  14538. case AST.ObjectExpression:
  14539. args = [];
  14540. forEach(ast.properties, function(property) {
  14541. if (property.computed) {
  14542. args.push({key: self.recurse(property.key),
  14543. computed: true,
  14544. value: self.recurse(property.value)
  14545. });
  14546. } else {
  14547. args.push({key: property.key.type === AST.Identifier ?
  14548. property.key.name :
  14549. ('' + property.key.value),
  14550. computed: false,
  14551. value: self.recurse(property.value)
  14552. });
  14553. }
  14554. });
  14555. return function(scope, locals, assign, inputs) {
  14556. var value = {};
  14557. for (var i = 0; i < args.length; ++i) {
  14558. if (args[i].computed) {
  14559. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  14560. } else {
  14561. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  14562. }
  14563. }
  14564. return context ? {value: value} : value;
  14565. };
  14566. case AST.ThisExpression:
  14567. return function(scope) {
  14568. return context ? {value: scope} : scope;
  14569. };
  14570. case AST.LocalsExpression:
  14571. return function(scope, locals) {
  14572. return context ? {value: locals} : locals;
  14573. };
  14574. case AST.NGValueParameter:
  14575. return function(scope, locals, assign) {
  14576. return context ? {value: assign} : assign;
  14577. };
  14578. }
  14579. },
  14580. 'unary+': function(argument, context) {
  14581. return function(scope, locals, assign, inputs) {
  14582. var arg = argument(scope, locals, assign, inputs);
  14583. if (isDefined(arg)) {
  14584. arg = +arg;
  14585. } else {
  14586. arg = 0;
  14587. }
  14588. return context ? {value: arg} : arg;
  14589. };
  14590. },
  14591. 'unary-': function(argument, context) {
  14592. return function(scope, locals, assign, inputs) {
  14593. var arg = argument(scope, locals, assign, inputs);
  14594. if (isDefined(arg)) {
  14595. arg = -arg;
  14596. } else {
  14597. arg = -0;
  14598. }
  14599. return context ? {value: arg} : arg;
  14600. };
  14601. },
  14602. 'unary!': function(argument, context) {
  14603. return function(scope, locals, assign, inputs) {
  14604. var arg = !argument(scope, locals, assign, inputs);
  14605. return context ? {value: arg} : arg;
  14606. };
  14607. },
  14608. 'binary+': function(left, right, context) {
  14609. return function(scope, locals, assign, inputs) {
  14610. var lhs = left(scope, locals, assign, inputs);
  14611. var rhs = right(scope, locals, assign, inputs);
  14612. var arg = plusFn(lhs, rhs);
  14613. return context ? {value: arg} : arg;
  14614. };
  14615. },
  14616. 'binary-': function(left, right, context) {
  14617. return function(scope, locals, assign, inputs) {
  14618. var lhs = left(scope, locals, assign, inputs);
  14619. var rhs = right(scope, locals, assign, inputs);
  14620. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  14621. return context ? {value: arg} : arg;
  14622. };
  14623. },
  14624. 'binary*': function(left, right, context) {
  14625. return function(scope, locals, assign, inputs) {
  14626. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  14627. return context ? {value: arg} : arg;
  14628. };
  14629. },
  14630. 'binary/': function(left, right, context) {
  14631. return function(scope, locals, assign, inputs) {
  14632. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  14633. return context ? {value: arg} : arg;
  14634. };
  14635. },
  14636. 'binary%': function(left, right, context) {
  14637. return function(scope, locals, assign, inputs) {
  14638. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  14639. return context ? {value: arg} : arg;
  14640. };
  14641. },
  14642. 'binary===': function(left, right, context) {
  14643. return function(scope, locals, assign, inputs) {
  14644. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  14645. return context ? {value: arg} : arg;
  14646. };
  14647. },
  14648. 'binary!==': function(left, right, context) {
  14649. return function(scope, locals, assign, inputs) {
  14650. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  14651. return context ? {value: arg} : arg;
  14652. };
  14653. },
  14654. 'binary==': function(left, right, context) {
  14655. return function(scope, locals, assign, inputs) {
  14656. // eslint-disable-next-line eqeqeq
  14657. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  14658. return context ? {value: arg} : arg;
  14659. };
  14660. },
  14661. 'binary!=': function(left, right, context) {
  14662. return function(scope, locals, assign, inputs) {
  14663. // eslint-disable-next-line eqeqeq
  14664. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  14665. return context ? {value: arg} : arg;
  14666. };
  14667. },
  14668. 'binary<': function(left, right, context) {
  14669. return function(scope, locals, assign, inputs) {
  14670. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  14671. return context ? {value: arg} : arg;
  14672. };
  14673. },
  14674. 'binary>': function(left, right, context) {
  14675. return function(scope, locals, assign, inputs) {
  14676. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  14677. return context ? {value: arg} : arg;
  14678. };
  14679. },
  14680. 'binary<=': function(left, right, context) {
  14681. return function(scope, locals, assign, inputs) {
  14682. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  14683. return context ? {value: arg} : arg;
  14684. };
  14685. },
  14686. 'binary>=': function(left, right, context) {
  14687. return function(scope, locals, assign, inputs) {
  14688. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  14689. return context ? {value: arg} : arg;
  14690. };
  14691. },
  14692. 'binary&&': function(left, right, context) {
  14693. return function(scope, locals, assign, inputs) {
  14694. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  14695. return context ? {value: arg} : arg;
  14696. };
  14697. },
  14698. 'binary||': function(left, right, context) {
  14699. return function(scope, locals, assign, inputs) {
  14700. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  14701. return context ? {value: arg} : arg;
  14702. };
  14703. },
  14704. 'ternary?:': function(test, alternate, consequent, context) {
  14705. return function(scope, locals, assign, inputs) {
  14706. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  14707. return context ? {value: arg} : arg;
  14708. };
  14709. },
  14710. value: function(value, context) {
  14711. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  14712. },
  14713. identifier: function(name, context, create) {
  14714. return function(scope, locals, assign, inputs) {
  14715. var base = locals && (name in locals) ? locals : scope;
  14716. if (create && create !== 1 && base && base[name] == null) {
  14717. base[name] = {};
  14718. }
  14719. var value = base ? base[name] : undefined;
  14720. if (context) {
  14721. return {context: base, name: name, value: value};
  14722. } else {
  14723. return value;
  14724. }
  14725. };
  14726. },
  14727. computedMember: function(left, right, context, create) {
  14728. return function(scope, locals, assign, inputs) {
  14729. var lhs = left(scope, locals, assign, inputs);
  14730. var rhs;
  14731. var value;
  14732. if (lhs != null) {
  14733. rhs = right(scope, locals, assign, inputs);
  14734. rhs = getStringValue(rhs);
  14735. if (create && create !== 1) {
  14736. if (lhs && !(lhs[rhs])) {
  14737. lhs[rhs] = {};
  14738. }
  14739. }
  14740. value = lhs[rhs];
  14741. }
  14742. if (context) {
  14743. return {context: lhs, name: rhs, value: value};
  14744. } else {
  14745. return value;
  14746. }
  14747. };
  14748. },
  14749. nonComputedMember: function(left, right, context, create) {
  14750. return function(scope, locals, assign, inputs) {
  14751. var lhs = left(scope, locals, assign, inputs);
  14752. if (create && create !== 1) {
  14753. if (lhs && lhs[right] == null) {
  14754. lhs[right] = {};
  14755. }
  14756. }
  14757. var value = lhs != null ? lhs[right] : undefined;
  14758. if (context) {
  14759. return {context: lhs, name: right, value: value};
  14760. } else {
  14761. return value;
  14762. }
  14763. };
  14764. },
  14765. inputs: function(input, watchId) {
  14766. return function(scope, value, locals, inputs) {
  14767. if (inputs) return inputs[watchId];
  14768. return input(scope, value, locals);
  14769. };
  14770. }
  14771. };
  14772. /**
  14773. * @constructor
  14774. */
  14775. function Parser(lexer, $filter, options) {
  14776. this.ast = new AST(lexer, options);
  14777. this.astCompiler = options.csp ? new ASTInterpreter($filter) :
  14778. new ASTCompiler($filter);
  14779. }
  14780. Parser.prototype = {
  14781. constructor: Parser,
  14782. parse: function(text) {
  14783. var ast = this.ast.ast(text);
  14784. var fn = this.astCompiler.compile(ast);
  14785. fn.literal = isLiteral(ast);
  14786. fn.constant = isConstant(ast);
  14787. return fn;
  14788. }
  14789. };
  14790. function getValueOf(value) {
  14791. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  14792. }
  14793. ///////////////////////////////////
  14794. /**
  14795. * @ngdoc service
  14796. * @name $parse
  14797. * @kind function
  14798. *
  14799. * @description
  14800. *
  14801. * Converts Angular {@link guide/expression expression} into a function.
  14802. *
  14803. * ```js
  14804. * var getter = $parse('user.name');
  14805. * var setter = getter.assign;
  14806. * var context = {user:{name:'angular'}};
  14807. * var locals = {user:{name:'local'}};
  14808. *
  14809. * expect(getter(context)).toEqual('angular');
  14810. * setter(context, 'newValue');
  14811. * expect(context.user.name).toEqual('newValue');
  14812. * expect(getter(context, locals)).toEqual('local');
  14813. * ```
  14814. *
  14815. *
  14816. * @param {string} expression String expression to compile.
  14817. * @returns {function(context, locals)} a function which represents the compiled expression:
  14818. *
  14819. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14820. * are evaluated against (typically a scope object).
  14821. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14822. * `context`.
  14823. *
  14824. * The returned function also has the following properties:
  14825. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  14826. * literal.
  14827. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  14828. * constant literals.
  14829. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  14830. * set to a function to change its value on the given context.
  14831. *
  14832. */
  14833. /**
  14834. * @ngdoc provider
  14835. * @name $parseProvider
  14836. * @this
  14837. *
  14838. * @description
  14839. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  14840. * service.
  14841. */
  14842. function $ParseProvider() {
  14843. var cache = createMap();
  14844. var literals = {
  14845. 'true': true,
  14846. 'false': false,
  14847. 'null': null,
  14848. 'undefined': undefined
  14849. };
  14850. var identStart, identContinue;
  14851. /**
  14852. * @ngdoc method
  14853. * @name $parseProvider#addLiteral
  14854. * @description
  14855. *
  14856. * Configure $parse service to add literal values that will be present as literal at expressions.
  14857. *
  14858. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  14859. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  14860. *
  14861. **/
  14862. this.addLiteral = function(literalName, literalValue) {
  14863. literals[literalName] = literalValue;
  14864. };
  14865. /**
  14866. * @ngdoc method
  14867. * @name $parseProvider#setIdentifierFns
  14868. *
  14869. * @description
  14870. *
  14871. * Allows defining the set of characters that are allowed in Angular expressions. The function
  14872. * `identifierStart` will get called to know if a given character is a valid character to be the
  14873. * first character for an identifier. The function `identifierContinue` will get called to know if
  14874. * a given character is a valid character to be a follow-up identifier character. The functions
  14875. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  14876. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  14877. * mind that the `string` parameter can be two characters long depending on the character
  14878. * representation. It is expected for the function to return `true` or `false`, whether that
  14879. * character is allowed or not.
  14880. *
  14881. * Since this function will be called extensively, keep the implementation of these functions fast,
  14882. * as the performance of these functions have a direct impact on the expressions parsing speed.
  14883. *
  14884. * @param {function=} identifierStart The function that will decide whether the given character is
  14885. * a valid identifier start character.
  14886. * @param {function=} identifierContinue The function that will decide whether the given character is
  14887. * a valid identifier continue character.
  14888. */
  14889. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  14890. identStart = identifierStart;
  14891. identContinue = identifierContinue;
  14892. return this;
  14893. };
  14894. this.$get = ['$filter', function($filter) {
  14895. var noUnsafeEval = csp().noUnsafeEval;
  14896. var $parseOptions = {
  14897. csp: noUnsafeEval,
  14898. literals: copy(literals),
  14899. isIdentifierStart: isFunction(identStart) && identStart,
  14900. isIdentifierContinue: isFunction(identContinue) && identContinue
  14901. };
  14902. return $parse;
  14903. function $parse(exp, interceptorFn) {
  14904. var parsedExpression, oneTime, cacheKey;
  14905. switch (typeof exp) {
  14906. case 'string':
  14907. exp = exp.trim();
  14908. cacheKey = exp;
  14909. parsedExpression = cache[cacheKey];
  14910. if (!parsedExpression) {
  14911. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  14912. oneTime = true;
  14913. exp = exp.substring(2);
  14914. }
  14915. var lexer = new Lexer($parseOptions);
  14916. var parser = new Parser(lexer, $filter, $parseOptions);
  14917. parsedExpression = parser.parse(exp);
  14918. if (parsedExpression.constant) {
  14919. parsedExpression.$$watchDelegate = constantWatchDelegate;
  14920. } else if (oneTime) {
  14921. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  14922. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  14923. } else if (parsedExpression.inputs) {
  14924. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  14925. }
  14926. cache[cacheKey] = parsedExpression;
  14927. }
  14928. return addInterceptor(parsedExpression, interceptorFn);
  14929. case 'function':
  14930. return addInterceptor(exp, interceptorFn);
  14931. default:
  14932. return addInterceptor(noop, interceptorFn);
  14933. }
  14934. }
  14935. function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) {
  14936. if (newValue == null || oldValueOfValue == null) { // null/undefined
  14937. return newValue === oldValueOfValue;
  14938. }
  14939. if (typeof newValue === 'object') {
  14940. // attempt to convert the value to a primitive type
  14941. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  14942. // be cheaply dirty-checked
  14943. newValue = getValueOf(newValue);
  14944. if (typeof newValue === 'object' && !compareObjectIdentity) {
  14945. // objects/arrays are not supported - deep-watching them would be too expensive
  14946. return false;
  14947. }
  14948. // fall-through to the primitive equality check
  14949. }
  14950. //Primitive or NaN
  14951. // eslint-disable-next-line no-self-compare
  14952. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  14953. }
  14954. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14955. var inputExpressions = parsedExpression.inputs;
  14956. var lastResult;
  14957. if (inputExpressions.length === 1) {
  14958. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14959. inputExpressions = inputExpressions[0];
  14960. return scope.$watch(function expressionInputWatch(scope) {
  14961. var newInputValue = inputExpressions(scope);
  14962. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, inputExpressions.isPure)) {
  14963. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  14964. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  14965. }
  14966. return lastResult;
  14967. }, listener, objectEquality, prettyPrintExpression);
  14968. }
  14969. var oldInputValueOfValues = [];
  14970. var oldInputValues = [];
  14971. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14972. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14973. oldInputValues[i] = null;
  14974. }
  14975. return scope.$watch(function expressionInputsWatch(scope) {
  14976. var changed = false;
  14977. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14978. var newInputValue = inputExpressions[i](scope);
  14979. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], inputExpressions[i].isPure))) {
  14980. oldInputValues[i] = newInputValue;
  14981. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  14982. }
  14983. }
  14984. if (changed) {
  14985. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  14986. }
  14987. return lastResult;
  14988. }, listener, objectEquality, prettyPrintExpression);
  14989. }
  14990. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14991. var unwatch, lastValue;
  14992. if (parsedExpression.inputs) {
  14993. unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);
  14994. } else {
  14995. unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);
  14996. }
  14997. return unwatch;
  14998. function oneTimeWatch(scope) {
  14999. return parsedExpression(scope);
  15000. }
  15001. function oneTimeListener(value, old, scope) {
  15002. lastValue = value;
  15003. if (isFunction(listener)) {
  15004. listener(value, old, scope);
  15005. }
  15006. if (isDefined(value)) {
  15007. scope.$$postDigest(function() {
  15008. if (isDefined(lastValue)) {
  15009. unwatch();
  15010. }
  15011. });
  15012. }
  15013. }
  15014. }
  15015. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  15016. var unwatch, lastValue;
  15017. unwatch = scope.$watch(function oneTimeWatch(scope) {
  15018. return parsedExpression(scope);
  15019. }, function oneTimeListener(value, old, scope) {
  15020. lastValue = value;
  15021. if (isFunction(listener)) {
  15022. listener(value, old, scope);
  15023. }
  15024. if (isAllDefined(value)) {
  15025. scope.$$postDigest(function() {
  15026. if (isAllDefined(lastValue)) unwatch();
  15027. });
  15028. }
  15029. }, objectEquality);
  15030. return unwatch;
  15031. function isAllDefined(value) {
  15032. var allDefined = true;
  15033. forEach(value, function(val) {
  15034. if (!isDefined(val)) allDefined = false;
  15035. });
  15036. return allDefined;
  15037. }
  15038. }
  15039. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  15040. var unwatch = scope.$watch(function constantWatch(scope) {
  15041. unwatch();
  15042. return parsedExpression(scope);
  15043. }, listener, objectEquality);
  15044. return unwatch;
  15045. }
  15046. function addInterceptor(parsedExpression, interceptorFn) {
  15047. if (!interceptorFn) return parsedExpression;
  15048. var watchDelegate = parsedExpression.$$watchDelegate;
  15049. var useInputs = false;
  15050. var regularWatch =
  15051. watchDelegate !== oneTimeLiteralWatchDelegate &&
  15052. watchDelegate !== oneTimeWatchDelegate;
  15053. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  15054. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  15055. return interceptorFn(value, scope, locals);
  15056. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  15057. var value = parsedExpression(scope, locals, assign, inputs);
  15058. var result = interceptorFn(value, scope, locals);
  15059. // we only return the interceptor's result if the
  15060. // initial value is defined (for bind-once)
  15061. return isDefined(value) ? result : value;
  15062. };
  15063. // Propagate $$watchDelegates other then inputsWatchDelegate
  15064. useInputs = !parsedExpression.inputs;
  15065. if (watchDelegate && watchDelegate !== inputsWatchDelegate) {
  15066. fn.$$watchDelegate = watchDelegate;
  15067. fn.inputs = parsedExpression.inputs;
  15068. } else if (!interceptorFn.$stateful) {
  15069. // Treat interceptor like filters - assume non-stateful by default and use the inputsWatchDelegate
  15070. fn.$$watchDelegate = inputsWatchDelegate;
  15071. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  15072. }
  15073. if (fn.inputs) {
  15074. fn.inputs = fn.inputs.map(function(e) {
  15075. // Remove the isPure flag of inputs when it is not absolute because they are now wrapped in a
  15076. // potentially non-pure interceptor function.
  15077. if (e.isPure === PURITY_RELATIVE) {
  15078. return function depurifier(s) { return e(s); };
  15079. }
  15080. return e;
  15081. });
  15082. }
  15083. return fn;
  15084. }
  15085. }];
  15086. }
  15087. /**
  15088. * @ngdoc service
  15089. * @name $q
  15090. * @requires $rootScope
  15091. *
  15092. * @description
  15093. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  15094. * when they are done processing.
  15095. *
  15096. * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred
  15097. * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  15098. *
  15099. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  15100. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  15101. *
  15102. * # $q constructor
  15103. *
  15104. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  15105. * function as the first argument. This is similar to the native Promise implementation from ES6,
  15106. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  15107. *
  15108. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  15109. * available yet.
  15110. *
  15111. * It can be used like so:
  15112. *
  15113. * ```js
  15114. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  15115. * // are available in the current lexical scope (they could have been injected or passed in).
  15116. *
  15117. * function asyncGreet(name) {
  15118. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  15119. * return $q(function(resolve, reject) {
  15120. * setTimeout(function() {
  15121. * if (okToGreet(name)) {
  15122. * resolve('Hello, ' + name + '!');
  15123. * } else {
  15124. * reject('Greeting ' + name + ' is not allowed.');
  15125. * }
  15126. * }, 1000);
  15127. * });
  15128. * }
  15129. *
  15130. * var promise = asyncGreet('Robin Hood');
  15131. * promise.then(function(greeting) {
  15132. * alert('Success: ' + greeting);
  15133. * }, function(reason) {
  15134. * alert('Failed: ' + reason);
  15135. * });
  15136. * ```
  15137. *
  15138. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  15139. *
  15140. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  15141. *
  15142. * However, the more traditional CommonJS-style usage is still available, and documented below.
  15143. *
  15144. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  15145. * interface for interacting with an object that represents the result of an action that is
  15146. * performed asynchronously, and may or may not be finished at any given point in time.
  15147. *
  15148. * From the perspective of dealing with error handling, deferred and promise APIs are to
  15149. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  15150. *
  15151. * ```js
  15152. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  15153. * // are available in the current lexical scope (they could have been injected or passed in).
  15154. *
  15155. * function asyncGreet(name) {
  15156. * var deferred = $q.defer();
  15157. *
  15158. * setTimeout(function() {
  15159. * deferred.notify('About to greet ' + name + '.');
  15160. *
  15161. * if (okToGreet(name)) {
  15162. * deferred.resolve('Hello, ' + name + '!');
  15163. * } else {
  15164. * deferred.reject('Greeting ' + name + ' is not allowed.');
  15165. * }
  15166. * }, 1000);
  15167. *
  15168. * return deferred.promise;
  15169. * }
  15170. *
  15171. * var promise = asyncGreet('Robin Hood');
  15172. * promise.then(function(greeting) {
  15173. * alert('Success: ' + greeting);
  15174. * }, function(reason) {
  15175. * alert('Failed: ' + reason);
  15176. * }, function(update) {
  15177. * alert('Got notification: ' + update);
  15178. * });
  15179. * ```
  15180. *
  15181. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  15182. * comes in the way of guarantees that promise and deferred APIs make, see
  15183. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  15184. *
  15185. * Additionally the promise api allows for composition that is very hard to do with the
  15186. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  15187. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  15188. * section on serial or parallel joining of promises.
  15189. *
  15190. * # The Deferred API
  15191. *
  15192. * A new instance of deferred is constructed by calling `$q.defer()`.
  15193. *
  15194. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  15195. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  15196. * of the task.
  15197. *
  15198. * **Methods**
  15199. *
  15200. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  15201. * constructed via `$q.reject`, the promise will be rejected instead.
  15202. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  15203. * resolving it with a rejection constructed via `$q.reject`.
  15204. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  15205. * multiple times before the promise is either resolved or rejected.
  15206. *
  15207. * **Properties**
  15208. *
  15209. * - promise – `{Promise}` – promise object associated with this deferred.
  15210. *
  15211. *
  15212. * # The Promise API
  15213. *
  15214. * A new promise instance is created when a deferred instance is created and can be retrieved by
  15215. * calling `deferred.promise`.
  15216. *
  15217. * The purpose of the promise object is to allow for interested parties to get access to the result
  15218. * of the deferred task when it completes.
  15219. *
  15220. * **Methods**
  15221. *
  15222. * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
  15223. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  15224. * as soon as the result is available. The callbacks are called with a single argument: the result
  15225. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  15226. * provide a progress indication, before the promise is resolved or rejected.
  15227. *
  15228. * This method *returns a new promise* which is resolved or rejected via the return value of the
  15229. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  15230. * with the value which is resolved in that promise using
  15231. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  15232. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  15233. * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
  15234. * arguments are optional.
  15235. *
  15236. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  15237. *
  15238. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  15239. * but to do so without modifying the final value. This is useful to release resources or do some
  15240. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  15241. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  15242. * more information.
  15243. *
  15244. * # Chaining promises
  15245. *
  15246. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  15247. * possible to create a chain of promises:
  15248. *
  15249. * ```js
  15250. * promiseB = promiseA.then(function(result) {
  15251. * return result + 1;
  15252. * });
  15253. *
  15254. * // promiseB will be resolved immediately after promiseA is resolved and its value
  15255. * // will be the result of promiseA incremented by 1
  15256. * ```
  15257. *
  15258. * It is possible to create chains of any length and since a promise can be resolved with another
  15259. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  15260. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  15261. * $http's response interceptors.
  15262. *
  15263. *
  15264. * # Differences between Kris Kowal's Q and $q
  15265. *
  15266. * There are two main differences:
  15267. *
  15268. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  15269. * mechanism in angular, which means faster propagation of resolution or rejection into your
  15270. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  15271. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  15272. * all the important functionality needed for common async tasks.
  15273. *
  15274. * # Testing
  15275. *
  15276. * ```js
  15277. * it('should simulate promise', inject(function($q, $rootScope) {
  15278. * var deferred = $q.defer();
  15279. * var promise = deferred.promise;
  15280. * var resolvedValue;
  15281. *
  15282. * promise.then(function(value) { resolvedValue = value; });
  15283. * expect(resolvedValue).toBeUndefined();
  15284. *
  15285. * // Simulate resolving of promise
  15286. * deferred.resolve(123);
  15287. * // Note that the 'then' function does not get called synchronously.
  15288. * // This is because we want the promise API to always be async, whether or not
  15289. * // it got called synchronously or asynchronously.
  15290. * expect(resolvedValue).toBeUndefined();
  15291. *
  15292. * // Propagate promise resolution to 'then' functions using $apply().
  15293. * $rootScope.$apply();
  15294. * expect(resolvedValue).toEqual(123);
  15295. * }));
  15296. * ```
  15297. *
  15298. * @param {function(function, function)} resolver Function which is responsible for resolving or
  15299. * rejecting the newly created promise. The first parameter is a function which resolves the
  15300. * promise, the second parameter is a function which rejects the promise.
  15301. *
  15302. * @returns {Promise} The newly created promise.
  15303. */
  15304. /**
  15305. * @ngdoc provider
  15306. * @name $qProvider
  15307. * @this
  15308. *
  15309. * @description
  15310. */
  15311. function $QProvider() {
  15312. var errorOnUnhandledRejections = true;
  15313. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  15314. return qFactory(function(callback) {
  15315. $rootScope.$evalAsync(callback);
  15316. }, $exceptionHandler, errorOnUnhandledRejections);
  15317. }];
  15318. /**
  15319. * @ngdoc method
  15320. * @name $qProvider#errorOnUnhandledRejections
  15321. * @kind function
  15322. *
  15323. * @description
  15324. * Retrieves or overrides whether to generate an error when a rejected promise is not handled.
  15325. * This feature is enabled by default.
  15326. *
  15327. * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.
  15328. * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for
  15329. * chaining otherwise.
  15330. */
  15331. this.errorOnUnhandledRejections = function(value) {
  15332. if (isDefined(value)) {
  15333. errorOnUnhandledRejections = value;
  15334. return this;
  15335. } else {
  15336. return errorOnUnhandledRejections;
  15337. }
  15338. };
  15339. }
  15340. /** @this */
  15341. function $$QProvider() {
  15342. var errorOnUnhandledRejections = true;
  15343. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  15344. return qFactory(function(callback) {
  15345. $browser.defer(callback);
  15346. }, $exceptionHandler, errorOnUnhandledRejections);
  15347. }];
  15348. this.errorOnUnhandledRejections = function(value) {
  15349. if (isDefined(value)) {
  15350. errorOnUnhandledRejections = value;
  15351. return this;
  15352. } else {
  15353. return errorOnUnhandledRejections;
  15354. }
  15355. };
  15356. }
  15357. /**
  15358. * Constructs a promise manager.
  15359. *
  15360. * @param {function(function)} nextTick Function for executing functions in the next turn.
  15361. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  15362. * debugging purposes.
  15363. * @param {boolean=} errorOnUnhandledRejections Whether an error should be generated on unhandled
  15364. * promises rejections.
  15365. * @returns {object} Promise manager.
  15366. */
  15367. function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {
  15368. var $qMinErr = minErr('$q', TypeError);
  15369. var queueSize = 0;
  15370. var checkQueue = [];
  15371. /**
  15372. * @ngdoc method
  15373. * @name ng.$q#defer
  15374. * @kind function
  15375. *
  15376. * @description
  15377. * Creates a `Deferred` object which represents a task which will finish in the future.
  15378. *
  15379. * @returns {Deferred} Returns a new instance of deferred.
  15380. */
  15381. function defer() {
  15382. return new Deferred();
  15383. }
  15384. function Deferred() {
  15385. var promise = this.promise = new Promise();
  15386. //Non prototype methods necessary to support unbound execution :/
  15387. this.resolve = function(val) { resolvePromise(promise, val); };
  15388. this.reject = function(reason) { rejectPromise(promise, reason); };
  15389. this.notify = function(progress) { notifyPromise(promise, progress); };
  15390. }
  15391. function Promise() {
  15392. this.$$state = { status: 0 };
  15393. }
  15394. extend(Promise.prototype, {
  15395. then: function(onFulfilled, onRejected, progressBack) {
  15396. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  15397. return this;
  15398. }
  15399. var result = new Promise();
  15400. this.$$state.pending = this.$$state.pending || [];
  15401. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  15402. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  15403. return result;
  15404. },
  15405. 'catch': function(callback) {
  15406. return this.then(null, callback);
  15407. },
  15408. 'finally': function(callback, progressBack) {
  15409. return this.then(function(value) {
  15410. return handleCallback(value, resolve, callback);
  15411. }, function(error) {
  15412. return handleCallback(error, reject, callback);
  15413. }, progressBack);
  15414. }
  15415. });
  15416. function processQueue(state) {
  15417. var fn, promise, pending;
  15418. pending = state.pending;
  15419. state.processScheduled = false;
  15420. state.pending = undefined;
  15421. try {
  15422. for (var i = 0, ii = pending.length; i < ii; ++i) {
  15423. markQStateExceptionHandled(state);
  15424. promise = pending[i][0];
  15425. fn = pending[i][state.status];
  15426. try {
  15427. if (isFunction(fn)) {
  15428. resolvePromise(promise, fn(state.value));
  15429. } else if (state.status === 1) {
  15430. resolvePromise(promise, state.value);
  15431. } else {
  15432. rejectPromise(promise, state.value);
  15433. }
  15434. } catch (e) {
  15435. rejectPromise(promise, e);
  15436. }
  15437. }
  15438. } finally {
  15439. --queueSize;
  15440. if (errorOnUnhandledRejections && queueSize === 0) {
  15441. nextTick(processChecks);
  15442. }
  15443. }
  15444. }
  15445. function processChecks() {
  15446. // eslint-disable-next-line no-unmodified-loop-condition
  15447. while (!queueSize && checkQueue.length) {
  15448. var toCheck = checkQueue.shift();
  15449. if (!isStateExceptionHandled(toCheck)) {
  15450. markQStateExceptionHandled(toCheck);
  15451. var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);
  15452. if (isError(toCheck.value)) {
  15453. exceptionHandler(toCheck.value, errorMessage);
  15454. } else {
  15455. exceptionHandler(errorMessage);
  15456. }
  15457. }
  15458. }
  15459. }
  15460. function scheduleProcessQueue(state) {
  15461. if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !isStateExceptionHandled(state)) {
  15462. if (queueSize === 0 && checkQueue.length === 0) {
  15463. nextTick(processChecks);
  15464. }
  15465. checkQueue.push(state);
  15466. }
  15467. if (state.processScheduled || !state.pending) return;
  15468. state.processScheduled = true;
  15469. ++queueSize;
  15470. nextTick(function() { processQueue(state); });
  15471. }
  15472. function resolvePromise(promise, val) {
  15473. if (promise.$$state.status) return;
  15474. if (val === promise) {
  15475. $$reject(promise, $qMinErr(
  15476. 'qcycle',
  15477. 'Expected promise to be resolved with value other than itself \'{0}\'',
  15478. val));
  15479. } else {
  15480. $$resolve(promise, val);
  15481. }
  15482. }
  15483. function $$resolve(promise, val) {
  15484. var then;
  15485. var done = false;
  15486. try {
  15487. if (isObject(val) || isFunction(val)) then = val.then;
  15488. if (isFunction(then)) {
  15489. promise.$$state.status = -1;
  15490. then.call(val, doResolve, doReject, doNotify);
  15491. } else {
  15492. promise.$$state.value = val;
  15493. promise.$$state.status = 1;
  15494. scheduleProcessQueue(promise.$$state);
  15495. }
  15496. } catch (e) {
  15497. doReject(e);
  15498. }
  15499. function doResolve(val) {
  15500. if (done) return;
  15501. done = true;
  15502. $$resolve(promise, val);
  15503. }
  15504. function doReject(val) {
  15505. if (done) return;
  15506. done = true;
  15507. $$reject(promise, val);
  15508. }
  15509. function doNotify(progress) {
  15510. notifyPromise(promise, progress);
  15511. }
  15512. }
  15513. function rejectPromise(promise, reason) {
  15514. if (promise.$$state.status) return;
  15515. $$reject(promise, reason);
  15516. }
  15517. function $$reject(promise, reason) {
  15518. promise.$$state.value = reason;
  15519. promise.$$state.status = 2;
  15520. scheduleProcessQueue(promise.$$state);
  15521. }
  15522. function notifyPromise(promise, progress) {
  15523. var callbacks = promise.$$state.pending;
  15524. if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {
  15525. nextTick(function() {
  15526. var callback, result;
  15527. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  15528. result = callbacks[i][0];
  15529. callback = callbacks[i][3];
  15530. try {
  15531. notifyPromise(result, isFunction(callback) ? callback(progress) : progress);
  15532. } catch (e) {
  15533. exceptionHandler(e);
  15534. }
  15535. }
  15536. });
  15537. }
  15538. }
  15539. /**
  15540. * @ngdoc method
  15541. * @name $q#reject
  15542. * @kind function
  15543. *
  15544. * @description
  15545. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  15546. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  15547. * a promise chain, you don't need to worry about it.
  15548. *
  15549. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  15550. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  15551. * a promise error callback and you want to forward the error to the promise derived from the
  15552. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  15553. * `reject`.
  15554. *
  15555. * ```js
  15556. * promiseB = promiseA.then(function(result) {
  15557. * // success: do something and resolve promiseB
  15558. * // with the old or a new result
  15559. * return result;
  15560. * }, function(reason) {
  15561. * // error: handle the error if possible and
  15562. * // resolve promiseB with newPromiseOrValue,
  15563. * // otherwise forward the rejection to promiseB
  15564. * if (canHandle(reason)) {
  15565. * // handle the error and recover
  15566. * return newPromiseOrValue;
  15567. * }
  15568. * return $q.reject(reason);
  15569. * });
  15570. * ```
  15571. *
  15572. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  15573. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  15574. */
  15575. function reject(reason) {
  15576. var result = new Promise();
  15577. rejectPromise(result, reason);
  15578. return result;
  15579. }
  15580. function handleCallback(value, resolver, callback) {
  15581. var callbackOutput = null;
  15582. try {
  15583. if (isFunction(callback)) callbackOutput = callback();
  15584. } catch (e) {
  15585. return reject(e);
  15586. }
  15587. if (isPromiseLike(callbackOutput)) {
  15588. return callbackOutput.then(function() {
  15589. return resolver(value);
  15590. }, reject);
  15591. } else {
  15592. return resolver(value);
  15593. }
  15594. }
  15595. /**
  15596. * @ngdoc method
  15597. * @name $q#when
  15598. * @kind function
  15599. *
  15600. * @description
  15601. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  15602. * This is useful when you are dealing with an object that might or might not be a promise, or if
  15603. * the promise comes from a source that can't be trusted.
  15604. *
  15605. * @param {*} value Value or a promise
  15606. * @param {Function=} successCallback
  15607. * @param {Function=} errorCallback
  15608. * @param {Function=} progressCallback
  15609. * @returns {Promise} Returns a promise of the passed value or promise
  15610. */
  15611. function when(value, callback, errback, progressBack) {
  15612. var result = new Promise();
  15613. resolvePromise(result, value);
  15614. return result.then(callback, errback, progressBack);
  15615. }
  15616. /**
  15617. * @ngdoc method
  15618. * @name $q#resolve
  15619. * @kind function
  15620. *
  15621. * @description
  15622. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  15623. *
  15624. * @param {*} value Value or a promise
  15625. * @param {Function=} successCallback
  15626. * @param {Function=} errorCallback
  15627. * @param {Function=} progressCallback
  15628. * @returns {Promise} Returns a promise of the passed value or promise
  15629. */
  15630. var resolve = when;
  15631. /**
  15632. * @ngdoc method
  15633. * @name $q#all
  15634. * @kind function
  15635. *
  15636. * @description
  15637. * Combines multiple promises into a single promise that is resolved when all of the input
  15638. * promises are resolved.
  15639. *
  15640. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15641. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  15642. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  15643. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  15644. * with the same rejection value.
  15645. */
  15646. function all(promises) {
  15647. var result = new Promise(),
  15648. counter = 0,
  15649. results = isArray(promises) ? [] : {};
  15650. forEach(promises, function(promise, key) {
  15651. counter++;
  15652. when(promise).then(function(value) {
  15653. results[key] = value;
  15654. if (!(--counter)) resolvePromise(result, results);
  15655. }, function(reason) {
  15656. rejectPromise(result, reason);
  15657. });
  15658. });
  15659. if (counter === 0) {
  15660. resolvePromise(result, results);
  15661. }
  15662. return result;
  15663. }
  15664. /**
  15665. * @ngdoc method
  15666. * @name $q#race
  15667. * @kind function
  15668. *
  15669. * @description
  15670. * Returns a promise that resolves or rejects as soon as one of those promises
  15671. * resolves or rejects, with the value or reason from that promise.
  15672. *
  15673. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15674. * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
  15675. * resolves or rejects, with the value or reason from that promise.
  15676. */
  15677. function race(promises) {
  15678. var deferred = defer();
  15679. forEach(promises, function(promise) {
  15680. when(promise).then(deferred.resolve, deferred.reject);
  15681. });
  15682. return deferred.promise;
  15683. }
  15684. function $Q(resolver) {
  15685. if (!isFunction(resolver)) {
  15686. throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
  15687. }
  15688. var promise = new Promise();
  15689. function resolveFn(value) {
  15690. resolvePromise(promise, value);
  15691. }
  15692. function rejectFn(reason) {
  15693. rejectPromise(promise, reason);
  15694. }
  15695. resolver(resolveFn, rejectFn);
  15696. return promise;
  15697. }
  15698. // Let's make the instanceof operator work for promises, so that
  15699. // `new $q(fn) instanceof $q` would evaluate to true.
  15700. $Q.prototype = Promise.prototype;
  15701. $Q.defer = defer;
  15702. $Q.reject = reject;
  15703. $Q.when = when;
  15704. $Q.resolve = resolve;
  15705. $Q.all = all;
  15706. $Q.race = race;
  15707. return $Q;
  15708. }
  15709. function isStateExceptionHandled(state) {
  15710. return !!state.pur;
  15711. }
  15712. function markQStateExceptionHandled(state) {
  15713. state.pur = true;
  15714. }
  15715. function markQExceptionHandled(q) {
  15716. markQStateExceptionHandled(q.$$state);
  15717. }
  15718. /** @this */
  15719. function $$RAFProvider() { //rAF
  15720. this.$get = ['$window', '$timeout', function($window, $timeout) {
  15721. var requestAnimationFrame = $window.requestAnimationFrame ||
  15722. $window.webkitRequestAnimationFrame;
  15723. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  15724. $window.webkitCancelAnimationFrame ||
  15725. $window.webkitCancelRequestAnimationFrame;
  15726. var rafSupported = !!requestAnimationFrame;
  15727. var raf = rafSupported
  15728. ? function(fn) {
  15729. var id = requestAnimationFrame(fn);
  15730. return function() {
  15731. cancelAnimationFrame(id);
  15732. };
  15733. }
  15734. : function(fn) {
  15735. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  15736. return function() {
  15737. $timeout.cancel(timer);
  15738. };
  15739. };
  15740. raf.supported = rafSupported;
  15741. return raf;
  15742. }];
  15743. }
  15744. /**
  15745. * DESIGN NOTES
  15746. *
  15747. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  15748. *
  15749. * The typical use of scope is to watch the expressions, which most of the time return the same
  15750. * value as last time so we optimize the operation.
  15751. *
  15752. * Closures construction is expensive in terms of speed as well as memory:
  15753. * - No closures, instead use prototypical inheritance for API
  15754. * - Internal state needs to be stored on scope directly, which means that private state is
  15755. * exposed as $$____ properties
  15756. *
  15757. * Loop operations are optimized by using while(count--) { ... }
  15758. * - This means that in order to keep the same order of execution as addition we have to add
  15759. * items to the array at the beginning (unshift) instead of at the end (push)
  15760. *
  15761. * Child scopes are created and removed often
  15762. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  15763. *
  15764. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  15765. * in the same way as watch. Watch requires return of the initialization function which is expensive
  15766. * to construct.
  15767. */
  15768. /**
  15769. * @ngdoc provider
  15770. * @name $rootScopeProvider
  15771. * @description
  15772. *
  15773. * Provider for the $rootScope service.
  15774. */
  15775. /**
  15776. * @ngdoc method
  15777. * @name $rootScopeProvider#digestTtl
  15778. * @description
  15779. *
  15780. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  15781. * assuming that the model is unstable.
  15782. *
  15783. * The current default is 10 iterations.
  15784. *
  15785. * In complex applications it's possible that the dependencies between `$watch`s will result in
  15786. * several digest iterations. However if an application needs more than the default 10 digest
  15787. * iterations for its model to stabilize then you should investigate what is causing the model to
  15788. * continuously change during the digest.
  15789. *
  15790. * Increasing the TTL could have performance implications, so you should not change it without
  15791. * proper justification.
  15792. *
  15793. * @param {number} limit The number of digest iterations.
  15794. */
  15795. /**
  15796. * @ngdoc service
  15797. * @name $rootScope
  15798. * @this
  15799. *
  15800. * @description
  15801. *
  15802. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  15803. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  15804. * between the model and the view, via a mechanism for watching the model for changes.
  15805. * They also provide event emission/broadcast and subscription facility. See the
  15806. * {@link guide/scope developer guide on scopes}.
  15807. */
  15808. function $RootScopeProvider() {
  15809. var TTL = 10;
  15810. var $rootScopeMinErr = minErr('$rootScope');
  15811. var lastDirtyWatch = null;
  15812. var applyAsyncId = null;
  15813. this.digestTtl = function(value) {
  15814. if (arguments.length) {
  15815. TTL = value;
  15816. }
  15817. return TTL;
  15818. };
  15819. function createChildScopeClass(parent) {
  15820. function ChildScope() {
  15821. this.$$watchers = this.$$nextSibling =
  15822. this.$$childHead = this.$$childTail = null;
  15823. this.$$listeners = {};
  15824. this.$$listenerCount = {};
  15825. this.$$watchersCount = 0;
  15826. this.$id = nextUid();
  15827. this.$$ChildScope = null;
  15828. }
  15829. ChildScope.prototype = parent;
  15830. return ChildScope;
  15831. }
  15832. this.$get = ['$exceptionHandler', '$parse', '$browser',
  15833. function($exceptionHandler, $parse, $browser) {
  15834. function destroyChildScope($event) {
  15835. $event.currentScope.$$destroyed = true;
  15836. }
  15837. function cleanUpScope($scope) {
  15838. // Support: IE 9 only
  15839. if (msie === 9) {
  15840. // There is a memory leak in IE9 if all child scopes are not disconnected
  15841. // completely when a scope is destroyed. So this code will recurse up through
  15842. // all this scopes children
  15843. //
  15844. // See issue https://github.com/angular/angular.js/issues/10706
  15845. if ($scope.$$childHead) {
  15846. cleanUpScope($scope.$$childHead);
  15847. }
  15848. if ($scope.$$nextSibling) {
  15849. cleanUpScope($scope.$$nextSibling);
  15850. }
  15851. }
  15852. // The code below works around IE9 and V8's memory leaks
  15853. //
  15854. // See:
  15855. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  15856. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  15857. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  15858. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  15859. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  15860. }
  15861. /**
  15862. * @ngdoc type
  15863. * @name $rootScope.Scope
  15864. *
  15865. * @description
  15866. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  15867. * {@link auto.$injector $injector}. Child scopes are created using the
  15868. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  15869. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  15870. * an in-depth introduction and usage examples.
  15871. *
  15872. *
  15873. * # Inheritance
  15874. * A scope can inherit from a parent scope, as in this example:
  15875. * ```js
  15876. var parent = $rootScope;
  15877. var child = parent.$new();
  15878. parent.salutation = "Hello";
  15879. expect(child.salutation).toEqual('Hello');
  15880. child.salutation = "Welcome";
  15881. expect(child.salutation).toEqual('Welcome');
  15882. expect(parent.salutation).toEqual('Hello');
  15883. * ```
  15884. *
  15885. * When interacting with `Scope` in tests, additional helper methods are available on the
  15886. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  15887. * details.
  15888. *
  15889. *
  15890. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  15891. * provided for the current scope. Defaults to {@link ng}.
  15892. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  15893. * append/override services provided by `providers`. This is handy
  15894. * when unit-testing and having the need to override a default
  15895. * service.
  15896. * @returns {Object} Newly created scope.
  15897. *
  15898. */
  15899. function Scope() {
  15900. this.$id = nextUid();
  15901. this.$$phase = this.$parent = this.$$watchers =
  15902. this.$$nextSibling = this.$$prevSibling =
  15903. this.$$childHead = this.$$childTail = null;
  15904. this.$root = this;
  15905. this.$$destroyed = false;
  15906. this.$$listeners = {};
  15907. this.$$listenerCount = {};
  15908. this.$$watchersCount = 0;
  15909. this.$$isolateBindings = null;
  15910. }
  15911. /**
  15912. * @ngdoc property
  15913. * @name $rootScope.Scope#$id
  15914. *
  15915. * @description
  15916. * Unique scope ID (monotonically increasing) useful for debugging.
  15917. */
  15918. /**
  15919. * @ngdoc property
  15920. * @name $rootScope.Scope#$parent
  15921. *
  15922. * @description
  15923. * Reference to the parent scope.
  15924. */
  15925. /**
  15926. * @ngdoc property
  15927. * @name $rootScope.Scope#$root
  15928. *
  15929. * @description
  15930. * Reference to the root scope.
  15931. */
  15932. Scope.prototype = {
  15933. constructor: Scope,
  15934. /**
  15935. * @ngdoc method
  15936. * @name $rootScope.Scope#$new
  15937. * @kind function
  15938. *
  15939. * @description
  15940. * Creates a new child {@link ng.$rootScope.Scope scope}.
  15941. *
  15942. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  15943. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  15944. *
  15945. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  15946. * desired for the scope and its child scopes to be permanently detached from the parent and
  15947. * thus stop participating in model change detection and listener notification by invoking.
  15948. *
  15949. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  15950. * parent scope. The scope is isolated, as it can not see parent scope properties.
  15951. * When creating widgets, it is useful for the widget to not accidentally read parent
  15952. * state.
  15953. *
  15954. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  15955. * of the newly created scope. Defaults to `this` scope if not provided.
  15956. * This is used when creating a transclude scope to correctly place it
  15957. * in the scope hierarchy while maintaining the correct prototypical
  15958. * inheritance.
  15959. *
  15960. * @returns {Object} The newly created child scope.
  15961. *
  15962. */
  15963. $new: function(isolate, parent) {
  15964. var child;
  15965. parent = parent || this;
  15966. if (isolate) {
  15967. child = new Scope();
  15968. child.$root = this.$root;
  15969. } else {
  15970. // Only create a child scope class if somebody asks for one,
  15971. // but cache it to allow the VM to optimize lookups.
  15972. if (!this.$$ChildScope) {
  15973. this.$$ChildScope = createChildScopeClass(this);
  15974. }
  15975. child = new this.$$ChildScope();
  15976. }
  15977. child.$parent = parent;
  15978. child.$$prevSibling = parent.$$childTail;
  15979. if (parent.$$childHead) {
  15980. parent.$$childTail.$$nextSibling = child;
  15981. parent.$$childTail = child;
  15982. } else {
  15983. parent.$$childHead = parent.$$childTail = child;
  15984. }
  15985. // When the new scope is not isolated or we inherit from `this`, and
  15986. // the parent scope is destroyed, the property `$$destroyed` is inherited
  15987. // prototypically. In all other cases, this property needs to be set
  15988. // when the parent scope is destroyed.
  15989. // The listener needs to be added after the parent is set
  15990. if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
  15991. return child;
  15992. },
  15993. /**
  15994. * @ngdoc method
  15995. * @name $rootScope.Scope#$watch
  15996. * @kind function
  15997. *
  15998. * @description
  15999. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  16000. *
  16001. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  16002. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  16003. * its value when executed multiple times with the same input because it may be executed multiple
  16004. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  16005. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
  16006. * - The `listener` is called only when the value from the current `watchExpression` and the
  16007. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  16008. * see below). Inequality is determined according to reference inequality,
  16009. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  16010. * via the `!==` Javascript operator, unless `objectEquality == true`
  16011. * (see next point)
  16012. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  16013. * according to the {@link angular.equals} function. To save the value of the object for
  16014. * later comparison, the {@link angular.copy} function is used. This therefore means that
  16015. * watching complex objects will have adverse memory and performance implications.
  16016. * - This should not be used to watch for changes in objects that are
  16017. * or contain [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.
  16018. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  16019. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  16020. * iteration limit is 10 to prevent an infinite loop deadlock.
  16021. *
  16022. *
  16023. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  16024. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  16025. * multiple calls to your `watchExpression` because it will execute multiple times in a
  16026. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  16027. *
  16028. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  16029. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  16030. * watcher. In rare cases, this is undesirable because the listener is called when the result
  16031. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  16032. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  16033. * listener was called due to initialization.
  16034. *
  16035. *
  16036. *
  16037. * # Example
  16038. * ```js
  16039. // let's assume that scope was dependency injected as the $rootScope
  16040. var scope = $rootScope;
  16041. scope.name = 'misko';
  16042. scope.counter = 0;
  16043. expect(scope.counter).toEqual(0);
  16044. scope.$watch('name', function(newValue, oldValue) {
  16045. scope.counter = scope.counter + 1;
  16046. });
  16047. expect(scope.counter).toEqual(0);
  16048. scope.$digest();
  16049. // the listener is always called during the first $digest loop after it was registered
  16050. expect(scope.counter).toEqual(1);
  16051. scope.$digest();
  16052. // but now it will not be called unless the value changes
  16053. expect(scope.counter).toEqual(1);
  16054. scope.name = 'adam';
  16055. scope.$digest();
  16056. expect(scope.counter).toEqual(2);
  16057. // Using a function as a watchExpression
  16058. var food;
  16059. scope.foodCounter = 0;
  16060. expect(scope.foodCounter).toEqual(0);
  16061. scope.$watch(
  16062. // This function returns the value being watched. It is called for each turn of the $digest loop
  16063. function() { return food; },
  16064. // This is the change listener, called when the value returned from the above function changes
  16065. function(newValue, oldValue) {
  16066. if ( newValue !== oldValue ) {
  16067. // Only increment the counter if the value changed
  16068. scope.foodCounter = scope.foodCounter + 1;
  16069. }
  16070. }
  16071. );
  16072. // No digest has been run so the counter will be zero
  16073. expect(scope.foodCounter).toEqual(0);
  16074. // Run the digest but since food has not changed count will still be zero
  16075. scope.$digest();
  16076. expect(scope.foodCounter).toEqual(0);
  16077. // Update food and run digest. Now the counter will increment
  16078. food = 'cheeseburger';
  16079. scope.$digest();
  16080. expect(scope.foodCounter).toEqual(1);
  16081. * ```
  16082. *
  16083. *
  16084. *
  16085. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  16086. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  16087. * a call to the `listener`.
  16088. *
  16089. * - `string`: Evaluated as {@link guide/expression expression}
  16090. * - `function(scope)`: called with current `scope` as a parameter.
  16091. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  16092. * of `watchExpression` changes.
  16093. *
  16094. * - `newVal` contains the current value of the `watchExpression`
  16095. * - `oldVal` contains the previous value of the `watchExpression`
  16096. * - `scope` refers to the current scope
  16097. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  16098. * comparing for reference equality.
  16099. * @returns {function()} Returns a deregistration function for this listener.
  16100. */
  16101. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  16102. var get = $parse(watchExp);
  16103. if (get.$$watchDelegate) {
  16104. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  16105. }
  16106. var scope = this,
  16107. array = scope.$$watchers,
  16108. watcher = {
  16109. fn: listener,
  16110. last: initWatchVal,
  16111. get: get,
  16112. exp: prettyPrintExpression || watchExp,
  16113. eq: !!objectEquality
  16114. };
  16115. lastDirtyWatch = null;
  16116. if (!isFunction(listener)) {
  16117. watcher.fn = noop;
  16118. }
  16119. if (!array) {
  16120. array = scope.$$watchers = [];
  16121. array.$$digestWatchIndex = -1;
  16122. }
  16123. // we use unshift since we use a while loop in $digest for speed.
  16124. // the while loop reads in reverse order.
  16125. array.unshift(watcher);
  16126. array.$$digestWatchIndex++;
  16127. incrementWatchersCount(this, 1);
  16128. return function deregisterWatch() {
  16129. var index = arrayRemove(array, watcher);
  16130. if (index >= 0) {
  16131. incrementWatchersCount(scope, -1);
  16132. if (index < array.$$digestWatchIndex) {
  16133. array.$$digestWatchIndex--;
  16134. }
  16135. }
  16136. lastDirtyWatch = null;
  16137. };
  16138. },
  16139. /**
  16140. * @ngdoc method
  16141. * @name $rootScope.Scope#$watchGroup
  16142. * @kind function
  16143. *
  16144. * @description
  16145. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  16146. * If any one expression in the collection changes the `listener` is executed.
  16147. *
  16148. * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return
  16149. * values are examined for changes on every call to `$digest`.
  16150. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  16151. *
  16152. * `$watchGroup` is more performant than watching each expression individually, and should be
  16153. * used when the listener does not need to know which expression has changed.
  16154. * If the listener needs to know which expression has changed,
  16155. * {@link ng.$rootScope.Scope#$watch $watch()} or
  16156. * {@link ng.$rootScope.Scope#$watchCollection $watchCollection()} should be used.
  16157. *
  16158. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  16159. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  16160. *
  16161. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  16162. * expression in `watchExpressions` changes
  16163. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  16164. * those of `watchExpression`
  16165. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  16166. * those of `watchExpression`.
  16167. *
  16168. * Note that `newValues` and `oldValues` reflect the differences in each **individual**
  16169. * expression, and not the difference of the values between each call of the listener.
  16170. * That means the difference between `newValues` and `oldValues` cannot be used to determine
  16171. * which expression has changed / remained stable:
  16172. *
  16173. * ```js
  16174. *
  16175. * $scope.$watchGroup(['v1', 'v2'], function(newValues, oldValues) {
  16176. * console.log(newValues, oldValues);
  16177. * });
  16178. *
  16179. * // newValues, oldValues initially
  16180. * // [undefined, undefined], [undefined, undefined]
  16181. *
  16182. * $scope.v1 = 'a';
  16183. * $scope.v2 = 'a';
  16184. *
  16185. * // ['a', 'a'], [undefined, undefined]
  16186. *
  16187. * $scope.v2 = 'b'
  16188. *
  16189. * // v1 hasn't changed since it became `'a'`, therefore its oldValue is still `undefined`
  16190. * // ['a', 'b'], [undefined, 'a']
  16191. *
  16192. * ```
  16193. *
  16194. * The `scope` refers to the current scope.
  16195. * @returns {function()} Returns a de-registration function for all listeners.
  16196. */
  16197. $watchGroup: function(watchExpressions, listener) {
  16198. var oldValues = new Array(watchExpressions.length);
  16199. var newValues = new Array(watchExpressions.length);
  16200. var deregisterFns = [];
  16201. var self = this;
  16202. var changeReactionScheduled = false;
  16203. var firstRun = true;
  16204. if (!watchExpressions.length) {
  16205. // No expressions means we call the listener ASAP
  16206. var shouldCall = true;
  16207. self.$evalAsync(function() {
  16208. if (shouldCall) listener(newValues, newValues, self);
  16209. });
  16210. return function deregisterWatchGroup() {
  16211. shouldCall = false;
  16212. };
  16213. }
  16214. if (watchExpressions.length === 1) {
  16215. // Special case size of one
  16216. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  16217. newValues[0] = value;
  16218. oldValues[0] = oldValue;
  16219. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  16220. });
  16221. }
  16222. forEach(watchExpressions, function(expr, i) {
  16223. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  16224. newValues[i] = value;
  16225. oldValues[i] = oldValue;
  16226. if (!changeReactionScheduled) {
  16227. changeReactionScheduled = true;
  16228. self.$evalAsync(watchGroupAction);
  16229. }
  16230. });
  16231. deregisterFns.push(unwatchFn);
  16232. });
  16233. function watchGroupAction() {
  16234. changeReactionScheduled = false;
  16235. if (firstRun) {
  16236. firstRun = false;
  16237. listener(newValues, newValues, self);
  16238. } else {
  16239. listener(newValues, oldValues, self);
  16240. }
  16241. }
  16242. return function deregisterWatchGroup() {
  16243. while (deregisterFns.length) {
  16244. deregisterFns.shift()();
  16245. }
  16246. };
  16247. },
  16248. /**
  16249. * @ngdoc method
  16250. * @name $rootScope.Scope#$watchCollection
  16251. * @kind function
  16252. *
  16253. * @description
  16254. * Shallow watches the properties of an object and fires whenever any of the properties change
  16255. * (for arrays, this implies watching the array items; for object maps, this implies watching
  16256. * the properties). If a change is detected, the `listener` callback is fired.
  16257. *
  16258. * - The `obj` collection is observed via standard $watch operation and is examined on every
  16259. * call to $digest() to see if any items have been added, removed, or moved.
  16260. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  16261. * adding, removing, and moving items belonging to an object or array.
  16262. *
  16263. *
  16264. * # Example
  16265. * ```js
  16266. $scope.names = ['igor', 'matias', 'misko', 'james'];
  16267. $scope.dataCount = 4;
  16268. $scope.$watchCollection('names', function(newNames, oldNames) {
  16269. $scope.dataCount = newNames.length;
  16270. });
  16271. expect($scope.dataCount).toEqual(4);
  16272. $scope.$digest();
  16273. //still at 4 ... no changes
  16274. expect($scope.dataCount).toEqual(4);
  16275. $scope.names.pop();
  16276. $scope.$digest();
  16277. //now there's been a change
  16278. expect($scope.dataCount).toEqual(3);
  16279. * ```
  16280. *
  16281. *
  16282. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  16283. * expression value should evaluate to an object or an array which is observed on each
  16284. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  16285. * collection will trigger a call to the `listener`.
  16286. *
  16287. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  16288. * when a change is detected.
  16289. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  16290. * - The `oldCollection` object is a copy of the former collection data.
  16291. * Due to performance considerations, the`oldCollection` value is computed only if the
  16292. * `listener` function declares two or more arguments.
  16293. * - The `scope` argument refers to the current scope.
  16294. *
  16295. * @returns {function()} Returns a de-registration function for this listener. When the
  16296. * de-registration function is executed, the internal watch operation is terminated.
  16297. */
  16298. $watchCollection: function(obj, listener) {
  16299. $watchCollectionInterceptor.$stateful = true;
  16300. var self = this;
  16301. // the current value, updated on each dirty-check run
  16302. var newValue;
  16303. // a shallow copy of the newValue from the last dirty-check run,
  16304. // updated to match newValue during dirty-check run
  16305. var oldValue;
  16306. // a shallow copy of the newValue from when the last change happened
  16307. var veryOldValue;
  16308. // only track veryOldValue if the listener is asking for it
  16309. var trackVeryOldValue = (listener.length > 1);
  16310. var changeDetected = 0;
  16311. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  16312. var internalArray = [];
  16313. var internalObject = {};
  16314. var initRun = true;
  16315. var oldLength = 0;
  16316. function $watchCollectionInterceptor(_value) {
  16317. newValue = _value;
  16318. var newLength, key, bothNaN, newItem, oldItem;
  16319. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  16320. if (isUndefined(newValue)) return;
  16321. if (!isObject(newValue)) { // if primitive
  16322. if (oldValue !== newValue) {
  16323. oldValue = newValue;
  16324. changeDetected++;
  16325. }
  16326. } else if (isArrayLike(newValue)) {
  16327. if (oldValue !== internalArray) {
  16328. // we are transitioning from something which was not an array into array.
  16329. oldValue = internalArray;
  16330. oldLength = oldValue.length = 0;
  16331. changeDetected++;
  16332. }
  16333. newLength = newValue.length;
  16334. if (oldLength !== newLength) {
  16335. // if lengths do not match we need to trigger change notification
  16336. changeDetected++;
  16337. oldValue.length = oldLength = newLength;
  16338. }
  16339. // copy the items to oldValue and look for changes.
  16340. for (var i = 0; i < newLength; i++) {
  16341. oldItem = oldValue[i];
  16342. newItem = newValue[i];
  16343. // eslint-disable-next-line no-self-compare
  16344. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16345. if (!bothNaN && (oldItem !== newItem)) {
  16346. changeDetected++;
  16347. oldValue[i] = newItem;
  16348. }
  16349. }
  16350. } else {
  16351. if (oldValue !== internalObject) {
  16352. // we are transitioning from something which was not an object into object.
  16353. oldValue = internalObject = {};
  16354. oldLength = 0;
  16355. changeDetected++;
  16356. }
  16357. // copy the items to oldValue and look for changes.
  16358. newLength = 0;
  16359. for (key in newValue) {
  16360. if (hasOwnProperty.call(newValue, key)) {
  16361. newLength++;
  16362. newItem = newValue[key];
  16363. oldItem = oldValue[key];
  16364. if (key in oldValue) {
  16365. // eslint-disable-next-line no-self-compare
  16366. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16367. if (!bothNaN && (oldItem !== newItem)) {
  16368. changeDetected++;
  16369. oldValue[key] = newItem;
  16370. }
  16371. } else {
  16372. oldLength++;
  16373. oldValue[key] = newItem;
  16374. changeDetected++;
  16375. }
  16376. }
  16377. }
  16378. if (oldLength > newLength) {
  16379. // we used to have more keys, need to find them and destroy them.
  16380. changeDetected++;
  16381. for (key in oldValue) {
  16382. if (!hasOwnProperty.call(newValue, key)) {
  16383. oldLength--;
  16384. delete oldValue[key];
  16385. }
  16386. }
  16387. }
  16388. }
  16389. return changeDetected;
  16390. }
  16391. function $watchCollectionAction() {
  16392. if (initRun) {
  16393. initRun = false;
  16394. listener(newValue, newValue, self);
  16395. } else {
  16396. listener(newValue, veryOldValue, self);
  16397. }
  16398. // make a copy for the next time a collection is changed
  16399. if (trackVeryOldValue) {
  16400. if (!isObject(newValue)) {
  16401. //primitive
  16402. veryOldValue = newValue;
  16403. } else if (isArrayLike(newValue)) {
  16404. veryOldValue = new Array(newValue.length);
  16405. for (var i = 0; i < newValue.length; i++) {
  16406. veryOldValue[i] = newValue[i];
  16407. }
  16408. } else { // if object
  16409. veryOldValue = {};
  16410. for (var key in newValue) {
  16411. if (hasOwnProperty.call(newValue, key)) {
  16412. veryOldValue[key] = newValue[key];
  16413. }
  16414. }
  16415. }
  16416. }
  16417. }
  16418. return this.$watch(changeDetector, $watchCollectionAction);
  16419. },
  16420. /**
  16421. * @ngdoc method
  16422. * @name $rootScope.Scope#$digest
  16423. * @kind function
  16424. *
  16425. * @description
  16426. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  16427. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  16428. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  16429. * until no more listeners are firing. This means that it is possible to get into an infinite
  16430. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  16431. * iterations exceeds 10.
  16432. *
  16433. * Usually, you don't call `$digest()` directly in
  16434. * {@link ng.directive:ngController controllers} or in
  16435. * {@link ng.$compileProvider#directive directives}.
  16436. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  16437. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  16438. *
  16439. * If you want to be notified whenever `$digest()` is called,
  16440. * you can register a `watchExpression` function with
  16441. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  16442. *
  16443. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  16444. *
  16445. * # Example
  16446. * ```js
  16447. var scope = ...;
  16448. scope.name = 'misko';
  16449. scope.counter = 0;
  16450. expect(scope.counter).toEqual(0);
  16451. scope.$watch('name', function(newValue, oldValue) {
  16452. scope.counter = scope.counter + 1;
  16453. });
  16454. expect(scope.counter).toEqual(0);
  16455. scope.$digest();
  16456. // the listener is always called during the first $digest loop after it was registered
  16457. expect(scope.counter).toEqual(1);
  16458. scope.$digest();
  16459. // but now it will not be called unless the value changes
  16460. expect(scope.counter).toEqual(1);
  16461. scope.name = 'adam';
  16462. scope.$digest();
  16463. expect(scope.counter).toEqual(2);
  16464. * ```
  16465. *
  16466. */
  16467. $digest: function() {
  16468. var watch, value, last, fn, get,
  16469. watchers,
  16470. dirty, ttl = TTL,
  16471. next, current, target = this,
  16472. watchLog = [],
  16473. logIdx, asyncTask;
  16474. beginPhase('$digest');
  16475. // Check for changes to browser url that happened in sync before the call to $digest
  16476. $browser.$$checkUrlChange();
  16477. if (this === $rootScope && applyAsyncId !== null) {
  16478. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  16479. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  16480. $browser.defer.cancel(applyAsyncId);
  16481. flushApplyAsync();
  16482. }
  16483. lastDirtyWatch = null;
  16484. do { // "while dirty" loop
  16485. dirty = false;
  16486. current = target;
  16487. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  16488. // be reentered recursively. Calling $digest from a function passed to $evalAsync would
  16489. // lead to a '$digest already in progress' error.
  16490. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  16491. try {
  16492. asyncTask = asyncQueue[asyncQueuePosition];
  16493. fn = asyncTask.fn;
  16494. fn(asyncTask.scope, asyncTask.locals);
  16495. } catch (e) {
  16496. $exceptionHandler(e);
  16497. }
  16498. lastDirtyWatch = null;
  16499. }
  16500. asyncQueue.length = 0;
  16501. traverseScopesLoop:
  16502. do { // "traverse the scopes" loop
  16503. if ((watchers = current.$$watchers)) {
  16504. // process our watches
  16505. watchers.$$digestWatchIndex = watchers.length;
  16506. while (watchers.$$digestWatchIndex--) {
  16507. try {
  16508. watch = watchers[watchers.$$digestWatchIndex];
  16509. // Most common watches are on primitives, in which case we can short
  16510. // circuit it with === operator, only when === fails do we use .equals
  16511. if (watch) {
  16512. get = watch.get;
  16513. if ((value = get(current)) !== (last = watch.last) &&
  16514. !(watch.eq
  16515. ? equals(value, last)
  16516. : (isNumberNaN(value) && isNumberNaN(last)))) {
  16517. dirty = true;
  16518. lastDirtyWatch = watch;
  16519. watch.last = watch.eq ? copy(value, null) : value;
  16520. fn = watch.fn;
  16521. fn(value, ((last === initWatchVal) ? value : last), current);
  16522. if (ttl < 5) {
  16523. logIdx = 4 - ttl;
  16524. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  16525. watchLog[logIdx].push({
  16526. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  16527. newVal: value,
  16528. oldVal: last
  16529. });
  16530. }
  16531. } else if (watch === lastDirtyWatch) {
  16532. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  16533. // have already been tested.
  16534. dirty = false;
  16535. break traverseScopesLoop;
  16536. }
  16537. }
  16538. } catch (e) {
  16539. $exceptionHandler(e);
  16540. }
  16541. }
  16542. }
  16543. // Insanity Warning: scope depth-first traversal
  16544. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16545. // this piece should be kept in sync with the traversal in $broadcast
  16546. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  16547. (current !== target && current.$$nextSibling)))) {
  16548. while (current !== target && !(next = current.$$nextSibling)) {
  16549. current = current.$parent;
  16550. }
  16551. }
  16552. } while ((current = next));
  16553. // `break traverseScopesLoop;` takes us to here
  16554. if ((dirty || asyncQueue.length) && !(ttl--)) {
  16555. clearPhase();
  16556. throw $rootScopeMinErr('infdig',
  16557. '{0} $digest() iterations reached. Aborting!\n' +
  16558. 'Watchers fired in the last 5 iterations: {1}',
  16559. TTL, watchLog);
  16560. }
  16561. } while (dirty || asyncQueue.length);
  16562. clearPhase();
  16563. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  16564. while (postDigestQueuePosition < postDigestQueue.length) {
  16565. try {
  16566. postDigestQueue[postDigestQueuePosition++]();
  16567. } catch (e) {
  16568. $exceptionHandler(e);
  16569. }
  16570. }
  16571. postDigestQueue.length = postDigestQueuePosition = 0;
  16572. // Check for changes to browser url that happened during the $digest
  16573. // (for which no event is fired; e.g. via `history.pushState()`)
  16574. $browser.$$checkUrlChange();
  16575. },
  16576. /**
  16577. * @ngdoc event
  16578. * @name $rootScope.Scope#$destroy
  16579. * @eventType broadcast on scope being destroyed
  16580. *
  16581. * @description
  16582. * Broadcasted when a scope and its children are being destroyed.
  16583. *
  16584. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16585. * clean up DOM bindings before an element is removed from the DOM.
  16586. */
  16587. /**
  16588. * @ngdoc method
  16589. * @name $rootScope.Scope#$destroy
  16590. * @kind function
  16591. *
  16592. * @description
  16593. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  16594. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  16595. * propagate to the current scope and its children. Removal also implies that the current
  16596. * scope is eligible for garbage collection.
  16597. *
  16598. * The `$destroy()` is usually used by directives such as
  16599. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  16600. * unrolling of the loop.
  16601. *
  16602. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  16603. * Application code can register a `$destroy` event handler that will give it a chance to
  16604. * perform any necessary cleanup.
  16605. *
  16606. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16607. * clean up DOM bindings before an element is removed from the DOM.
  16608. */
  16609. $destroy: function() {
  16610. // We can't destroy a scope that has been already destroyed.
  16611. if (this.$$destroyed) return;
  16612. var parent = this.$parent;
  16613. this.$broadcast('$destroy');
  16614. this.$$destroyed = true;
  16615. if (this === $rootScope) {
  16616. //Remove handlers attached to window when $rootScope is removed
  16617. $browser.$$applicationDestroyed();
  16618. }
  16619. incrementWatchersCount(this, -this.$$watchersCount);
  16620. for (var eventName in this.$$listenerCount) {
  16621. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  16622. }
  16623. // sever all the references to parent scopes (after this cleanup, the current scope should
  16624. // not be retained by any of our references and should be eligible for garbage collection)
  16625. if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
  16626. if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
  16627. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  16628. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  16629. // Disable listeners, watchers and apply/digest methods
  16630. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  16631. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  16632. this.$$listeners = {};
  16633. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  16634. this.$$nextSibling = null;
  16635. cleanUpScope(this);
  16636. },
  16637. /**
  16638. * @ngdoc method
  16639. * @name $rootScope.Scope#$eval
  16640. * @kind function
  16641. *
  16642. * @description
  16643. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  16644. * the expression are propagated (uncaught). This is useful when evaluating Angular
  16645. * expressions.
  16646. *
  16647. * # Example
  16648. * ```js
  16649. var scope = ng.$rootScope.Scope();
  16650. scope.a = 1;
  16651. scope.b = 2;
  16652. expect(scope.$eval('a+b')).toEqual(3);
  16653. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  16654. * ```
  16655. *
  16656. * @param {(string|function())=} expression An angular expression to be executed.
  16657. *
  16658. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16659. * - `function(scope)`: execute the function with the current `scope` parameter.
  16660. *
  16661. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16662. * @returns {*} The result of evaluating the expression.
  16663. */
  16664. $eval: function(expr, locals) {
  16665. return $parse(expr)(this, locals);
  16666. },
  16667. /**
  16668. * @ngdoc method
  16669. * @name $rootScope.Scope#$evalAsync
  16670. * @kind function
  16671. *
  16672. * @description
  16673. * Executes the expression on the current scope at a later point in time.
  16674. *
  16675. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  16676. * that:
  16677. *
  16678. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  16679. * rendering).
  16680. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  16681. * `expression` execution.
  16682. *
  16683. * Any exceptions from the execution of the expression are forwarded to the
  16684. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16685. *
  16686. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  16687. * will be scheduled. However, it is encouraged to always call code that changes the model
  16688. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  16689. *
  16690. * @param {(string|function())=} expression An angular expression to be executed.
  16691. *
  16692. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16693. * - `function(scope)`: execute the function with the current `scope` parameter.
  16694. *
  16695. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16696. */
  16697. $evalAsync: function(expr, locals) {
  16698. // if we are outside of an $digest loop and this is the first time we are scheduling async
  16699. // task also schedule async auto-flush
  16700. if (!$rootScope.$$phase && !asyncQueue.length) {
  16701. $browser.defer(function() {
  16702. if (asyncQueue.length) {
  16703. $rootScope.$digest();
  16704. }
  16705. });
  16706. }
  16707. asyncQueue.push({scope: this, fn: $parse(expr), locals: locals});
  16708. },
  16709. $$postDigest: function(fn) {
  16710. postDigestQueue.push(fn);
  16711. },
  16712. /**
  16713. * @ngdoc method
  16714. * @name $rootScope.Scope#$apply
  16715. * @kind function
  16716. *
  16717. * @description
  16718. * `$apply()` is used to execute an expression in angular from outside of the angular
  16719. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  16720. * Because we are calling into the angular framework we need to perform proper scope life
  16721. * cycle of {@link ng.$exceptionHandler exception handling},
  16722. * {@link ng.$rootScope.Scope#$digest executing watches}.
  16723. *
  16724. * ## Life cycle
  16725. *
  16726. * # Pseudo-Code of `$apply()`
  16727. * ```js
  16728. function $apply(expr) {
  16729. try {
  16730. return $eval(expr);
  16731. } catch (e) {
  16732. $exceptionHandler(e);
  16733. } finally {
  16734. $root.$digest();
  16735. }
  16736. }
  16737. * ```
  16738. *
  16739. *
  16740. * Scope's `$apply()` method transitions through the following stages:
  16741. *
  16742. * 1. The {@link guide/expression expression} is executed using the
  16743. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  16744. * 2. Any exceptions from the execution of the expression are forwarded to the
  16745. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16746. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  16747. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  16748. *
  16749. *
  16750. * @param {(string|function())=} exp An angular expression to be executed.
  16751. *
  16752. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16753. * - `function(scope)`: execute the function with current `scope` parameter.
  16754. *
  16755. * @returns {*} The result of evaluating the expression.
  16756. */
  16757. $apply: function(expr) {
  16758. try {
  16759. beginPhase('$apply');
  16760. try {
  16761. return this.$eval(expr);
  16762. } finally {
  16763. clearPhase();
  16764. }
  16765. } catch (e) {
  16766. $exceptionHandler(e);
  16767. } finally {
  16768. try {
  16769. $rootScope.$digest();
  16770. } catch (e) {
  16771. $exceptionHandler(e);
  16772. // eslint-disable-next-line no-unsafe-finally
  16773. throw e;
  16774. }
  16775. }
  16776. },
  16777. /**
  16778. * @ngdoc method
  16779. * @name $rootScope.Scope#$applyAsync
  16780. * @kind function
  16781. *
  16782. * @description
  16783. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  16784. * varies across browsers, but is typically around ~10 milliseconds.
  16785. *
  16786. * This can be used to queue up multiple expressions which need to be evaluated in the same
  16787. * digest.
  16788. *
  16789. * @param {(string|function())=} exp An angular expression to be executed.
  16790. *
  16791. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16792. * - `function(scope)`: execute the function with current `scope` parameter.
  16793. */
  16794. $applyAsync: function(expr) {
  16795. var scope = this;
  16796. if (expr) {
  16797. applyAsyncQueue.push($applyAsyncExpression);
  16798. }
  16799. expr = $parse(expr);
  16800. scheduleApplyAsync();
  16801. function $applyAsyncExpression() {
  16802. scope.$eval(expr);
  16803. }
  16804. },
  16805. /**
  16806. * @ngdoc method
  16807. * @name $rootScope.Scope#$on
  16808. * @kind function
  16809. *
  16810. * @description
  16811. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  16812. * discussion of event life cycle.
  16813. *
  16814. * The event listener function format is: `function(event, args...)`. The `event` object
  16815. * passed into the listener has the following attributes:
  16816. *
  16817. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  16818. * `$broadcast`-ed.
  16819. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  16820. * event propagates through the scope hierarchy, this property is set to null.
  16821. * - `name` - `{string}`: name of the event.
  16822. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  16823. * further event propagation (available only for events that were `$emit`-ed).
  16824. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  16825. * to true.
  16826. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  16827. *
  16828. * @param {string} name Event name to listen on.
  16829. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  16830. * @returns {function()} Returns a deregistration function for this listener.
  16831. */
  16832. $on: function(name, listener) {
  16833. var namedListeners = this.$$listeners[name];
  16834. if (!namedListeners) {
  16835. this.$$listeners[name] = namedListeners = [];
  16836. }
  16837. namedListeners.push(listener);
  16838. var current = this;
  16839. do {
  16840. if (!current.$$listenerCount[name]) {
  16841. current.$$listenerCount[name] = 0;
  16842. }
  16843. current.$$listenerCount[name]++;
  16844. } while ((current = current.$parent));
  16845. var self = this;
  16846. return function() {
  16847. var indexOfListener = namedListeners.indexOf(listener);
  16848. if (indexOfListener !== -1) {
  16849. namedListeners[indexOfListener] = null;
  16850. decrementListenerCount(self, 1, name);
  16851. }
  16852. };
  16853. },
  16854. /**
  16855. * @ngdoc method
  16856. * @name $rootScope.Scope#$emit
  16857. * @kind function
  16858. *
  16859. * @description
  16860. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  16861. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16862. *
  16863. * The event life cycle starts at the scope on which `$emit` was called. All
  16864. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16865. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  16866. * registered listeners along the way. The event will stop propagating if one of the listeners
  16867. * cancels it.
  16868. *
  16869. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16870. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16871. *
  16872. * @param {string} name Event name to emit.
  16873. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16874. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  16875. */
  16876. $emit: function(name, args) {
  16877. var empty = [],
  16878. namedListeners,
  16879. scope = this,
  16880. stopPropagation = false,
  16881. event = {
  16882. name: name,
  16883. targetScope: scope,
  16884. stopPropagation: function() {stopPropagation = true;},
  16885. preventDefault: function() {
  16886. event.defaultPrevented = true;
  16887. },
  16888. defaultPrevented: false
  16889. },
  16890. listenerArgs = concat([event], arguments, 1),
  16891. i, length;
  16892. do {
  16893. namedListeners = scope.$$listeners[name] || empty;
  16894. event.currentScope = scope;
  16895. for (i = 0, length = namedListeners.length; i < length; i++) {
  16896. // if listeners were deregistered, defragment the array
  16897. if (!namedListeners[i]) {
  16898. namedListeners.splice(i, 1);
  16899. i--;
  16900. length--;
  16901. continue;
  16902. }
  16903. try {
  16904. //allow all listeners attached to the current scope to run
  16905. namedListeners[i].apply(null, listenerArgs);
  16906. } catch (e) {
  16907. $exceptionHandler(e);
  16908. }
  16909. }
  16910. //if any listener on the current scope stops propagation, prevent bubbling
  16911. if (stopPropagation) {
  16912. event.currentScope = null;
  16913. return event;
  16914. }
  16915. //traverse upwards
  16916. scope = scope.$parent;
  16917. } while (scope);
  16918. event.currentScope = null;
  16919. return event;
  16920. },
  16921. /**
  16922. * @ngdoc method
  16923. * @name $rootScope.Scope#$broadcast
  16924. * @kind function
  16925. *
  16926. * @description
  16927. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  16928. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16929. *
  16930. * The event life cycle starts at the scope on which `$broadcast` was called. All
  16931. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16932. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  16933. * scope and calls all registered listeners along the way. The event cannot be canceled.
  16934. *
  16935. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16936. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16937. *
  16938. * @param {string} name Event name to broadcast.
  16939. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16940. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  16941. */
  16942. $broadcast: function(name, args) {
  16943. var target = this,
  16944. current = target,
  16945. next = target,
  16946. event = {
  16947. name: name,
  16948. targetScope: target,
  16949. preventDefault: function() {
  16950. event.defaultPrevented = true;
  16951. },
  16952. defaultPrevented: false
  16953. };
  16954. if (!target.$$listenerCount[name]) return event;
  16955. var listenerArgs = concat([event], arguments, 1),
  16956. listeners, i, length;
  16957. //down while you can, then up and next sibling or up and next sibling until back at root
  16958. while ((current = next)) {
  16959. event.currentScope = current;
  16960. listeners = current.$$listeners[name] || [];
  16961. for (i = 0, length = listeners.length; i < length; i++) {
  16962. // if listeners were deregistered, defragment the array
  16963. if (!listeners[i]) {
  16964. listeners.splice(i, 1);
  16965. i--;
  16966. length--;
  16967. continue;
  16968. }
  16969. try {
  16970. listeners[i].apply(null, listenerArgs);
  16971. } catch (e) {
  16972. $exceptionHandler(e);
  16973. }
  16974. }
  16975. // Insanity Warning: scope depth-first traversal
  16976. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16977. // this piece should be kept in sync with the traversal in $digest
  16978. // (though it differs due to having the extra check for $$listenerCount)
  16979. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  16980. (current !== target && current.$$nextSibling)))) {
  16981. while (current !== target && !(next = current.$$nextSibling)) {
  16982. current = current.$parent;
  16983. }
  16984. }
  16985. }
  16986. event.currentScope = null;
  16987. return event;
  16988. }
  16989. };
  16990. var $rootScope = new Scope();
  16991. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  16992. var asyncQueue = $rootScope.$$asyncQueue = [];
  16993. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  16994. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  16995. var postDigestQueuePosition = 0;
  16996. return $rootScope;
  16997. function beginPhase(phase) {
  16998. if ($rootScope.$$phase) {
  16999. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  17000. }
  17001. $rootScope.$$phase = phase;
  17002. }
  17003. function clearPhase() {
  17004. $rootScope.$$phase = null;
  17005. }
  17006. function incrementWatchersCount(current, count) {
  17007. do {
  17008. current.$$watchersCount += count;
  17009. } while ((current = current.$parent));
  17010. }
  17011. function decrementListenerCount(current, count, name) {
  17012. do {
  17013. current.$$listenerCount[name] -= count;
  17014. if (current.$$listenerCount[name] === 0) {
  17015. delete current.$$listenerCount[name];
  17016. }
  17017. } while ((current = current.$parent));
  17018. }
  17019. /**
  17020. * function used as an initial value for watchers.
  17021. * because it's unique we can easily tell it apart from other values
  17022. */
  17023. function initWatchVal() {}
  17024. function flushApplyAsync() {
  17025. while (applyAsyncQueue.length) {
  17026. try {
  17027. applyAsyncQueue.shift()();
  17028. } catch (e) {
  17029. $exceptionHandler(e);
  17030. }
  17031. }
  17032. applyAsyncId = null;
  17033. }
  17034. function scheduleApplyAsync() {
  17035. if (applyAsyncId === null) {
  17036. applyAsyncId = $browser.defer(function() {
  17037. $rootScope.$apply(flushApplyAsync);
  17038. });
  17039. }
  17040. }
  17041. }];
  17042. }
  17043. /**
  17044. * @ngdoc service
  17045. * @name $rootElement
  17046. *
  17047. * @description
  17048. * The root element of Angular application. This is either the element where {@link
  17049. * ng.directive:ngApp ngApp} was declared or the element passed into
  17050. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  17051. * location where the application's {@link auto.$injector $injector} service gets
  17052. * published, and can be retrieved using `$rootElement.injector()`.
  17053. */
  17054. // the implementation is in angular.bootstrap
  17055. /**
  17056. * @this
  17057. * @description
  17058. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  17059. */
  17060. function $$SanitizeUriProvider() {
  17061. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  17062. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  17063. /**
  17064. * @description
  17065. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  17066. * urls during a[href] sanitization.
  17067. *
  17068. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  17069. *
  17070. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  17071. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  17072. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  17073. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  17074. *
  17075. * @param {RegExp=} regexp New regexp to whitelist urls with.
  17076. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  17077. * chaining otherwise.
  17078. */
  17079. this.aHrefSanitizationWhitelist = function(regexp) {
  17080. if (isDefined(regexp)) {
  17081. aHrefSanitizationWhitelist = regexp;
  17082. return this;
  17083. }
  17084. return aHrefSanitizationWhitelist;
  17085. };
  17086. /**
  17087. * @description
  17088. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  17089. * urls during img[src] sanitization.
  17090. *
  17091. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  17092. *
  17093. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  17094. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  17095. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  17096. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  17097. *
  17098. * @param {RegExp=} regexp New regexp to whitelist urls with.
  17099. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  17100. * chaining otherwise.
  17101. */
  17102. this.imgSrcSanitizationWhitelist = function(regexp) {
  17103. if (isDefined(regexp)) {
  17104. imgSrcSanitizationWhitelist = regexp;
  17105. return this;
  17106. }
  17107. return imgSrcSanitizationWhitelist;
  17108. };
  17109. this.$get = function() {
  17110. return function sanitizeUri(uri, isImage) {
  17111. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  17112. var normalizedVal;
  17113. normalizedVal = urlResolve(uri).href;
  17114. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  17115. return 'unsafe:' + normalizedVal;
  17116. }
  17117. return uri;
  17118. };
  17119. };
  17120. }
  17121. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  17122. * Any commits to this file should be reviewed with security in mind. *
  17123. * Changes to this file can potentially create security vulnerabilities. *
  17124. * An approval from 2 Core members with history of modifying *
  17125. * this file is required. *
  17126. * *
  17127. * Does the change somehow allow for arbitrary javascript to be executed? *
  17128. * Or allows for someone to change the prototype of built-in objects? *
  17129. * Or gives undesired access to variables likes document or window? *
  17130. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  17131. /* exported $SceProvider, $SceDelegateProvider */
  17132. var $sceMinErr = minErr('$sce');
  17133. var SCE_CONTEXTS = {
  17134. // HTML is used when there's HTML rendered (e.g. ng-bind-html, iframe srcdoc binding).
  17135. HTML: 'html',
  17136. // Style statements or stylesheets. Currently unused in AngularJS.
  17137. CSS: 'css',
  17138. // An URL used in a context where it does not refer to a resource that loads code. Currently
  17139. // unused in AngularJS.
  17140. URL: 'url',
  17141. // RESOURCE_URL is a subtype of URL used where the referred-to resource could be interpreted as
  17142. // code. (e.g. ng-include, script src binding, templateUrl)
  17143. RESOURCE_URL: 'resourceUrl',
  17144. // Script. Currently unused in AngularJS.
  17145. JS: 'js'
  17146. };
  17147. // Helper functions follow.
  17148. var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;
  17149. function snakeToCamel(name) {
  17150. return name
  17151. .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);
  17152. }
  17153. function adjustMatcher(matcher) {
  17154. if (matcher === 'self') {
  17155. return matcher;
  17156. } else if (isString(matcher)) {
  17157. // Strings match exactly except for 2 wildcards - '*' and '**'.
  17158. // '*' matches any character except those from the set ':/.?&'.
  17159. // '**' matches any character (like .* in a RegExp).
  17160. // More than 2 *'s raises an error as it's ill defined.
  17161. if (matcher.indexOf('***') > -1) {
  17162. throw $sceMinErr('iwcard',
  17163. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  17164. }
  17165. matcher = escapeForRegexp(matcher).
  17166. replace(/\\\*\\\*/g, '.*').
  17167. replace(/\\\*/g, '[^:/.?&;]*');
  17168. return new RegExp('^' + matcher + '$');
  17169. } else if (isRegExp(matcher)) {
  17170. // The only other type of matcher allowed is a Regexp.
  17171. // Match entire URL / disallow partial matches.
  17172. // Flags are reset (i.e. no global, ignoreCase or multiline)
  17173. return new RegExp('^' + matcher.source + '$');
  17174. } else {
  17175. throw $sceMinErr('imatcher',
  17176. 'Matchers may only be "self", string patterns or RegExp objects');
  17177. }
  17178. }
  17179. function adjustMatchers(matchers) {
  17180. var adjustedMatchers = [];
  17181. if (isDefined(matchers)) {
  17182. forEach(matchers, function(matcher) {
  17183. adjustedMatchers.push(adjustMatcher(matcher));
  17184. });
  17185. }
  17186. return adjustedMatchers;
  17187. }
  17188. /**
  17189. * @ngdoc service
  17190. * @name $sceDelegate
  17191. * @kind function
  17192. *
  17193. * @description
  17194. *
  17195. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  17196. * Contextual Escaping (SCE)} services to AngularJS.
  17197. *
  17198. * For an overview of this service and the functionnality it provides in AngularJS, see the main
  17199. * page for {@link ng.$sce SCE}. The current page is targeted for developers who need to alter how
  17200. * SCE works in their application, which shouldn't be needed in most cases.
  17201. *
  17202. * <div class="alert alert-danger">
  17203. * AngularJS strongly relies on contextual escaping for the security of bindings: disabling or
  17204. * modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners,
  17205. * changes to this service will also influence users, so be extra careful and document your changes.
  17206. * </div>
  17207. *
  17208. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  17209. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  17210. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  17211. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  17212. * work because `$sce` delegates to `$sceDelegate` for these operations.
  17213. *
  17214. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  17215. *
  17216. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  17217. * can override it completely to change the behavior of `$sce`, the common case would
  17218. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  17219. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  17220. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  17221. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  17222. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  17223. */
  17224. /**
  17225. * @ngdoc provider
  17226. * @name $sceDelegateProvider
  17227. * @this
  17228. *
  17229. * @description
  17230. *
  17231. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  17232. * $sceDelegate service}, used as a delegate for {@link ng.$sce Strict Contextual Escaping (SCE)}.
  17233. *
  17234. * The `$sceDelegateProvider` allows one to get/set the whitelists and blacklists used to ensure
  17235. * that the URLs used for sourcing AngularJS templates and other script-running URLs are safe (all
  17236. * places that use the `$sce.RESOURCE_URL` context). See
  17237. * {@link ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist}
  17238. * and
  17239. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist},
  17240. *
  17241. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  17242. * Strict Contextual Escaping (SCE)}.
  17243. *
  17244. * **Example**: Consider the following case. <a name="example"></a>
  17245. *
  17246. * - your app is hosted at url `http://myapp.example.com/`
  17247. * - but some of your templates are hosted on other domains you control such as
  17248. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  17249. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  17250. *
  17251. * Here is what a secure configuration for this scenario might look like:
  17252. *
  17253. * ```
  17254. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  17255. * $sceDelegateProvider.resourceUrlWhitelist([
  17256. * // Allow same origin resource loads.
  17257. * 'self',
  17258. * // Allow loading from our assets domain. Notice the difference between * and **.
  17259. * 'http://srv*.assets.example.com/**'
  17260. * ]);
  17261. *
  17262. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  17263. * $sceDelegateProvider.resourceUrlBlacklist([
  17264. * 'http://myapp.example.com/clickThru**'
  17265. * ]);
  17266. * });
  17267. * ```
  17268. * Note that an empty whitelist will block every resource URL from being loaded, and will require
  17269. * you to manually mark each one as trusted with `$sce.trustAsResourceUrl`. However, templates
  17270. * requested by {@link ng.$templateRequest $templateRequest} that are present in
  17271. * {@link ng.$templateCache $templateCache} will not go through this check. If you have a mechanism
  17272. * to populate your templates in that cache at config time, then it is a good idea to remove 'self'
  17273. * from that whitelist. This helps to mitigate the security impact of certain types of issues, like
  17274. * for instance attacker-controlled `ng-includes`.
  17275. */
  17276. function $SceDelegateProvider() {
  17277. this.SCE_CONTEXTS = SCE_CONTEXTS;
  17278. // Resource URLs can also be trusted by policy.
  17279. var resourceUrlWhitelist = ['self'],
  17280. resourceUrlBlacklist = [];
  17281. /**
  17282. * @ngdoc method
  17283. * @name $sceDelegateProvider#resourceUrlWhitelist
  17284. * @kind function
  17285. *
  17286. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  17287. * provided. This must be an array or null. A snapshot of this array is used so further
  17288. * changes to the array are ignored.
  17289. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  17290. * allowed in this array.
  17291. *
  17292. * @return {Array} The currently set whitelist array.
  17293. *
  17294. * @description
  17295. * Sets/Gets the whitelist of trusted resource URLs.
  17296. *
  17297. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  17298. * same origin resource requests.
  17299. *
  17300. * <div class="alert alert-warning">
  17301. * **Note:** the default whitelist of 'self' is not recommended if your app shares its origin
  17302. * with other apps! It is a good idea to limit it to only your application's directory.
  17303. * </div>
  17304. */
  17305. this.resourceUrlWhitelist = function(value) {
  17306. if (arguments.length) {
  17307. resourceUrlWhitelist = adjustMatchers(value);
  17308. }
  17309. return resourceUrlWhitelist;
  17310. };
  17311. /**
  17312. * @ngdoc method
  17313. * @name $sceDelegateProvider#resourceUrlBlacklist
  17314. * @kind function
  17315. *
  17316. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  17317. * provided. This must be an array or null. A snapshot of this array is used so further
  17318. * changes to the array are ignored.</p><p>
  17319. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  17320. * allowed in this array.</p><p>
  17321. * The typical usage for the blacklist is to **block
  17322. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  17323. * these would otherwise be trusted but actually return content from the redirected domain.
  17324. * </p><p>
  17325. * Finally, **the blacklist overrides the whitelist** and has the final say.
  17326. *
  17327. * @return {Array} The currently set blacklist array.
  17328. *
  17329. * @description
  17330. * Sets/Gets the blacklist of trusted resource URLs.
  17331. *
  17332. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  17333. * is no blacklist.)
  17334. */
  17335. this.resourceUrlBlacklist = function(value) {
  17336. if (arguments.length) {
  17337. resourceUrlBlacklist = adjustMatchers(value);
  17338. }
  17339. return resourceUrlBlacklist;
  17340. };
  17341. this.$get = ['$injector', function($injector) {
  17342. var htmlSanitizer = function htmlSanitizer(html) {
  17343. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17344. };
  17345. if ($injector.has('$sanitize')) {
  17346. htmlSanitizer = $injector.get('$sanitize');
  17347. }
  17348. function matchUrl(matcher, parsedUrl) {
  17349. if (matcher === 'self') {
  17350. return urlIsSameOrigin(parsedUrl);
  17351. } else {
  17352. // definitely a regex. See adjustMatchers()
  17353. return !!matcher.exec(parsedUrl.href);
  17354. }
  17355. }
  17356. function isResourceUrlAllowedByPolicy(url) {
  17357. var parsedUrl = urlResolve(url.toString());
  17358. var i, n, allowed = false;
  17359. // Ensure that at least one item from the whitelist allows this url.
  17360. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  17361. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  17362. allowed = true;
  17363. break;
  17364. }
  17365. }
  17366. if (allowed) {
  17367. // Ensure that no item from the blacklist blocked this url.
  17368. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  17369. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  17370. allowed = false;
  17371. break;
  17372. }
  17373. }
  17374. }
  17375. return allowed;
  17376. }
  17377. function generateHolderType(Base) {
  17378. var holderType = function TrustedValueHolderType(trustedValue) {
  17379. this.$$unwrapTrustedValue = function() {
  17380. return trustedValue;
  17381. };
  17382. };
  17383. if (Base) {
  17384. holderType.prototype = new Base();
  17385. }
  17386. holderType.prototype.valueOf = function sceValueOf() {
  17387. return this.$$unwrapTrustedValue();
  17388. };
  17389. holderType.prototype.toString = function sceToString() {
  17390. return this.$$unwrapTrustedValue().toString();
  17391. };
  17392. return holderType;
  17393. }
  17394. var trustedValueHolderBase = generateHolderType(),
  17395. byType = {};
  17396. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  17397. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  17398. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  17399. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  17400. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  17401. /**
  17402. * @ngdoc method
  17403. * @name $sceDelegate#trustAs
  17404. *
  17405. * @description
  17406. * Returns a trusted representation of the parameter for the specified context. This trusted
  17407. * object will later on be used as-is, without any security check, by bindings or directives
  17408. * that require this security context.
  17409. * For instance, marking a string as trusted for the `$sce.HTML` context will entirely bypass
  17410. * the potential `$sanitize` call in corresponding `$sce.HTML` bindings or directives, such as
  17411. * `ng-bind-html`. Note that in most cases you won't need to call this function: if you have the
  17412. * sanitizer loaded, passing the value itself will render all the HTML that does not pose a
  17413. * security risk.
  17414. *
  17415. * See {@link ng.$sceDelegate#getTrusted getTrusted} for the function that will consume those
  17416. * trusted values, and {@link ng.$sce $sce} for general documentation about strict contextual
  17417. * escaping.
  17418. *
  17419. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  17420. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  17421. *
  17422. * @param {*} value The value that should be considered trusted.
  17423. * @return {*} A trusted representation of value, that can be used in the given context.
  17424. */
  17425. function trustAs(type, trustedValue) {
  17426. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17427. if (!Constructor) {
  17428. throw $sceMinErr('icontext',
  17429. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  17430. type, trustedValue);
  17431. }
  17432. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  17433. return trustedValue;
  17434. }
  17435. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  17436. // mutable objects, we ensure here that the value passed in is actually a string.
  17437. if (typeof trustedValue !== 'string') {
  17438. throw $sceMinErr('itype',
  17439. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  17440. type);
  17441. }
  17442. return new Constructor(trustedValue);
  17443. }
  17444. /**
  17445. * @ngdoc method
  17446. * @name $sceDelegate#valueOf
  17447. *
  17448. * @description
  17449. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  17450. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  17451. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  17452. *
  17453. * If the passed parameter is not a value that had been returned by {@link
  17454. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, it must be returned as-is.
  17455. *
  17456. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  17457. * call or anything else.
  17458. * @return {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  17459. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  17460. * `value` unchanged.
  17461. */
  17462. function valueOf(maybeTrusted) {
  17463. if (maybeTrusted instanceof trustedValueHolderBase) {
  17464. return maybeTrusted.$$unwrapTrustedValue();
  17465. } else {
  17466. return maybeTrusted;
  17467. }
  17468. }
  17469. /**
  17470. * @ngdoc method
  17471. * @name $sceDelegate#getTrusted
  17472. *
  17473. * @description
  17474. * Takes any input, and either returns a value that's safe to use in the specified context, or
  17475. * throws an exception.
  17476. *
  17477. * In practice, there are several cases. When given a string, this function runs checks
  17478. * and sanitization to make it safe without prior assumptions. When given the result of a {@link
  17479. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call, it returns the originally supplied
  17480. * value if that value's context is valid for this call's context. Finally, this function can
  17481. * also throw when there is no way to turn `maybeTrusted` in a safe value (e.g., no sanitization
  17482. * is available or possible.)
  17483. *
  17484. * @param {string} type The context in which this value is to be used (such as `$sce.HTML`).
  17485. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  17486. * `$sceDelegate.trustAs`} call, or anything else (which will not be considered trusted.)
  17487. * @return {*} A version of the value that's safe to use in the given context, or throws an
  17488. * exception if this is impossible.
  17489. */
  17490. function getTrusted(type, maybeTrusted) {
  17491. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  17492. return maybeTrusted;
  17493. }
  17494. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17495. // If maybeTrusted is a trusted class instance or subclass instance, then unwrap and return
  17496. // as-is.
  17497. if (constructor && maybeTrusted instanceof constructor) {
  17498. return maybeTrusted.$$unwrapTrustedValue();
  17499. }
  17500. // Otherwise, if we get here, then we may either make it safe, or throw an exception. This
  17501. // depends on the context: some are sanitizatible (HTML), some use whitelists (RESOURCE_URL),
  17502. // some are impossible to do (JS). This step isn't implemented for CSS and URL, as AngularJS
  17503. // has no corresponding sinks.
  17504. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  17505. // RESOURCE_URL uses a whitelist.
  17506. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  17507. return maybeTrusted;
  17508. } else {
  17509. throw $sceMinErr('insecurl',
  17510. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  17511. maybeTrusted.toString());
  17512. }
  17513. } else if (type === SCE_CONTEXTS.HTML) {
  17514. // htmlSanitizer throws its own error when no sanitizer is available.
  17515. return htmlSanitizer(maybeTrusted);
  17516. }
  17517. // Default error when the $sce service has no way to make the input safe.
  17518. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17519. }
  17520. return { trustAs: trustAs,
  17521. getTrusted: getTrusted,
  17522. valueOf: valueOf };
  17523. }];
  17524. }
  17525. /**
  17526. * @ngdoc provider
  17527. * @name $sceProvider
  17528. * @this
  17529. *
  17530. * @description
  17531. *
  17532. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  17533. * - enable/disable Strict Contextual Escaping (SCE) in a module
  17534. * - override the default implementation with a custom delegate
  17535. *
  17536. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  17537. */
  17538. /**
  17539. * @ngdoc service
  17540. * @name $sce
  17541. * @kind function
  17542. *
  17543. * @description
  17544. *
  17545. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  17546. *
  17547. * # Strict Contextual Escaping
  17548. *
  17549. * Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render
  17550. * trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and
  17551. * (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  17552. *
  17553. * ## Overview
  17554. *
  17555. * To systematically block XSS security bugs, AngularJS treats all values as untrusted by default in
  17556. * HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically
  17557. * run security checks on them (sanitizations, whitelists, depending on context), or throw when it
  17558. * cannot guarantee the security of the result. That behavior depends strongly on contexts: HTML
  17559. * can be sanitized, but template URLs cannot, for instance.
  17560. *
  17561. * To illustrate this, consider the `ng-bind-html` directive. It renders its value directly as HTML:
  17562. * we call that the *context*. When given an untrusted input, AngularJS will attempt to sanitize it
  17563. * before rendering if a sanitizer is available, and throw otherwise. To bypass sanitization and
  17564. * render the input as-is, you will need to mark it as trusted for that context before attempting
  17565. * to bind it.
  17566. *
  17567. * As of version 1.2, AngularJS ships with SCE enabled by default.
  17568. *
  17569. * ## In practice
  17570. *
  17571. * Here's an example of a binding in a privileged context:
  17572. *
  17573. * ```
  17574. * <input ng-model="userHtml" aria-label="User input">
  17575. * <div ng-bind-html="userHtml"></div>
  17576. * ```
  17577. *
  17578. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  17579. * disabled, this application allows the user to render arbitrary HTML into the DIV, which would
  17580. * be an XSS security bug. In a more realistic example, one may be rendering user comments, blog
  17581. * articles, etc. via bindings. (HTML is just one example of a context where rendering user
  17582. * controlled input creates security vulnerabilities.)
  17583. *
  17584. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  17585. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  17586. *
  17587. * How would you ensure that every place that used these types of bindings was bound to a value that
  17588. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  17589. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  17590. * properties/fields and forgot to update the binding to the sanitized value?
  17591. *
  17592. * To be secure by default, AngularJS makes sure bindings go through that sanitization, or
  17593. * any similar validation process, unless there's a good reason to trust the given value in this
  17594. * context. That trust is formalized with a function call. This means that as a developer, you
  17595. * can assume all untrusted bindings are safe. Then, to audit your code for binding security issues,
  17596. * you just need to ensure the values you mark as trusted indeed are safe - because they were
  17597. * received from your server, sanitized by your library, etc. You can organize your codebase to
  17598. * help with this - perhaps allowing only the files in a specific directory to do this.
  17599. * Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then
  17600. * becomes a more manageable task.
  17601. *
  17602. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  17603. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  17604. * build the trusted versions of your values.
  17605. *
  17606. * ## How does it work?
  17607. *
  17608. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  17609. * $sce.getTrusted(context, value)} rather than to the value directly. Think of this function as
  17610. * a way to enforce the required security context in your data sink. Directives use {@link
  17611. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs
  17612. * the {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. Also,
  17613. * when binding without directives, AngularJS will understand the context of your bindings
  17614. * automatically.
  17615. *
  17616. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  17617. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  17618. * simplified):
  17619. *
  17620. * ```
  17621. * var ngBindHtmlDirective = ['$sce', function($sce) {
  17622. * return function(scope, element, attr) {
  17623. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  17624. * element.html(value || '');
  17625. * });
  17626. * };
  17627. * }];
  17628. * ```
  17629. *
  17630. * ## Impact on loading templates
  17631. *
  17632. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  17633. * `templateUrl`'s specified by {@link guide/directive directives}.
  17634. *
  17635. * By default, Angular only loads templates from the same domain and protocol as the application
  17636. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  17637. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  17638. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  17639. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  17640. *
  17641. * *Please note*:
  17642. * The browser's
  17643. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  17644. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  17645. * policy apply in addition to this and may further restrict whether the template is successfully
  17646. * loaded. This means that without the right CORS policy, loading templates from a different domain
  17647. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  17648. * browsers.
  17649. *
  17650. * ## This feels like too much overhead
  17651. *
  17652. * It's important to remember that SCE only applies to interpolation expressions.
  17653. *
  17654. * If your expressions are constant literals, they're automatically trusted and you don't need to
  17655. * call `$sce.trustAs` on them (e.g.
  17656. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works. The `$sceDelegate` will
  17657. * also use the `$sanitize` service if it is available when binding untrusted values to
  17658. * `$sce.HTML` context. AngularJS provides an implementation in `angular-sanitize.js`, and if you
  17659. * wish to use it, you will also need to depend on the {@link ngSanitize `ngSanitize`} module in
  17660. * your application.
  17661. *
  17662. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  17663. * templates in `ng-include` from your application's domain without having to even know about SCE.
  17664. * It blocks loading templates from other domains or loading templates over http from an https
  17665. * served document. You can change these by setting your own custom {@link
  17666. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  17667. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  17668. *
  17669. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  17670. * application that's secure and can be audited to verify that with much more ease than bolting
  17671. * security onto an application later.
  17672. *
  17673. * <a name="contexts"></a>
  17674. * ## What trusted context types are supported?
  17675. *
  17676. * | Context | Notes |
  17677. * |---------------------|----------------|
  17678. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered, and the {@link ngSanitize.$sanitize $sanitize} service is available (implemented by the {@link ngSanitize ngSanitize} module) this will sanitize the value instead of throwing an error. |
  17679. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently, no bindings require this context. Feel free to use it in your own directives. |
  17680. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=`, `<img src=`, and some others sanitize their urls and don't constitute an SCE context.) |
  17681. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG`, `VIDEO`, `AUDIO`, `SOURCE`, and `TRACK` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does (it's not just the URL that matters, but also what is at the end of it), and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  17682. * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently, no bindings require this context. Feel free to use it in your own directives. |
  17683. *
  17684. *
  17685. * Be aware that `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  17686. * through {@link ng.$sce#getTrusted $sce.getTrusted}. There's no CSS-, URL-, or JS-context bindings
  17687. * in AngularJS currently, so their corresponding `$sce.trustAs` functions aren't useful yet. This
  17688. * might evolve.
  17689. *
  17690. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  17691. *
  17692. * Each element in these arrays must be one of the following:
  17693. *
  17694. * - **'self'**
  17695. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  17696. * domain** as the application document using the **same protocol**.
  17697. * - **String** (except the special value `'self'`)
  17698. * - The string is matched against the full *normalized / absolute URL* of the resource
  17699. * being tested (substring matches are not good enough.)
  17700. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  17701. * match themselves.
  17702. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  17703. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  17704. * in a whitelist.
  17705. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  17706. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  17707. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  17708. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  17709. * http://foo.example.com/templates/**).
  17710. * - **RegExp** (*see caveat below*)
  17711. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  17712. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  17713. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  17714. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  17715. * small number of cases. A `.` character in the regex used when matching the scheme or a
  17716. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  17717. * is highly recommended to use the string patterns and only fall back to regular expressions
  17718. * as a last resort.
  17719. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  17720. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  17721. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  17722. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  17723. * - If you are generating your JavaScript from some other templating engine (not
  17724. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  17725. * remember to escape your regular expression (and be aware that you might need more than
  17726. * one level of escaping depending on your templating engine and the way you interpolated
  17727. * the value.) Do make use of your platform's escaping mechanism as it might be good
  17728. * enough before coding your own. E.g. Ruby has
  17729. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  17730. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  17731. * Javascript lacks a similar built in function for escaping. Take a look at Google
  17732. * Closure library's [goog.string.regExpEscape(s)](
  17733. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  17734. *
  17735. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  17736. *
  17737. * ## Show me an example using SCE.
  17738. *
  17739. * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
  17740. * <file name="index.html">
  17741. * <div ng-controller="AppController as myCtrl">
  17742. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  17743. * <b>User comments</b><br>
  17744. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  17745. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  17746. * exploit.
  17747. * <div class="well">
  17748. * <div ng-repeat="userComment in myCtrl.userComments">
  17749. * <b>{{userComment.name}}</b>:
  17750. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  17751. * <br>
  17752. * </div>
  17753. * </div>
  17754. * </div>
  17755. * </file>
  17756. *
  17757. * <file name="script.js">
  17758. * angular.module('mySceApp', ['ngSanitize'])
  17759. * .controller('AppController', ['$http', '$templateCache', '$sce',
  17760. * function AppController($http, $templateCache, $sce) {
  17761. * var self = this;
  17762. * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {
  17763. * self.userComments = response.data;
  17764. * });
  17765. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  17766. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17767. * 'sanitization.&quot;">Hover over this text.</span>');
  17768. * }]);
  17769. * </file>
  17770. *
  17771. * <file name="test_data.json">
  17772. * [
  17773. * { "name": "Alice",
  17774. * "htmlComment":
  17775. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  17776. * },
  17777. * { "name": "Bob",
  17778. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  17779. * }
  17780. * ]
  17781. * </file>
  17782. *
  17783. * <file name="protractor.js" type="protractor">
  17784. * describe('SCE doc demo', function() {
  17785. * it('should sanitize untrusted values', function() {
  17786. * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
  17787. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  17788. * });
  17789. *
  17790. * it('should NOT sanitize explicitly trusted values', function() {
  17791. * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
  17792. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17793. * 'sanitization.&quot;">Hover over this text.</span>');
  17794. * });
  17795. * });
  17796. * </file>
  17797. * </example>
  17798. *
  17799. *
  17800. *
  17801. * ## Can I disable SCE completely?
  17802. *
  17803. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  17804. * for little coding overhead. It will be much harder to take an SCE disabled application and
  17805. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  17806. * for cases where you have a lot of existing code that was written before SCE was introduced and
  17807. * you're migrating them a module at a time. Also do note that this is an app-wide setting, so if
  17808. * you are writing a library, you will cause security bugs applications using it.
  17809. *
  17810. * That said, here's how you can completely disable SCE:
  17811. *
  17812. * ```
  17813. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  17814. * // Completely disable SCE. For demonstration purposes only!
  17815. * // Do not use in new projects or libraries.
  17816. * $sceProvider.enabled(false);
  17817. * });
  17818. * ```
  17819. *
  17820. */
  17821. function $SceProvider() {
  17822. var enabled = true;
  17823. /**
  17824. * @ngdoc method
  17825. * @name $sceProvider#enabled
  17826. * @kind function
  17827. *
  17828. * @param {boolean=} value If provided, then enables/disables SCE application-wide.
  17829. * @return {boolean} True if SCE is enabled, false otherwise.
  17830. *
  17831. * @description
  17832. * Enables/disables SCE and returns the current value.
  17833. */
  17834. this.enabled = function(value) {
  17835. if (arguments.length) {
  17836. enabled = !!value;
  17837. }
  17838. return enabled;
  17839. };
  17840. /* Design notes on the default implementation for SCE.
  17841. *
  17842. * The API contract for the SCE delegate
  17843. * -------------------------------------
  17844. * The SCE delegate object must provide the following 3 methods:
  17845. *
  17846. * - trustAs(contextEnum, value)
  17847. * This method is used to tell the SCE service that the provided value is OK to use in the
  17848. * contexts specified by contextEnum. It must return an object that will be accepted by
  17849. * getTrusted() for a compatible contextEnum and return this value.
  17850. *
  17851. * - valueOf(value)
  17852. * For values that were not produced by trustAs(), return them as is. For values that were
  17853. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  17854. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  17855. * such a value.
  17856. *
  17857. * - getTrusted(contextEnum, value)
  17858. * This function should return the a value that is safe to use in the context specified by
  17859. * contextEnum or throw and exception otherwise.
  17860. *
  17861. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  17862. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  17863. * instance, an implementation could maintain a registry of all trusted objects by context. In
  17864. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  17865. * return the same object passed in if it was found in the registry under a compatible context or
  17866. * throw an exception otherwise. An implementation might only wrap values some of the time based
  17867. * on some criteria. getTrusted() might return a value and not throw an exception for special
  17868. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  17869. *
  17870. *
  17871. * A note on the inheritance model for SCE contexts
  17872. * ------------------------------------------------
  17873. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  17874. * is purely an implementation details.
  17875. *
  17876. * The contract is simply this:
  17877. *
  17878. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  17879. * will also succeed.
  17880. *
  17881. * Inheritance happens to capture this in a natural way. In some future, we may not use
  17882. * inheritance anymore. That is OK because no code outside of sce.js and sceSpecs.js would need to
  17883. * be aware of this detail.
  17884. */
  17885. this.$get = ['$parse', '$sceDelegate', function(
  17886. $parse, $sceDelegate) {
  17887. // Support: IE 9-11 only
  17888. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  17889. // the "expression(javascript expression)" syntax which is insecure.
  17890. if (enabled && msie < 8) {
  17891. throw $sceMinErr('iequirks',
  17892. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  17893. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  17894. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  17895. }
  17896. var sce = shallowCopy(SCE_CONTEXTS);
  17897. /**
  17898. * @ngdoc method
  17899. * @name $sce#isEnabled
  17900. * @kind function
  17901. *
  17902. * @return {Boolean} True if SCE is enabled, false otherwise. If you want to set the value, you
  17903. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  17904. *
  17905. * @description
  17906. * Returns a boolean indicating if SCE is enabled.
  17907. */
  17908. sce.isEnabled = function() {
  17909. return enabled;
  17910. };
  17911. sce.trustAs = $sceDelegate.trustAs;
  17912. sce.getTrusted = $sceDelegate.getTrusted;
  17913. sce.valueOf = $sceDelegate.valueOf;
  17914. if (!enabled) {
  17915. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  17916. sce.valueOf = identity;
  17917. }
  17918. /**
  17919. * @ngdoc method
  17920. * @name $sce#parseAs
  17921. *
  17922. * @description
  17923. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  17924. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  17925. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  17926. * *result*)}
  17927. *
  17928. * @param {string} type The SCE context in which this result will be used.
  17929. * @param {string} expression String expression to compile.
  17930. * @return {function(context, locals)} A function which represents the compiled expression:
  17931. *
  17932. * * `context` – `{object}` – an object against which any expressions embedded in the
  17933. * strings are evaluated against (typically a scope object).
  17934. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  17935. * in `context`.
  17936. */
  17937. sce.parseAs = function sceParseAs(type, expr) {
  17938. var parsed = $parse(expr);
  17939. if (parsed.literal && parsed.constant) {
  17940. return parsed;
  17941. } else {
  17942. return $parse(expr, function(value) {
  17943. return sce.getTrusted(type, value);
  17944. });
  17945. }
  17946. };
  17947. /**
  17948. * @ngdoc method
  17949. * @name $sce#trustAs
  17950. *
  17951. * @description
  17952. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns a
  17953. * wrapped object that represents your value, and the trust you have in its safety for the given
  17954. * context. AngularJS can then use that value as-is in bindings of the specified secure context.
  17955. * This is used in bindings for `ng-bind-html`, `ng-include`, and most `src` attribute
  17956. * interpolations. See {@link ng.$sce $sce} for strict contextual escaping.
  17957. *
  17958. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  17959. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  17960. *
  17961. * @param {*} value The value that that should be considered trusted.
  17962. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  17963. * in the context you specified.
  17964. */
  17965. /**
  17966. * @ngdoc method
  17967. * @name $sce#trustAsHtml
  17968. *
  17969. * @description
  17970. * Shorthand method. `$sce.trustAsHtml(value)` →
  17971. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  17972. *
  17973. * @param {*} value The value to mark as trusted for `$sce.HTML` context.
  17974. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  17975. * in `$sce.HTML` context (like `ng-bind-html`).
  17976. */
  17977. /**
  17978. * @ngdoc method
  17979. * @name $sce#trustAsCss
  17980. *
  17981. * @description
  17982. * Shorthand method. `$sce.trustAsCss(value)` →
  17983. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.CSS, value)`}
  17984. *
  17985. * @param {*} value The value to mark as trusted for `$sce.CSS` context.
  17986. * @return {*} A wrapped version of value that can be used as a trusted variant
  17987. * of your `value` in `$sce.CSS` context. This context is currently unused, so there are
  17988. * almost no reasons to use this function so far.
  17989. */
  17990. /**
  17991. * @ngdoc method
  17992. * @name $sce#trustAsUrl
  17993. *
  17994. * @description
  17995. * Shorthand method. `$sce.trustAsUrl(value)` →
  17996. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  17997. *
  17998. * @param {*} value The value to mark as trusted for `$sce.URL` context.
  17999. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18000. * in `$sce.URL` context. That context is currently unused, so there are almost no reasons
  18001. * to use this function so far.
  18002. */
  18003. /**
  18004. * @ngdoc method
  18005. * @name $sce#trustAsResourceUrl
  18006. *
  18007. * @description
  18008. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  18009. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  18010. *
  18011. * @param {*} value The value to mark as trusted for `$sce.RESOURCE_URL` context.
  18012. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18013. * in `$sce.RESOURCE_URL` context (template URLs in `ng-include`, most `src` attribute
  18014. * bindings, ...)
  18015. */
  18016. /**
  18017. * @ngdoc method
  18018. * @name $sce#trustAsJs
  18019. *
  18020. * @description
  18021. * Shorthand method. `$sce.trustAsJs(value)` →
  18022. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  18023. *
  18024. * @param {*} value The value to mark as trusted for `$sce.JS` context.
  18025. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18026. * in `$sce.JS` context. That context is currently unused, so there are almost no reasons to
  18027. * use this function so far.
  18028. */
  18029. /**
  18030. * @ngdoc method
  18031. * @name $sce#getTrusted
  18032. *
  18033. * @description
  18034. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  18035. * takes any input, and either returns a value that's safe to use in the specified context,
  18036. * or throws an exception. This function is aware of trusted values created by the `trustAs`
  18037. * function and its shorthands, and when contexts are appropriate, returns the unwrapped value
  18038. * as-is. Finally, this function can also throw when there is no way to turn `maybeTrusted` in a
  18039. * safe value (e.g., no sanitization is available or possible.)
  18040. *
  18041. * @param {string} type The context in which this value is to be used.
  18042. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs
  18043. * `$sce.trustAs`} call, or anything else (which will not be considered trusted.)
  18044. * @return {*} A version of the value that's safe to use in the given context, or throws an
  18045. * exception if this is impossible.
  18046. */
  18047. /**
  18048. * @ngdoc method
  18049. * @name $sce#getTrustedHtml
  18050. *
  18051. * @description
  18052. * Shorthand method. `$sce.getTrustedHtml(value)` →
  18053. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  18054. *
  18055. * @param {*} value The value to pass to `$sce.getTrusted`.
  18056. * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  18057. */
  18058. /**
  18059. * @ngdoc method
  18060. * @name $sce#getTrustedCss
  18061. *
  18062. * @description
  18063. * Shorthand method. `$sce.getTrustedCss(value)` →
  18064. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  18065. *
  18066. * @param {*} value The value to pass to `$sce.getTrusted`.
  18067. * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  18068. */
  18069. /**
  18070. * @ngdoc method
  18071. * @name $sce#getTrustedUrl
  18072. *
  18073. * @description
  18074. * Shorthand method. `$sce.getTrustedUrl(value)` →
  18075. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  18076. *
  18077. * @param {*} value The value to pass to `$sce.getTrusted`.
  18078. * @return {*} The return value of `$sce.getTrusted($sce.URL, value)`
  18079. */
  18080. /**
  18081. * @ngdoc method
  18082. * @name $sce#getTrustedResourceUrl
  18083. *
  18084. * @description
  18085. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  18086. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  18087. *
  18088. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  18089. * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  18090. */
  18091. /**
  18092. * @ngdoc method
  18093. * @name $sce#getTrustedJs
  18094. *
  18095. * @description
  18096. * Shorthand method. `$sce.getTrustedJs(value)` →
  18097. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  18098. *
  18099. * @param {*} value The value to pass to `$sce.getTrusted`.
  18100. * @return {*} The return value of `$sce.getTrusted($sce.JS, value)`
  18101. */
  18102. /**
  18103. * @ngdoc method
  18104. * @name $sce#parseAsHtml
  18105. *
  18106. * @description
  18107. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  18108. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  18109. *
  18110. * @param {string} expression String expression to compile.
  18111. * @return {function(context, locals)} A function which represents the compiled expression:
  18112. *
  18113. * * `context` – `{object}` – an object against which any expressions embedded in the
  18114. * strings are evaluated against (typically a scope object).
  18115. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18116. * in `context`.
  18117. */
  18118. /**
  18119. * @ngdoc method
  18120. * @name $sce#parseAsCss
  18121. *
  18122. * @description
  18123. * Shorthand method. `$sce.parseAsCss(value)` →
  18124. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  18125. *
  18126. * @param {string} expression String expression to compile.
  18127. * @return {function(context, locals)} A function which represents the compiled expression:
  18128. *
  18129. * * `context` – `{object}` – an object against which any expressions embedded in the
  18130. * strings are evaluated against (typically a scope object).
  18131. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18132. * in `context`.
  18133. */
  18134. /**
  18135. * @ngdoc method
  18136. * @name $sce#parseAsUrl
  18137. *
  18138. * @description
  18139. * Shorthand method. `$sce.parseAsUrl(value)` →
  18140. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  18141. *
  18142. * @param {string} expression String expression to compile.
  18143. * @return {function(context, locals)} A function which represents the compiled expression:
  18144. *
  18145. * * `context` – `{object}` – an object against which any expressions embedded in the
  18146. * strings are evaluated against (typically a scope object).
  18147. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18148. * in `context`.
  18149. */
  18150. /**
  18151. * @ngdoc method
  18152. * @name $sce#parseAsResourceUrl
  18153. *
  18154. * @description
  18155. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  18156. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  18157. *
  18158. * @param {string} expression String expression to compile.
  18159. * @return {function(context, locals)} A function which represents the compiled expression:
  18160. *
  18161. * * `context` – `{object}` – an object against which any expressions embedded in the
  18162. * strings are evaluated against (typically a scope object).
  18163. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18164. * in `context`.
  18165. */
  18166. /**
  18167. * @ngdoc method
  18168. * @name $sce#parseAsJs
  18169. *
  18170. * @description
  18171. * Shorthand method. `$sce.parseAsJs(value)` →
  18172. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  18173. *
  18174. * @param {string} expression String expression to compile.
  18175. * @return {function(context, locals)} A function which represents the compiled expression:
  18176. *
  18177. * * `context` – `{object}` – an object against which any expressions embedded in the
  18178. * strings are evaluated against (typically a scope object).
  18179. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18180. * in `context`.
  18181. */
  18182. // Shorthand delegations.
  18183. var parse = sce.parseAs,
  18184. getTrusted = sce.getTrusted,
  18185. trustAs = sce.trustAs;
  18186. forEach(SCE_CONTEXTS, function(enumValue, name) {
  18187. var lName = lowercase(name);
  18188. sce[snakeToCamel('parse_as_' + lName)] = function(expr) {
  18189. return parse(enumValue, expr);
  18190. };
  18191. sce[snakeToCamel('get_trusted_' + lName)] = function(value) {
  18192. return getTrusted(enumValue, value);
  18193. };
  18194. sce[snakeToCamel('trust_as_' + lName)] = function(value) {
  18195. return trustAs(enumValue, value);
  18196. };
  18197. });
  18198. return sce;
  18199. }];
  18200. }
  18201. /* exported $SnifferProvider */
  18202. /**
  18203. * !!! This is an undocumented "private" service !!!
  18204. *
  18205. * @name $sniffer
  18206. * @requires $window
  18207. * @requires $document
  18208. * @this
  18209. *
  18210. * @property {boolean} history Does the browser support html5 history api ?
  18211. * @property {boolean} transitions Does the browser support CSS transition events ?
  18212. * @property {boolean} animations Does the browser support CSS animation events ?
  18213. *
  18214. * @description
  18215. * This is very simple implementation of testing browser's features.
  18216. */
  18217. function $SnifferProvider() {
  18218. this.$get = ['$window', '$document', function($window, $document) {
  18219. var eventSupport = {},
  18220. // Chrome Packaged Apps are not allowed to access `history.pushState`.
  18221. // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
  18222. // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
  18223. // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
  18224. // (see https://developer.chrome.com/apps/manifest/sandbox).
  18225. // (NW.js apps have access to Chrome APIs, but do support `history`.)
  18226. isNw = $window.nw && $window.nw.process,
  18227. isChromePackagedApp =
  18228. !isNw &&
  18229. $window.chrome &&
  18230. ($window.chrome.app && $window.chrome.app.runtime ||
  18231. !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
  18232. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  18233. android =
  18234. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  18235. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  18236. document = $document[0] || {},
  18237. bodyStyle = document.body && document.body.style,
  18238. transitions = false,
  18239. animations = false;
  18240. if (bodyStyle) {
  18241. // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x
  18242. // Mentioned browsers need a -webkit- prefix for transitions & animations.
  18243. transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);
  18244. animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);
  18245. }
  18246. return {
  18247. // Android has history.pushState, but it does not update location correctly
  18248. // so let's not use the history API at all.
  18249. // http://code.google.com/p/android/issues/detail?id=17471
  18250. // https://github.com/angular/angular.js/issues/904
  18251. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  18252. // so let's not use the history API also
  18253. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  18254. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  18255. hasEvent: function(event) {
  18256. // Support: IE 9-11 only
  18257. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  18258. // it. In particular the event is not fired when backspace or delete key are pressed or
  18259. // when cut operation is performed.
  18260. // IE10+ implements 'input' event but it erroneously fires under various situations,
  18261. // e.g. when placeholder changes, or a form is focused.
  18262. if (event === 'input' && msie) return false;
  18263. if (isUndefined(eventSupport[event])) {
  18264. var divElm = document.createElement('div');
  18265. eventSupport[event] = 'on' + event in divElm;
  18266. }
  18267. return eventSupport[event];
  18268. },
  18269. csp: csp(),
  18270. transitions: transitions,
  18271. animations: animations,
  18272. android: android
  18273. };
  18274. }];
  18275. }
  18276. var $templateRequestMinErr = minErr('$compile');
  18277. /**
  18278. * @ngdoc provider
  18279. * @name $templateRequestProvider
  18280. * @this
  18281. *
  18282. * @description
  18283. * Used to configure the options passed to the {@link $http} service when making a template request.
  18284. *
  18285. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  18286. * requesting a template.
  18287. */
  18288. function $TemplateRequestProvider() {
  18289. var httpOptions;
  18290. /**
  18291. * @ngdoc method
  18292. * @name $templateRequestProvider#httpOptions
  18293. * @description
  18294. * The options to be passed to the {@link $http} service when making the request.
  18295. * You can use this to override options such as the "Accept" header for template requests.
  18296. *
  18297. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  18298. * options if not overridden here.
  18299. *
  18300. * @param {string=} value new value for the {@link $http} options.
  18301. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  18302. */
  18303. this.httpOptions = function(val) {
  18304. if (val) {
  18305. httpOptions = val;
  18306. return this;
  18307. }
  18308. return httpOptions;
  18309. };
  18310. /**
  18311. * @ngdoc service
  18312. * @name $templateRequest
  18313. *
  18314. * @description
  18315. * The `$templateRequest` service runs security checks then downloads the provided template using
  18316. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  18317. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  18318. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  18319. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  18320. * when `tpl` is of type string and `$templateCache` has the matching entry.
  18321. *
  18322. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  18323. * can configure this via {@link $templateRequestProvider#httpOptions}.
  18324. *
  18325. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  18326. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  18327. *
  18328. * @return {Promise} a promise for the HTTP response data of the given URL.
  18329. *
  18330. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  18331. */
  18332. this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',
  18333. function($exceptionHandler, $templateCache, $http, $q, $sce) {
  18334. function handleRequestFn(tpl, ignoreRequestError) {
  18335. handleRequestFn.totalPendingRequests++;
  18336. // We consider the template cache holds only trusted templates, so
  18337. // there's no need to go through whitelisting again for keys that already
  18338. // are included in there. This also makes Angular accept any script
  18339. // directive, no matter its name. However, we still need to unwrap trusted
  18340. // types.
  18341. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  18342. tpl = $sce.getTrustedResourceUrl(tpl);
  18343. }
  18344. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  18345. if (isArray(transformResponse)) {
  18346. transformResponse = transformResponse.filter(function(transformer) {
  18347. return transformer !== defaultHttpResponseTransform;
  18348. });
  18349. } else if (transformResponse === defaultHttpResponseTransform) {
  18350. transformResponse = null;
  18351. }
  18352. return $http.get(tpl, extend({
  18353. cache: $templateCache,
  18354. transformResponse: transformResponse
  18355. }, httpOptions))
  18356. .finally(function() {
  18357. handleRequestFn.totalPendingRequests--;
  18358. })
  18359. .then(function(response) {
  18360. $templateCache.put(tpl, response.data);
  18361. return response.data;
  18362. }, handleError);
  18363. function handleError(resp) {
  18364. if (!ignoreRequestError) {
  18365. resp = $templateRequestMinErr('tpload',
  18366. 'Failed to load template: {0} (HTTP status: {1} {2})',
  18367. tpl, resp.status, resp.statusText);
  18368. $exceptionHandler(resp);
  18369. }
  18370. return $q.reject(resp);
  18371. }
  18372. }
  18373. handleRequestFn.totalPendingRequests = 0;
  18374. return handleRequestFn;
  18375. }
  18376. ];
  18377. }
  18378. /** @this */
  18379. function $$TestabilityProvider() {
  18380. this.$get = ['$rootScope', '$browser', '$location',
  18381. function($rootScope, $browser, $location) {
  18382. /**
  18383. * @name $testability
  18384. *
  18385. * @description
  18386. * The private $$testability service provides a collection of methods for use when debugging
  18387. * or by automated test and debugging tools.
  18388. */
  18389. var testability = {};
  18390. /**
  18391. * @name $$testability#findBindings
  18392. *
  18393. * @description
  18394. * Returns an array of elements that are bound (via ng-bind or {{}})
  18395. * to expressions matching the input.
  18396. *
  18397. * @param {Element} element The element root to search from.
  18398. * @param {string} expression The binding expression to match.
  18399. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18400. * for the expression. Filters and whitespace are ignored.
  18401. */
  18402. testability.findBindings = function(element, expression, opt_exactMatch) {
  18403. var bindings = element.getElementsByClassName('ng-binding');
  18404. var matches = [];
  18405. forEach(bindings, function(binding) {
  18406. var dataBinding = angular.element(binding).data('$binding');
  18407. if (dataBinding) {
  18408. forEach(dataBinding, function(bindingName) {
  18409. if (opt_exactMatch) {
  18410. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  18411. if (matcher.test(bindingName)) {
  18412. matches.push(binding);
  18413. }
  18414. } else {
  18415. if (bindingName.indexOf(expression) !== -1) {
  18416. matches.push(binding);
  18417. }
  18418. }
  18419. });
  18420. }
  18421. });
  18422. return matches;
  18423. };
  18424. /**
  18425. * @name $$testability#findModels
  18426. *
  18427. * @description
  18428. * Returns an array of elements that are two-way found via ng-model to
  18429. * expressions matching the input.
  18430. *
  18431. * @param {Element} element The element root to search from.
  18432. * @param {string} expression The model expression to match.
  18433. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18434. * for the expression.
  18435. */
  18436. testability.findModels = function(element, expression, opt_exactMatch) {
  18437. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  18438. for (var p = 0; p < prefixes.length; ++p) {
  18439. var attributeEquals = opt_exactMatch ? '=' : '*=';
  18440. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  18441. var elements = element.querySelectorAll(selector);
  18442. if (elements.length) {
  18443. return elements;
  18444. }
  18445. }
  18446. };
  18447. /**
  18448. * @name $$testability#getLocation
  18449. *
  18450. * @description
  18451. * Shortcut for getting the location in a browser agnostic way. Returns
  18452. * the path, search, and hash. (e.g. /path?a=b#hash)
  18453. */
  18454. testability.getLocation = function() {
  18455. return $location.url();
  18456. };
  18457. /**
  18458. * @name $$testability#setLocation
  18459. *
  18460. * @description
  18461. * Shortcut for navigating to a location without doing a full page reload.
  18462. *
  18463. * @param {string} url The location url (path, search and hash,
  18464. * e.g. /path?a=b#hash) to go to.
  18465. */
  18466. testability.setLocation = function(url) {
  18467. if (url !== $location.url()) {
  18468. $location.url(url);
  18469. $rootScope.$digest();
  18470. }
  18471. };
  18472. /**
  18473. * @name $$testability#whenStable
  18474. *
  18475. * @description
  18476. * Calls the callback when $timeout and $http requests are completed.
  18477. *
  18478. * @param {function} callback
  18479. */
  18480. testability.whenStable = function(callback) {
  18481. $browser.notifyWhenNoOutstandingRequests(callback);
  18482. };
  18483. return testability;
  18484. }];
  18485. }
  18486. /** @this */
  18487. function $TimeoutProvider() {
  18488. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  18489. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  18490. var deferreds = {};
  18491. /**
  18492. * @ngdoc service
  18493. * @name $timeout
  18494. *
  18495. * @description
  18496. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  18497. * block and delegates any exceptions to
  18498. * {@link ng.$exceptionHandler $exceptionHandler} service.
  18499. *
  18500. * The return value of calling `$timeout` is a promise, which will be resolved when
  18501. * the delay has passed and the timeout function, if provided, is executed.
  18502. *
  18503. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  18504. *
  18505. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  18506. * synchronously flush the queue of deferred functions.
  18507. *
  18508. * If you only want a promise that will be resolved after some specified delay
  18509. * then you can call `$timeout` without the `fn` function.
  18510. *
  18511. * @param {function()=} fn A function, whose execution should be delayed.
  18512. * @param {number=} [delay=0] Delay in milliseconds.
  18513. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  18514. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  18515. * @param {...*=} Pass additional parameters to the executed function.
  18516. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  18517. * will be resolved with the return value of the `fn` function.
  18518. *
  18519. */
  18520. function timeout(fn, delay, invokeApply) {
  18521. if (!isFunction(fn)) {
  18522. invokeApply = delay;
  18523. delay = fn;
  18524. fn = noop;
  18525. }
  18526. var args = sliceArgs(arguments, 3),
  18527. skipApply = (isDefined(invokeApply) && !invokeApply),
  18528. deferred = (skipApply ? $$q : $q).defer(),
  18529. promise = deferred.promise,
  18530. timeoutId;
  18531. timeoutId = $browser.defer(function() {
  18532. try {
  18533. deferred.resolve(fn.apply(null, args));
  18534. } catch (e) {
  18535. deferred.reject(e);
  18536. $exceptionHandler(e);
  18537. } finally {
  18538. delete deferreds[promise.$$timeoutId];
  18539. }
  18540. if (!skipApply) $rootScope.$apply();
  18541. }, delay);
  18542. promise.$$timeoutId = timeoutId;
  18543. deferreds[timeoutId] = deferred;
  18544. return promise;
  18545. }
  18546. /**
  18547. * @ngdoc method
  18548. * @name $timeout#cancel
  18549. *
  18550. * @description
  18551. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  18552. * resolved with a rejection.
  18553. *
  18554. * @param {Promise=} promise Promise returned by the `$timeout` function.
  18555. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  18556. * canceled.
  18557. */
  18558. timeout.cancel = function(promise) {
  18559. if (promise && promise.$$timeoutId in deferreds) {
  18560. // Timeout cancels should not report an unhandled promise.
  18561. markQExceptionHandled(deferreds[promise.$$timeoutId].promise);
  18562. deferreds[promise.$$timeoutId].reject('canceled');
  18563. delete deferreds[promise.$$timeoutId];
  18564. return $browser.defer.cancel(promise.$$timeoutId);
  18565. }
  18566. return false;
  18567. };
  18568. return timeout;
  18569. }];
  18570. }
  18571. // NOTE: The usage of window and document instead of $window and $document here is
  18572. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  18573. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  18574. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  18575. // doesn't know about mocked locations and resolves URLs to the real document - which is
  18576. // exactly the behavior needed here. There is little value is mocking these out for this
  18577. // service.
  18578. var urlParsingNode = window.document.createElement('a');
  18579. var originUrl = urlResolve(window.location.href);
  18580. /**
  18581. *
  18582. * Implementation Notes for non-IE browsers
  18583. * ----------------------------------------
  18584. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  18585. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  18586. * URL will be resolved into an absolute URL in the context of the application document.
  18587. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  18588. * properties are all populated to reflect the normalized URL. This approach has wide
  18589. * compatibility - Safari 1+, Mozilla 1+ etc. See
  18590. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18591. *
  18592. * Implementation Notes for IE
  18593. * ---------------------------
  18594. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  18595. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  18596. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  18597. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  18598. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  18599. * properties such as protocol, hostname, port, etc.
  18600. *
  18601. * References:
  18602. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  18603. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18604. * http://url.spec.whatwg.org/#urlutils
  18605. * https://github.com/angular/angular.js/pull/2902
  18606. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  18607. *
  18608. * @kind function
  18609. * @param {string} url The URL to be parsed.
  18610. * @description Normalizes and parses a URL.
  18611. * @returns {object} Returns the normalized URL as a dictionary.
  18612. *
  18613. * | member name | Description |
  18614. * |---------------|----------------|
  18615. * | href | A normalized version of the provided URL if it was not an absolute URL |
  18616. * | protocol | The protocol including the trailing colon |
  18617. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  18618. * | search | The search params, minus the question mark |
  18619. * | hash | The hash string, minus the hash symbol
  18620. * | hostname | The hostname
  18621. * | port | The port, without ":"
  18622. * | pathname | The pathname, beginning with "/"
  18623. *
  18624. */
  18625. function urlResolve(url) {
  18626. var href = url;
  18627. // Support: IE 9-11 only
  18628. if (msie) {
  18629. // Normalize before parse. Refer Implementation Notes on why this is
  18630. // done in two steps on IE.
  18631. urlParsingNode.setAttribute('href', href);
  18632. href = urlParsingNode.href;
  18633. }
  18634. urlParsingNode.setAttribute('href', href);
  18635. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  18636. return {
  18637. href: urlParsingNode.href,
  18638. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  18639. host: urlParsingNode.host,
  18640. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  18641. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  18642. hostname: urlParsingNode.hostname,
  18643. port: urlParsingNode.port,
  18644. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  18645. ? urlParsingNode.pathname
  18646. : '/' + urlParsingNode.pathname
  18647. };
  18648. }
  18649. /**
  18650. * Parse a request URL and determine whether this is a same-origin request as the application document.
  18651. *
  18652. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  18653. * or a parsed URL object.
  18654. * @returns {boolean} Whether the request is for the same origin as the application document.
  18655. */
  18656. function urlIsSameOrigin(requestUrl) {
  18657. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  18658. return (parsed.protocol === originUrl.protocol &&
  18659. parsed.host === originUrl.host);
  18660. }
  18661. /**
  18662. * @ngdoc service
  18663. * @name $window
  18664. * @this
  18665. *
  18666. * @description
  18667. * A reference to the browser's `window` object. While `window`
  18668. * is globally available in JavaScript, it causes testability problems, because
  18669. * it is a global variable. In angular we always refer to it through the
  18670. * `$window` service, so it may be overridden, removed or mocked for testing.
  18671. *
  18672. * Expressions, like the one defined for the `ngClick` directive in the example
  18673. * below, are evaluated with respect to the current scope. Therefore, there is
  18674. * no risk of inadvertently coding in a dependency on a global value in such an
  18675. * expression.
  18676. *
  18677. * @example
  18678. <example module="windowExample" name="window-service">
  18679. <file name="index.html">
  18680. <script>
  18681. angular.module('windowExample', [])
  18682. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  18683. $scope.greeting = 'Hello, World!';
  18684. $scope.doGreeting = function(greeting) {
  18685. $window.alert(greeting);
  18686. };
  18687. }]);
  18688. </script>
  18689. <div ng-controller="ExampleController">
  18690. <input type="text" ng-model="greeting" aria-label="greeting" />
  18691. <button ng-click="doGreeting(greeting)">ALERT</button>
  18692. </div>
  18693. </file>
  18694. <file name="protractor.js" type="protractor">
  18695. it('should display the greeting in the input box', function() {
  18696. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  18697. // If we click the button it will block the test runner
  18698. // element(':button').click();
  18699. });
  18700. </file>
  18701. </example>
  18702. */
  18703. function $WindowProvider() {
  18704. this.$get = valueFn(window);
  18705. }
  18706. /**
  18707. * @name $$cookieReader
  18708. * @requires $document
  18709. *
  18710. * @description
  18711. * This is a private service for reading cookies used by $http and ngCookies
  18712. *
  18713. * @return {Object} a key/value map of the current cookies
  18714. */
  18715. function $$CookieReader($document) {
  18716. var rawDocument = $document[0] || {};
  18717. var lastCookies = {};
  18718. var lastCookieString = '';
  18719. function safeGetCookie(rawDocument) {
  18720. try {
  18721. return rawDocument.cookie || '';
  18722. } catch (e) {
  18723. return '';
  18724. }
  18725. }
  18726. function safeDecodeURIComponent(str) {
  18727. try {
  18728. return decodeURIComponent(str);
  18729. } catch (e) {
  18730. return str;
  18731. }
  18732. }
  18733. return function() {
  18734. var cookieArray, cookie, i, index, name;
  18735. var currentCookieString = safeGetCookie(rawDocument);
  18736. if (currentCookieString !== lastCookieString) {
  18737. lastCookieString = currentCookieString;
  18738. cookieArray = lastCookieString.split('; ');
  18739. lastCookies = {};
  18740. for (i = 0; i < cookieArray.length; i++) {
  18741. cookie = cookieArray[i];
  18742. index = cookie.indexOf('=');
  18743. if (index > 0) { //ignore nameless cookies
  18744. name = safeDecodeURIComponent(cookie.substring(0, index));
  18745. // the first value that is seen for a cookie is the most
  18746. // specific one. values for the same cookie name that
  18747. // follow are for less specific paths.
  18748. if (isUndefined(lastCookies[name])) {
  18749. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  18750. }
  18751. }
  18752. }
  18753. }
  18754. return lastCookies;
  18755. };
  18756. }
  18757. $$CookieReader.$inject = ['$document'];
  18758. /** @this */
  18759. function $$CookieReaderProvider() {
  18760. this.$get = $$CookieReader;
  18761. }
  18762. /* global currencyFilter: true,
  18763. dateFilter: true,
  18764. filterFilter: true,
  18765. jsonFilter: true,
  18766. limitToFilter: true,
  18767. lowercaseFilter: true,
  18768. numberFilter: true,
  18769. orderByFilter: true,
  18770. uppercaseFilter: true,
  18771. */
  18772. /**
  18773. * @ngdoc provider
  18774. * @name $filterProvider
  18775. * @description
  18776. *
  18777. * Filters are just functions which transform input to an output. However filters need to be
  18778. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  18779. * annotated with dependencies and is responsible for creating a filter function.
  18780. *
  18781. * <div class="alert alert-warning">
  18782. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18783. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18784. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18785. * (`myapp_subsection_filterx`).
  18786. * </div>
  18787. *
  18788. * ```js
  18789. * // Filter registration
  18790. * function MyModule($provide, $filterProvider) {
  18791. * // create a service to demonstrate injection (not always needed)
  18792. * $provide.value('greet', function(name){
  18793. * return 'Hello ' + name + '!';
  18794. * });
  18795. *
  18796. * // register a filter factory which uses the
  18797. * // greet service to demonstrate DI.
  18798. * $filterProvider.register('greet', function(greet){
  18799. * // return the filter function which uses the greet service
  18800. * // to generate salutation
  18801. * return function(text) {
  18802. * // filters need to be forgiving so check input validity
  18803. * return text && greet(text) || text;
  18804. * };
  18805. * });
  18806. * }
  18807. * ```
  18808. *
  18809. * The filter function is registered with the `$injector` under the filter name suffix with
  18810. * `Filter`.
  18811. *
  18812. * ```js
  18813. * it('should be the same instance', inject(
  18814. * function($filterProvider) {
  18815. * $filterProvider.register('reverse', function(){
  18816. * return ...;
  18817. * });
  18818. * },
  18819. * function($filter, reverseFilter) {
  18820. * expect($filter('reverse')).toBe(reverseFilter);
  18821. * });
  18822. * ```
  18823. *
  18824. *
  18825. * For more information about how angular filters work, and how to create your own filters, see
  18826. * {@link guide/filter Filters} in the Angular Developer Guide.
  18827. */
  18828. /**
  18829. * @ngdoc service
  18830. * @name $filter
  18831. * @kind function
  18832. * @description
  18833. * Filters are used for formatting data displayed to the user.
  18834. *
  18835. * They can be used in view templates, controllers or services.Angular comes
  18836. * with a collection of [built-in filters](api/ng/filter), but it is easy to
  18837. * define your own as well.
  18838. *
  18839. * The general syntax in templates is as follows:
  18840. *
  18841. * ```html
  18842. * {{ expression [| filter_name[:parameter_value] ... ] }}
  18843. * ```
  18844. *
  18845. * @param {String} name Name of the filter function to retrieve
  18846. * @return {Function} the filter function
  18847. * @example
  18848. <example name="$filter" module="filterExample">
  18849. <file name="index.html">
  18850. <div ng-controller="MainCtrl">
  18851. <h3>{{ originalText }}</h3>
  18852. <h3>{{ filteredText }}</h3>
  18853. </div>
  18854. </file>
  18855. <file name="script.js">
  18856. angular.module('filterExample', [])
  18857. .controller('MainCtrl', function($scope, $filter) {
  18858. $scope.originalText = 'hello';
  18859. $scope.filteredText = $filter('uppercase')($scope.originalText);
  18860. });
  18861. </file>
  18862. </example>
  18863. */
  18864. $FilterProvider.$inject = ['$provide'];
  18865. /** @this */
  18866. function $FilterProvider($provide) {
  18867. var suffix = 'Filter';
  18868. /**
  18869. * @ngdoc method
  18870. * @name $filterProvider#register
  18871. * @param {string|Object} name Name of the filter function, or an object map of filters where
  18872. * the keys are the filter names and the values are the filter factories.
  18873. *
  18874. * <div class="alert alert-warning">
  18875. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18876. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18877. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18878. * (`myapp_subsection_filterx`).
  18879. * </div>
  18880. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  18881. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  18882. * of the registered filter instances.
  18883. */
  18884. function register(name, factory) {
  18885. if (isObject(name)) {
  18886. var filters = {};
  18887. forEach(name, function(filter, key) {
  18888. filters[key] = register(key, filter);
  18889. });
  18890. return filters;
  18891. } else {
  18892. return $provide.factory(name + suffix, factory);
  18893. }
  18894. }
  18895. this.register = register;
  18896. this.$get = ['$injector', function($injector) {
  18897. return function(name) {
  18898. return $injector.get(name + suffix);
  18899. };
  18900. }];
  18901. ////////////////////////////////////////
  18902. /* global
  18903. currencyFilter: false,
  18904. dateFilter: false,
  18905. filterFilter: false,
  18906. jsonFilter: false,
  18907. limitToFilter: false,
  18908. lowercaseFilter: false,
  18909. numberFilter: false,
  18910. orderByFilter: false,
  18911. uppercaseFilter: false
  18912. */
  18913. register('currency', currencyFilter);
  18914. register('date', dateFilter);
  18915. register('filter', filterFilter);
  18916. register('json', jsonFilter);
  18917. register('limitTo', limitToFilter);
  18918. register('lowercase', lowercaseFilter);
  18919. register('number', numberFilter);
  18920. register('orderBy', orderByFilter);
  18921. register('uppercase', uppercaseFilter);
  18922. }
  18923. /**
  18924. * @ngdoc filter
  18925. * @name filter
  18926. * @kind function
  18927. *
  18928. * @description
  18929. * Selects a subset of items from `array` and returns it as a new array.
  18930. *
  18931. * @param {Array} array The source array.
  18932. * <div class="alert alert-info">
  18933. * **Note**: If the array contains objects that reference themselves, filtering is not possible.
  18934. * </div>
  18935. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  18936. * `array`.
  18937. *
  18938. * Can be one of:
  18939. *
  18940. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  18941. * objects with string properties in `array` that match this string will be returned. This also
  18942. * applies to nested object properties.
  18943. * The predicate can be negated by prefixing the string with `!`.
  18944. *
  18945. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  18946. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  18947. * which have property `name` containing "M" and property `phone` containing "1". A special
  18948. * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
  18949. * against any property of the object or its nested object properties. That's equivalent to the
  18950. * simple substring match with a `string` as described above. The special property name can be
  18951. * overwritten, using the `anyPropertyKey` parameter.
  18952. * The predicate can be negated by prefixing the string with `!`.
  18953. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  18954. * not containing "M".
  18955. *
  18956. * Note that a named property will match properties on the same level only, while the special
  18957. * `$` property will match properties on the same level or deeper. E.g. an array item like
  18958. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  18959. * **will** be matched by `{$: 'John'}`.
  18960. *
  18961. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  18962. * The function is called for each element of the array, with the element, its index, and
  18963. * the entire array itself as arguments.
  18964. *
  18965. * The final result is an array of those elements that the predicate returned true for.
  18966. *
  18967. * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in
  18968. * determining if values retrieved using `expression` (when it is not a function) should be
  18969. * considered a match based on the expected value (from the filter expression) and actual
  18970. * value (from the object in the array).
  18971. *
  18972. * Can be one of:
  18973. *
  18974. * - `function(actual, expected)`:
  18975. * The function will be given the object value and the predicate value to compare and
  18976. * should return true if both values should be considered equal.
  18977. *
  18978. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  18979. * This is essentially strict comparison of expected and actual.
  18980. *
  18981. * - `false`: A short hand for a function which will look for a substring match in a case
  18982. * insensitive way. Primitive values are converted to strings. Objects are not compared against
  18983. * primitives, unless they have a custom `toString` method (e.g. `Date` objects).
  18984. *
  18985. *
  18986. * Defaults to `false`.
  18987. *
  18988. * @param {string} [anyPropertyKey] The special property name that matches against any property.
  18989. * By default `$`.
  18990. *
  18991. * @example
  18992. <example name="filter-filter">
  18993. <file name="index.html">
  18994. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  18995. {name:'Mary', phone:'800-BIG-MARY'},
  18996. {name:'Mike', phone:'555-4321'},
  18997. {name:'Adam', phone:'555-5678'},
  18998. {name:'Julie', phone:'555-8765'},
  18999. {name:'Juliette', phone:'555-5678'}]"></div>
  19000. <label>Search: <input ng-model="searchText"></label>
  19001. <table id="searchTextResults">
  19002. <tr><th>Name</th><th>Phone</th></tr>
  19003. <tr ng-repeat="friend in friends | filter:searchText">
  19004. <td>{{friend.name}}</td>
  19005. <td>{{friend.phone}}</td>
  19006. </tr>
  19007. </table>
  19008. <hr>
  19009. <label>Any: <input ng-model="search.$"></label> <br>
  19010. <label>Name only <input ng-model="search.name"></label><br>
  19011. <label>Phone only <input ng-model="search.phone"></label><br>
  19012. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  19013. <table id="searchObjResults">
  19014. <tr><th>Name</th><th>Phone</th></tr>
  19015. <tr ng-repeat="friendObj in friends | filter:search:strict">
  19016. <td>{{friendObj.name}}</td>
  19017. <td>{{friendObj.phone}}</td>
  19018. </tr>
  19019. </table>
  19020. </file>
  19021. <file name="protractor.js" type="protractor">
  19022. var expectFriendNames = function(expectedNames, key) {
  19023. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  19024. arr.forEach(function(wd, i) {
  19025. expect(wd.getText()).toMatch(expectedNames[i]);
  19026. });
  19027. });
  19028. };
  19029. it('should search across all fields when filtering with a string', function() {
  19030. var searchText = element(by.model('searchText'));
  19031. searchText.clear();
  19032. searchText.sendKeys('m');
  19033. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  19034. searchText.clear();
  19035. searchText.sendKeys('76');
  19036. expectFriendNames(['John', 'Julie'], 'friend');
  19037. });
  19038. it('should search in specific fields when filtering with a predicate object', function() {
  19039. var searchAny = element(by.model('search.$'));
  19040. searchAny.clear();
  19041. searchAny.sendKeys('i');
  19042. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  19043. });
  19044. it('should use a equal comparison when comparator is true', function() {
  19045. var searchName = element(by.model('search.name'));
  19046. var strict = element(by.model('strict'));
  19047. searchName.clear();
  19048. searchName.sendKeys('Julie');
  19049. strict.click();
  19050. expectFriendNames(['Julie'], 'friendObj');
  19051. });
  19052. </file>
  19053. </example>
  19054. */
  19055. function filterFilter() {
  19056. return function(array, expression, comparator, anyPropertyKey) {
  19057. if (!isArrayLike(array)) {
  19058. if (array == null) {
  19059. return array;
  19060. } else {
  19061. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  19062. }
  19063. }
  19064. anyPropertyKey = anyPropertyKey || '$';
  19065. var expressionType = getTypeForFilter(expression);
  19066. var predicateFn;
  19067. var matchAgainstAnyProp;
  19068. switch (expressionType) {
  19069. case 'function':
  19070. predicateFn = expression;
  19071. break;
  19072. case 'boolean':
  19073. case 'null':
  19074. case 'number':
  19075. case 'string':
  19076. matchAgainstAnyProp = true;
  19077. // falls through
  19078. case 'object':
  19079. predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  19080. break;
  19081. default:
  19082. return array;
  19083. }
  19084. return Array.prototype.filter.call(array, predicateFn);
  19085. };
  19086. }
  19087. // Helper functions for `filterFilter`
  19088. function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
  19089. var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
  19090. var predicateFn;
  19091. if (comparator === true) {
  19092. comparator = equals;
  19093. } else if (!isFunction(comparator)) {
  19094. comparator = function(actual, expected) {
  19095. if (isUndefined(actual)) {
  19096. // No substring matching against `undefined`
  19097. return false;
  19098. }
  19099. if ((actual === null) || (expected === null)) {
  19100. // No substring matching against `null`; only match against `null`
  19101. return actual === expected;
  19102. }
  19103. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  19104. // Should not compare primitives against objects, unless they have custom `toString` method
  19105. return false;
  19106. }
  19107. actual = lowercase('' + actual);
  19108. expected = lowercase('' + expected);
  19109. return actual.indexOf(expected) !== -1;
  19110. };
  19111. }
  19112. predicateFn = function(item) {
  19113. if (shouldMatchPrimitives && !isObject(item)) {
  19114. return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
  19115. }
  19116. return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  19117. };
  19118. return predicateFn;
  19119. }
  19120. function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
  19121. var actualType = getTypeForFilter(actual);
  19122. var expectedType = getTypeForFilter(expected);
  19123. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  19124. return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
  19125. } else if (isArray(actual)) {
  19126. // In case `actual` is an array, consider it a match
  19127. // if ANY of it's items matches `expected`
  19128. return actual.some(function(item) {
  19129. return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
  19130. });
  19131. }
  19132. switch (actualType) {
  19133. case 'object':
  19134. var key;
  19135. if (matchAgainstAnyProp) {
  19136. for (key in actual) {
  19137. // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined
  19138. // See: https://github.com/angular/angular.js/issues/15644
  19139. if (key.charAt && (key.charAt(0) !== '$') &&
  19140. deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
  19141. return true;
  19142. }
  19143. }
  19144. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
  19145. } else if (expectedType === 'object') {
  19146. for (key in expected) {
  19147. var expectedVal = expected[key];
  19148. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  19149. continue;
  19150. }
  19151. var matchAnyProperty = key === anyPropertyKey;
  19152. var actualVal = matchAnyProperty ? actual : actual[key];
  19153. if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
  19154. return false;
  19155. }
  19156. }
  19157. return true;
  19158. } else {
  19159. return comparator(actual, expected);
  19160. }
  19161. case 'function':
  19162. return false;
  19163. default:
  19164. return comparator(actual, expected);
  19165. }
  19166. }
  19167. // Used for easily differentiating between `null` and actual `object`
  19168. function getTypeForFilter(val) {
  19169. return (val === null) ? 'null' : typeof val;
  19170. }
  19171. var MAX_DIGITS = 22;
  19172. var DECIMAL_SEP = '.';
  19173. var ZERO_CHAR = '0';
  19174. /**
  19175. * @ngdoc filter
  19176. * @name currency
  19177. * @kind function
  19178. *
  19179. * @description
  19180. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  19181. * symbol for current locale is used.
  19182. *
  19183. * @param {number} amount Input to filter.
  19184. * @param {string=} symbol Currency symbol or identifier to be displayed.
  19185. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  19186. * @returns {string} Formatted number.
  19187. *
  19188. *
  19189. * @example
  19190. <example module="currencyExample" name="currency-filter">
  19191. <file name="index.html">
  19192. <script>
  19193. angular.module('currencyExample', [])
  19194. .controller('ExampleController', ['$scope', function($scope) {
  19195. $scope.amount = 1234.56;
  19196. }]);
  19197. </script>
  19198. <div ng-controller="ExampleController">
  19199. <input type="number" ng-model="amount" aria-label="amount"> <br>
  19200. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  19201. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
  19202. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  19203. </div>
  19204. </file>
  19205. <file name="protractor.js" type="protractor">
  19206. it('should init with 1234.56', function() {
  19207. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  19208. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  19209. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  19210. });
  19211. it('should update', function() {
  19212. if (browser.params.browser === 'safari') {
  19213. // Safari does not understand the minus key. See
  19214. // https://github.com/angular/protractor/issues/481
  19215. return;
  19216. }
  19217. element(by.model('amount')).clear();
  19218. element(by.model('amount')).sendKeys('-1234');
  19219. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  19220. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  19221. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  19222. });
  19223. </file>
  19224. </example>
  19225. */
  19226. currencyFilter.$inject = ['$locale'];
  19227. function currencyFilter($locale) {
  19228. var formats = $locale.NUMBER_FORMATS;
  19229. return function(amount, currencySymbol, fractionSize) {
  19230. if (isUndefined(currencySymbol)) {
  19231. currencySymbol = formats.CURRENCY_SYM;
  19232. }
  19233. if (isUndefined(fractionSize)) {
  19234. fractionSize = formats.PATTERNS[1].maxFrac;
  19235. }
  19236. // if null or undefined pass it through
  19237. return (amount == null)
  19238. ? amount
  19239. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  19240. replace(/\u00A4/g, currencySymbol);
  19241. };
  19242. }
  19243. /**
  19244. * @ngdoc filter
  19245. * @name number
  19246. * @kind function
  19247. *
  19248. * @description
  19249. * Formats a number as text.
  19250. *
  19251. * If the input is null or undefined, it will just be returned.
  19252. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  19253. * If the input is not a number an empty string is returned.
  19254. *
  19255. *
  19256. * @param {number|string} number Number to format.
  19257. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  19258. * If this is not provided then the fraction size is computed from the current locale's number
  19259. * formatting pattern. In the case of the default locale, it will be 3.
  19260. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  19261. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  19262. * include "," group separators after each third digit).
  19263. *
  19264. * @example
  19265. <example module="numberFilterExample" name="number-filter">
  19266. <file name="index.html">
  19267. <script>
  19268. angular.module('numberFilterExample', [])
  19269. .controller('ExampleController', ['$scope', function($scope) {
  19270. $scope.val = 1234.56789;
  19271. }]);
  19272. </script>
  19273. <div ng-controller="ExampleController">
  19274. <label>Enter number: <input ng-model='val'></label><br>
  19275. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  19276. No fractions: <span>{{val | number:0}}</span><br>
  19277. Negative number: <span>{{-val | number:4}}</span>
  19278. </div>
  19279. </file>
  19280. <file name="protractor.js" type="protractor">
  19281. it('should format numbers', function() {
  19282. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  19283. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  19284. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  19285. });
  19286. it('should update', function() {
  19287. element(by.model('val')).clear();
  19288. element(by.model('val')).sendKeys('3374.333');
  19289. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  19290. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  19291. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  19292. });
  19293. </file>
  19294. </example>
  19295. */
  19296. numberFilter.$inject = ['$locale'];
  19297. function numberFilter($locale) {
  19298. var formats = $locale.NUMBER_FORMATS;
  19299. return function(number, fractionSize) {
  19300. // if null or undefined pass it through
  19301. return (number == null)
  19302. ? number
  19303. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  19304. fractionSize);
  19305. };
  19306. }
  19307. /**
  19308. * Parse a number (as a string) into three components that can be used
  19309. * for formatting the number.
  19310. *
  19311. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  19312. *
  19313. * @param {string} numStr The number to parse
  19314. * @return {object} An object describing this number, containing the following keys:
  19315. * - d : an array of digits containing leading zeros as necessary
  19316. * - i : the number of the digits in `d` that are to the left of the decimal point
  19317. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  19318. *
  19319. */
  19320. function parse(numStr) {
  19321. var exponent = 0, digits, numberOfIntegerDigits;
  19322. var i, j, zeros;
  19323. // Decimal point?
  19324. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  19325. numStr = numStr.replace(DECIMAL_SEP, '');
  19326. }
  19327. // Exponential form?
  19328. if ((i = numStr.search(/e/i)) > 0) {
  19329. // Work out the exponent.
  19330. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  19331. numberOfIntegerDigits += +numStr.slice(i + 1);
  19332. numStr = numStr.substring(0, i);
  19333. } else if (numberOfIntegerDigits < 0) {
  19334. // There was no decimal point or exponent so it is an integer.
  19335. numberOfIntegerDigits = numStr.length;
  19336. }
  19337. // Count the number of leading zeros.
  19338. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
  19339. if (i === (zeros = numStr.length)) {
  19340. // The digits are all zero.
  19341. digits = [0];
  19342. numberOfIntegerDigits = 1;
  19343. } else {
  19344. // Count the number of trailing zeros
  19345. zeros--;
  19346. while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
  19347. // Trailing zeros are insignificant so ignore them
  19348. numberOfIntegerDigits -= i;
  19349. digits = [];
  19350. // Convert string to array of digits without leading/trailing zeros.
  19351. for (j = 0; i <= zeros; i++, j++) {
  19352. digits[j] = +numStr.charAt(i);
  19353. }
  19354. }
  19355. // If the number overflows the maximum allowed digits then use an exponent.
  19356. if (numberOfIntegerDigits > MAX_DIGITS) {
  19357. digits = digits.splice(0, MAX_DIGITS - 1);
  19358. exponent = numberOfIntegerDigits - 1;
  19359. numberOfIntegerDigits = 1;
  19360. }
  19361. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  19362. }
  19363. /**
  19364. * Round the parsed number to the specified number of decimal places
  19365. * This function changed the parsedNumber in-place
  19366. */
  19367. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  19368. var digits = parsedNumber.d;
  19369. var fractionLen = digits.length - parsedNumber.i;
  19370. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  19371. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  19372. // The index of the digit to where rounding is to occur
  19373. var roundAt = fractionSize + parsedNumber.i;
  19374. var digit = digits[roundAt];
  19375. if (roundAt > 0) {
  19376. // Drop fractional digits beyond `roundAt`
  19377. digits.splice(Math.max(parsedNumber.i, roundAt));
  19378. // Set non-fractional digits beyond `roundAt` to 0
  19379. for (var j = roundAt; j < digits.length; j++) {
  19380. digits[j] = 0;
  19381. }
  19382. } else {
  19383. // We rounded to zero so reset the parsedNumber
  19384. fractionLen = Math.max(0, fractionLen);
  19385. parsedNumber.i = 1;
  19386. digits.length = Math.max(1, roundAt = fractionSize + 1);
  19387. digits[0] = 0;
  19388. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  19389. }
  19390. if (digit >= 5) {
  19391. if (roundAt - 1 < 0) {
  19392. for (var k = 0; k > roundAt; k--) {
  19393. digits.unshift(0);
  19394. parsedNumber.i++;
  19395. }
  19396. digits.unshift(1);
  19397. parsedNumber.i++;
  19398. } else {
  19399. digits[roundAt - 1]++;
  19400. }
  19401. }
  19402. // Pad out with zeros to get the required fraction length
  19403. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  19404. // Do any carrying, e.g. a digit was rounded up to 10
  19405. var carry = digits.reduceRight(function(carry, d, i, digits) {
  19406. d = d + carry;
  19407. digits[i] = d % 10;
  19408. return Math.floor(d / 10);
  19409. }, 0);
  19410. if (carry) {
  19411. digits.unshift(carry);
  19412. parsedNumber.i++;
  19413. }
  19414. }
  19415. /**
  19416. * Format a number into a string
  19417. * @param {number} number The number to format
  19418. * @param {{
  19419. * minFrac, // the minimum number of digits required in the fraction part of the number
  19420. * maxFrac, // the maximum number of digits required in the fraction part of the number
  19421. * gSize, // number of digits in each group of separated digits
  19422. * lgSize, // number of digits in the last group of digits before the decimal separator
  19423. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  19424. * posPre, // the string to go in front of a positive number
  19425. * negSuf, // the string to go after a negative number (e.g. `)`)
  19426. * posSuf // the string to go after a positive number
  19427. * }} pattern
  19428. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  19429. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  19430. * @param {[type]} fractionSize The size of the fractional part of the number
  19431. * @return {string} The number formatted as a string
  19432. */
  19433. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  19434. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  19435. var isInfinity = !isFinite(number);
  19436. var isZero = false;
  19437. var numStr = Math.abs(number) + '',
  19438. formattedText = '',
  19439. parsedNumber;
  19440. if (isInfinity) {
  19441. formattedText = '\u221e';
  19442. } else {
  19443. parsedNumber = parse(numStr);
  19444. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  19445. var digits = parsedNumber.d;
  19446. var integerLen = parsedNumber.i;
  19447. var exponent = parsedNumber.e;
  19448. var decimals = [];
  19449. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  19450. // pad zeros for small numbers
  19451. while (integerLen < 0) {
  19452. digits.unshift(0);
  19453. integerLen++;
  19454. }
  19455. // extract decimals digits
  19456. if (integerLen > 0) {
  19457. decimals = digits.splice(integerLen, digits.length);
  19458. } else {
  19459. decimals = digits;
  19460. digits = [0];
  19461. }
  19462. // format the integer digits with grouping separators
  19463. var groups = [];
  19464. if (digits.length >= pattern.lgSize) {
  19465. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  19466. }
  19467. while (digits.length > pattern.gSize) {
  19468. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  19469. }
  19470. if (digits.length) {
  19471. groups.unshift(digits.join(''));
  19472. }
  19473. formattedText = groups.join(groupSep);
  19474. // append the decimal digits
  19475. if (decimals.length) {
  19476. formattedText += decimalSep + decimals.join('');
  19477. }
  19478. if (exponent) {
  19479. formattedText += 'e+' + exponent;
  19480. }
  19481. }
  19482. if (number < 0 && !isZero) {
  19483. return pattern.negPre + formattedText + pattern.negSuf;
  19484. } else {
  19485. return pattern.posPre + formattedText + pattern.posSuf;
  19486. }
  19487. }
  19488. function padNumber(num, digits, trim, negWrap) {
  19489. var neg = '';
  19490. if (num < 0 || (negWrap && num <= 0)) {
  19491. if (negWrap) {
  19492. num = -num + 1;
  19493. } else {
  19494. num = -num;
  19495. neg = '-';
  19496. }
  19497. }
  19498. num = '' + num;
  19499. while (num.length < digits) num = ZERO_CHAR + num;
  19500. if (trim) {
  19501. num = num.substr(num.length - digits);
  19502. }
  19503. return neg + num;
  19504. }
  19505. function dateGetter(name, size, offset, trim, negWrap) {
  19506. offset = offset || 0;
  19507. return function(date) {
  19508. var value = date['get' + name]();
  19509. if (offset > 0 || value > -offset) {
  19510. value += offset;
  19511. }
  19512. if (value === 0 && offset === -12) value = 12;
  19513. return padNumber(value, size, trim, negWrap);
  19514. };
  19515. }
  19516. function dateStrGetter(name, shortForm, standAlone) {
  19517. return function(date, formats) {
  19518. var value = date['get' + name]();
  19519. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  19520. var get = uppercase(propPrefix + name);
  19521. return formats[get][value];
  19522. };
  19523. }
  19524. function timeZoneGetter(date, formats, offset) {
  19525. var zone = -1 * offset;
  19526. var paddedZone = (zone >= 0) ? '+' : '';
  19527. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  19528. padNumber(Math.abs(zone % 60), 2);
  19529. return paddedZone;
  19530. }
  19531. function getFirstThursdayOfYear(year) {
  19532. // 0 = index of January
  19533. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  19534. // 4 = index of Thursday (+1 to account for 1st = 5)
  19535. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  19536. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  19537. }
  19538. function getThursdayThisWeek(datetime) {
  19539. return new Date(datetime.getFullYear(), datetime.getMonth(),
  19540. // 4 = index of Thursday
  19541. datetime.getDate() + (4 - datetime.getDay()));
  19542. }
  19543. function weekGetter(size) {
  19544. return function(date) {
  19545. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  19546. thisThurs = getThursdayThisWeek(date);
  19547. var diff = +thisThurs - +firstThurs,
  19548. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  19549. return padNumber(result, size);
  19550. };
  19551. }
  19552. function ampmGetter(date, formats) {
  19553. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  19554. }
  19555. function eraGetter(date, formats) {
  19556. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  19557. }
  19558. function longEraGetter(date, formats) {
  19559. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  19560. }
  19561. var DATE_FORMATS = {
  19562. yyyy: dateGetter('FullYear', 4, 0, false, true),
  19563. yy: dateGetter('FullYear', 2, 0, true, true),
  19564. y: dateGetter('FullYear', 1, 0, false, true),
  19565. MMMM: dateStrGetter('Month'),
  19566. MMM: dateStrGetter('Month', true),
  19567. MM: dateGetter('Month', 2, 1),
  19568. M: dateGetter('Month', 1, 1),
  19569. LLLL: dateStrGetter('Month', false, true),
  19570. dd: dateGetter('Date', 2),
  19571. d: dateGetter('Date', 1),
  19572. HH: dateGetter('Hours', 2),
  19573. H: dateGetter('Hours', 1),
  19574. hh: dateGetter('Hours', 2, -12),
  19575. h: dateGetter('Hours', 1, -12),
  19576. mm: dateGetter('Minutes', 2),
  19577. m: dateGetter('Minutes', 1),
  19578. ss: dateGetter('Seconds', 2),
  19579. s: dateGetter('Seconds', 1),
  19580. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  19581. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  19582. sss: dateGetter('Milliseconds', 3),
  19583. EEEE: dateStrGetter('Day'),
  19584. EEE: dateStrGetter('Day', true),
  19585. a: ampmGetter,
  19586. Z: timeZoneGetter,
  19587. ww: weekGetter(2),
  19588. w: weekGetter(1),
  19589. G: eraGetter,
  19590. GG: eraGetter,
  19591. GGG: eraGetter,
  19592. GGGG: longEraGetter
  19593. };
  19594. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\s\S]*)/,
  19595. NUMBER_STRING = /^-?\d+$/;
  19596. /**
  19597. * @ngdoc filter
  19598. * @name date
  19599. * @kind function
  19600. *
  19601. * @description
  19602. * Formats `date` to a string based on the requested `format`.
  19603. *
  19604. * `format` string can be composed of the following elements:
  19605. *
  19606. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  19607. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  19608. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  19609. * * `'MMMM'`: Month in year (January-December)
  19610. * * `'MMM'`: Month in year (Jan-Dec)
  19611. * * `'MM'`: Month in year, padded (01-12)
  19612. * * `'M'`: Month in year (1-12)
  19613. * * `'LLLL'`: Stand-alone month in year (January-December)
  19614. * * `'dd'`: Day in month, padded (01-31)
  19615. * * `'d'`: Day in month (1-31)
  19616. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  19617. * * `'EEE'`: Day in Week, (Sun-Sat)
  19618. * * `'HH'`: Hour in day, padded (00-23)
  19619. * * `'H'`: Hour in day (0-23)
  19620. * * `'hh'`: Hour in AM/PM, padded (01-12)
  19621. * * `'h'`: Hour in AM/PM, (1-12)
  19622. * * `'mm'`: Minute in hour, padded (00-59)
  19623. * * `'m'`: Minute in hour (0-59)
  19624. * * `'ss'`: Second in minute, padded (00-59)
  19625. * * `'s'`: Second in minute (0-59)
  19626. * * `'sss'`: Millisecond in second, padded (000-999)
  19627. * * `'a'`: AM/PM marker
  19628. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  19629. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  19630. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  19631. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  19632. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  19633. *
  19634. * `format` string can also be one of the following predefined
  19635. * {@link guide/i18n localizable formats}:
  19636. *
  19637. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  19638. * (e.g. Sep 3, 2010 12:05:08 PM)
  19639. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  19640. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  19641. * (e.g. Friday, September 3, 2010)
  19642. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  19643. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  19644. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  19645. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  19646. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  19647. *
  19648. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  19649. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  19650. * (e.g. `"h 'o''clock'"`).
  19651. *
  19652. * Any other characters in the `format` string will be output as-is.
  19653. *
  19654. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  19655. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  19656. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  19657. * specified in the string input, the time is considered to be in the local timezone.
  19658. * @param {string=} format Formatting rules (see Description). If not specified,
  19659. * `mediumDate` is used.
  19660. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  19661. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  19662. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  19663. * If not specified, the timezone of the browser will be used.
  19664. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  19665. *
  19666. * @example
  19667. <example name="filter-date">
  19668. <file name="index.html">
  19669. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  19670. <span>{{1288323623006 | date:'medium'}}</span><br>
  19671. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  19672. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  19673. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  19674. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  19675. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  19676. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  19677. </file>
  19678. <file name="protractor.js" type="protractor">
  19679. it('should format date', function() {
  19680. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  19681. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  19682. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  19683. toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
  19684. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  19685. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  19686. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  19687. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  19688. });
  19689. </file>
  19690. </example>
  19691. */
  19692. dateFilter.$inject = ['$locale'];
  19693. function dateFilter($locale) {
  19694. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  19695. // 1 2 3 4 5 6 7 8 9 10 11
  19696. function jsonStringToDate(string) {
  19697. var match;
  19698. if ((match = string.match(R_ISO8601_STR))) {
  19699. var date = new Date(0),
  19700. tzHour = 0,
  19701. tzMin = 0,
  19702. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  19703. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  19704. if (match[9]) {
  19705. tzHour = toInt(match[9] + match[10]);
  19706. tzMin = toInt(match[9] + match[11]);
  19707. }
  19708. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  19709. var h = toInt(match[4] || 0) - tzHour;
  19710. var m = toInt(match[5] || 0) - tzMin;
  19711. var s = toInt(match[6] || 0);
  19712. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  19713. timeSetter.call(date, h, m, s, ms);
  19714. return date;
  19715. }
  19716. return string;
  19717. }
  19718. return function(date, format, timezone) {
  19719. var text = '',
  19720. parts = [],
  19721. fn, match;
  19722. format = format || 'mediumDate';
  19723. format = $locale.DATETIME_FORMATS[format] || format;
  19724. if (isString(date)) {
  19725. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  19726. }
  19727. if (isNumber(date)) {
  19728. date = new Date(date);
  19729. }
  19730. if (!isDate(date) || !isFinite(date.getTime())) {
  19731. return date;
  19732. }
  19733. while (format) {
  19734. match = DATE_FORMATS_SPLIT.exec(format);
  19735. if (match) {
  19736. parts = concat(parts, match, 1);
  19737. format = parts.pop();
  19738. } else {
  19739. parts.push(format);
  19740. format = null;
  19741. }
  19742. }
  19743. var dateTimezoneOffset = date.getTimezoneOffset();
  19744. if (timezone) {
  19745. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  19746. date = convertTimezoneToLocal(date, timezone, true);
  19747. }
  19748. forEach(parts, function(value) {
  19749. fn = DATE_FORMATS[value];
  19750. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  19751. : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
  19752. });
  19753. return text;
  19754. };
  19755. }
  19756. /**
  19757. * @ngdoc filter
  19758. * @name json
  19759. * @kind function
  19760. *
  19761. * @description
  19762. * Allows you to convert a JavaScript object into JSON string.
  19763. *
  19764. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  19765. * the binding is automatically converted to JSON.
  19766. *
  19767. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  19768. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  19769. * @returns {string} JSON string.
  19770. *
  19771. *
  19772. * @example
  19773. <example name="filter-json">
  19774. <file name="index.html">
  19775. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  19776. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  19777. </file>
  19778. <file name="protractor.js" type="protractor">
  19779. it('should jsonify filtered objects', function() {
  19780. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
  19781. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
  19782. });
  19783. </file>
  19784. </example>
  19785. *
  19786. */
  19787. function jsonFilter() {
  19788. return function(object, spacing) {
  19789. if (isUndefined(spacing)) {
  19790. spacing = 2;
  19791. }
  19792. return toJson(object, spacing);
  19793. };
  19794. }
  19795. /**
  19796. * @ngdoc filter
  19797. * @name lowercase
  19798. * @kind function
  19799. * @description
  19800. * Converts string to lowercase.
  19801. *
  19802. * See the {@link ng.uppercase uppercase filter documentation} for a functionally identical example.
  19803. *
  19804. * @see angular.lowercase
  19805. */
  19806. var lowercaseFilter = valueFn(lowercase);
  19807. /**
  19808. * @ngdoc filter
  19809. * @name uppercase
  19810. * @kind function
  19811. * @description
  19812. * Converts string to uppercase.
  19813. * @example
  19814. <example module="uppercaseFilterExample" name="filter-uppercase">
  19815. <file name="index.html">
  19816. <script>
  19817. angular.module('uppercaseFilterExample', [])
  19818. .controller('ExampleController', ['$scope', function($scope) {
  19819. $scope.title = 'This is a title';
  19820. }]);
  19821. </script>
  19822. <div ng-controller="ExampleController">
  19823. <!-- This title should be formatted normally -->
  19824. <h1>{{title}}</h1>
  19825. <!-- This title should be capitalized -->
  19826. <h1>{{title | uppercase}}</h1>
  19827. </div>
  19828. </file>
  19829. </example>
  19830. */
  19831. var uppercaseFilter = valueFn(uppercase);
  19832. /**
  19833. * @ngdoc filter
  19834. * @name limitTo
  19835. * @kind function
  19836. *
  19837. * @description
  19838. * Creates a new array or string containing only a specified number of elements. The elements are
  19839. * taken from either the beginning or the end of the source array, string or number, as specified by
  19840. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  19841. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  19842. * it is converted to a string.
  19843. *
  19844. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  19845. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  19846. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  19847. * If the number is negative, `limit` number of items from the end of the source array/string
  19848. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  19849. * the input will be returned unchanged.
  19850. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  19851. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  19852. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  19853. * less than `limit` elements.
  19854. *
  19855. * @example
  19856. <example module="limitToExample" name="limit-to-filter">
  19857. <file name="index.html">
  19858. <script>
  19859. angular.module('limitToExample', [])
  19860. .controller('ExampleController', ['$scope', function($scope) {
  19861. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  19862. $scope.letters = "abcdefghi";
  19863. $scope.longNumber = 2345432342;
  19864. $scope.numLimit = 3;
  19865. $scope.letterLimit = 3;
  19866. $scope.longNumberLimit = 3;
  19867. }]);
  19868. </script>
  19869. <div ng-controller="ExampleController">
  19870. <label>
  19871. Limit {{numbers}} to:
  19872. <input type="number" step="1" ng-model="numLimit">
  19873. </label>
  19874. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  19875. <label>
  19876. Limit {{letters}} to:
  19877. <input type="number" step="1" ng-model="letterLimit">
  19878. </label>
  19879. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  19880. <label>
  19881. Limit {{longNumber}} to:
  19882. <input type="number" step="1" ng-model="longNumberLimit">
  19883. </label>
  19884. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  19885. </div>
  19886. </file>
  19887. <file name="protractor.js" type="protractor">
  19888. var numLimitInput = element(by.model('numLimit'));
  19889. var letterLimitInput = element(by.model('letterLimit'));
  19890. var longNumberLimitInput = element(by.model('longNumberLimit'));
  19891. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  19892. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  19893. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  19894. it('should limit the number array to first three items', function() {
  19895. expect(numLimitInput.getAttribute('value')).toBe('3');
  19896. expect(letterLimitInput.getAttribute('value')).toBe('3');
  19897. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  19898. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  19899. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  19900. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  19901. });
  19902. // There is a bug in safari and protractor that doesn't like the minus key
  19903. // it('should update the output when -3 is entered', function() {
  19904. // numLimitInput.clear();
  19905. // numLimitInput.sendKeys('-3');
  19906. // letterLimitInput.clear();
  19907. // letterLimitInput.sendKeys('-3');
  19908. // longNumberLimitInput.clear();
  19909. // longNumberLimitInput.sendKeys('-3');
  19910. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  19911. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  19912. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  19913. // });
  19914. it('should not exceed the maximum size of input array', function() {
  19915. numLimitInput.clear();
  19916. numLimitInput.sendKeys('100');
  19917. letterLimitInput.clear();
  19918. letterLimitInput.sendKeys('100');
  19919. longNumberLimitInput.clear();
  19920. longNumberLimitInput.sendKeys('100');
  19921. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  19922. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  19923. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  19924. });
  19925. </file>
  19926. </example>
  19927. */
  19928. function limitToFilter() {
  19929. return function(input, limit, begin) {
  19930. if (Math.abs(Number(limit)) === Infinity) {
  19931. limit = Number(limit);
  19932. } else {
  19933. limit = toInt(limit);
  19934. }
  19935. if (isNumberNaN(limit)) return input;
  19936. if (isNumber(input)) input = input.toString();
  19937. if (!isArrayLike(input)) return input;
  19938. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  19939. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  19940. if (limit >= 0) {
  19941. return sliceFn(input, begin, begin + limit);
  19942. } else {
  19943. if (begin === 0) {
  19944. return sliceFn(input, limit, input.length);
  19945. } else {
  19946. return sliceFn(input, Math.max(0, begin + limit), begin);
  19947. }
  19948. }
  19949. };
  19950. }
  19951. function sliceFn(input, begin, end) {
  19952. if (isString(input)) return input.slice(begin, end);
  19953. return slice.call(input, begin, end);
  19954. }
  19955. /**
  19956. * @ngdoc filter
  19957. * @name orderBy
  19958. * @kind function
  19959. *
  19960. * @description
  19961. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  19962. * function based on the values computed using the `expression` predicate.
  19963. *
  19964. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  19965. * `[{id: 'bar'}, {id: 'foo'}]`.
  19966. *
  19967. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  19968. * String, etc).
  19969. *
  19970. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  19971. * for the preceding one. The `expression` is evaluated against each item and the output is used
  19972. * for comparing with other items.
  19973. *
  19974. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  19975. * ascending order.
  19976. *
  19977. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  19978. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  19979. * strings alphabetically).
  19980. *
  19981. * ### Under the hood
  19982. *
  19983. * Ordering the specified `collection` happens in two phases:
  19984. *
  19985. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  19986. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  19987. * through a predicate that extracts the value of the `label` property, would be transformed to:
  19988. * ```
  19989. * {
  19990. * value: 'foo',
  19991. * type: 'string',
  19992. * index: ...
  19993. * }
  19994. * ```
  19995. * 2. The comparator function is used to sort the items, based on the derived values, types and
  19996. * indices.
  19997. *
  19998. * If you use a custom comparator, it will be called with pairs of objects of the form
  19999. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  20000. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  20001. * second, or `1` otherwise.
  20002. *
  20003. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  20004. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  20005. * dummy predicate that returns the item's index as `value`.
  20006. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  20007. *
  20008. * If a custom comparator still can't distinguish between two items, then they will be sorted based
  20009. * on their index using the built-in comparator.
  20010. *
  20011. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  20012. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  20013. * it to the comparator. The following rules govern the conversion:
  20014. *
  20015. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  20016. * used instead.<br />
  20017. * (If the object has a `valueOf()` method that returns another object, then the returned object
  20018. * will be used in subsequent steps.)
  20019. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  20020. * returns a primitive, its return value will be used instead.<br />
  20021. * (If the object has a `toString()` method that returns another object, then the returned object
  20022. * will be used in subsequent steps.)
  20023. * 3. No conversion; the object itself is used.
  20024. *
  20025. * ### The default comparator
  20026. *
  20027. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  20028. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  20029. * using their index in the original collection, and sorts values of different types by type.
  20030. *
  20031. * More specifically, it follows these steps to determine the relative order of items:
  20032. *
  20033. * 1. If the compared values are of different types, compare the types themselves alphabetically.
  20034. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  20035. * locale-insensitive way.
  20036. * 3. If both values are objects, compare their indices instead.
  20037. * 4. Otherwise, return:
  20038. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  20039. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  20040. * - `1`, otherwise.
  20041. *
  20042. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  20043. * saved as numbers and not strings.
  20044. * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e.
  20045. * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to
  20046. * other values.
  20047. *
  20048. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  20049. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  20050. * predicates) to be used by the comparator to determine the order of elements.
  20051. *
  20052. * Can be one of:
  20053. *
  20054. * - `Function`: A getter function. This function will be called with each item as argument and
  20055. * the return value will be used for sorting.
  20056. * - `string`: An Angular expression. This expression will be evaluated against each item and the
  20057. * result will be used for sorting. For example, use `'label'` to sort by a property called
  20058. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  20059. * property.<br />
  20060. * (The result of a constant expression is interpreted as a property name to be used for
  20061. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  20062. * property called `special name`.)<br />
  20063. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  20064. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  20065. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  20066. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  20067. * relative order of two items, the next predicate is used as a tie-breaker.
  20068. *
  20069. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  20070. *
  20071. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  20072. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  20073. * value pairs. If omitted, the built-in comparator will be used.
  20074. *
  20075. * @returns {Array} - The sorted array.
  20076. *
  20077. *
  20078. * @example
  20079. * ### Ordering a table with `ngRepeat`
  20080. *
  20081. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  20082. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  20083. * it defaults to the built-in comparator.
  20084. *
  20085. <example name="orderBy-static" module="orderByExample1">
  20086. <file name="index.html">
  20087. <div ng-controller="ExampleController">
  20088. <table class="friends">
  20089. <tr>
  20090. <th>Name</th>
  20091. <th>Phone Number</th>
  20092. <th>Age</th>
  20093. </tr>
  20094. <tr ng-repeat="friend in friends | orderBy:'-age'">
  20095. <td>{{friend.name}}</td>
  20096. <td>{{friend.phone}}</td>
  20097. <td>{{friend.age}}</td>
  20098. </tr>
  20099. </table>
  20100. </div>
  20101. </file>
  20102. <file name="script.js">
  20103. angular.module('orderByExample1', [])
  20104. .controller('ExampleController', ['$scope', function($scope) {
  20105. $scope.friends = [
  20106. {name: 'John', phone: '555-1212', age: 10},
  20107. {name: 'Mary', phone: '555-9876', age: 19},
  20108. {name: 'Mike', phone: '555-4321', age: 21},
  20109. {name: 'Adam', phone: '555-5678', age: 35},
  20110. {name: 'Julie', phone: '555-8765', age: 29}
  20111. ];
  20112. }]);
  20113. </file>
  20114. <file name="style.css">
  20115. .friends {
  20116. border-collapse: collapse;
  20117. }
  20118. .friends th {
  20119. border-bottom: 1px solid;
  20120. }
  20121. .friends td, .friends th {
  20122. border-left: 1px solid;
  20123. padding: 5px 10px;
  20124. }
  20125. .friends td:first-child, .friends th:first-child {
  20126. border-left: none;
  20127. }
  20128. </file>
  20129. <file name="protractor.js" type="protractor">
  20130. // Element locators
  20131. var names = element.all(by.repeater('friends').column('friend.name'));
  20132. it('should sort friends by age in reverse order', function() {
  20133. expect(names.get(0).getText()).toBe('Adam');
  20134. expect(names.get(1).getText()).toBe('Julie');
  20135. expect(names.get(2).getText()).toBe('Mike');
  20136. expect(names.get(3).getText()).toBe('Mary');
  20137. expect(names.get(4).getText()).toBe('John');
  20138. });
  20139. </file>
  20140. </example>
  20141. * <hr />
  20142. *
  20143. * @example
  20144. * ### Changing parameters dynamically
  20145. *
  20146. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  20147. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  20148. *
  20149. <example name="orderBy-dynamic" module="orderByExample2">
  20150. <file name="index.html">
  20151. <div ng-controller="ExampleController">
  20152. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  20153. <hr/>
  20154. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  20155. <hr/>
  20156. <table class="friends">
  20157. <tr>
  20158. <th>
  20159. <button ng-click="sortBy('name')">Name</button>
  20160. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  20161. </th>
  20162. <th>
  20163. <button ng-click="sortBy('phone')">Phone Number</button>
  20164. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  20165. </th>
  20166. <th>
  20167. <button ng-click="sortBy('age')">Age</button>
  20168. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  20169. </th>
  20170. </tr>
  20171. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  20172. <td>{{friend.name}}</td>
  20173. <td>{{friend.phone}}</td>
  20174. <td>{{friend.age}}</td>
  20175. </tr>
  20176. </table>
  20177. </div>
  20178. </file>
  20179. <file name="script.js">
  20180. angular.module('orderByExample2', [])
  20181. .controller('ExampleController', ['$scope', function($scope) {
  20182. var friends = [
  20183. {name: 'John', phone: '555-1212', age: 10},
  20184. {name: 'Mary', phone: '555-9876', age: 19},
  20185. {name: 'Mike', phone: '555-4321', age: 21},
  20186. {name: 'Adam', phone: '555-5678', age: 35},
  20187. {name: 'Julie', phone: '555-8765', age: 29}
  20188. ];
  20189. $scope.propertyName = 'age';
  20190. $scope.reverse = true;
  20191. $scope.friends = friends;
  20192. $scope.sortBy = function(propertyName) {
  20193. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  20194. $scope.propertyName = propertyName;
  20195. };
  20196. }]);
  20197. </file>
  20198. <file name="style.css">
  20199. .friends {
  20200. border-collapse: collapse;
  20201. }
  20202. .friends th {
  20203. border-bottom: 1px solid;
  20204. }
  20205. .friends td, .friends th {
  20206. border-left: 1px solid;
  20207. padding: 5px 10px;
  20208. }
  20209. .friends td:first-child, .friends th:first-child {
  20210. border-left: none;
  20211. }
  20212. .sortorder:after {
  20213. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  20214. }
  20215. .sortorder.reverse:after {
  20216. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  20217. }
  20218. </file>
  20219. <file name="protractor.js" type="protractor">
  20220. // Element locators
  20221. var unsortButton = element(by.partialButtonText('unsorted'));
  20222. var nameHeader = element(by.partialButtonText('Name'));
  20223. var phoneHeader = element(by.partialButtonText('Phone'));
  20224. var ageHeader = element(by.partialButtonText('Age'));
  20225. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  20226. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  20227. it('should sort friends by some property, when clicking on the column header', function() {
  20228. expect(firstName.getText()).toBe('Adam');
  20229. expect(lastName.getText()).toBe('John');
  20230. phoneHeader.click();
  20231. expect(firstName.getText()).toBe('John');
  20232. expect(lastName.getText()).toBe('Mary');
  20233. nameHeader.click();
  20234. expect(firstName.getText()).toBe('Adam');
  20235. expect(lastName.getText()).toBe('Mike');
  20236. ageHeader.click();
  20237. expect(firstName.getText()).toBe('John');
  20238. expect(lastName.getText()).toBe('Adam');
  20239. });
  20240. it('should sort friends in reverse order, when clicking on the same column', function() {
  20241. expect(firstName.getText()).toBe('Adam');
  20242. expect(lastName.getText()).toBe('John');
  20243. ageHeader.click();
  20244. expect(firstName.getText()).toBe('John');
  20245. expect(lastName.getText()).toBe('Adam');
  20246. ageHeader.click();
  20247. expect(firstName.getText()).toBe('Adam');
  20248. expect(lastName.getText()).toBe('John');
  20249. });
  20250. it('should restore the original order, when clicking "Set to unsorted"', function() {
  20251. expect(firstName.getText()).toBe('Adam');
  20252. expect(lastName.getText()).toBe('John');
  20253. unsortButton.click();
  20254. expect(firstName.getText()).toBe('John');
  20255. expect(lastName.getText()).toBe('Julie');
  20256. });
  20257. </file>
  20258. </example>
  20259. * <hr />
  20260. *
  20261. * @example
  20262. * ### Using `orderBy` inside a controller
  20263. *
  20264. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  20265. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  20266. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  20267. *
  20268. <example name="orderBy-call-manually" module="orderByExample3">
  20269. <file name="index.html">
  20270. <div ng-controller="ExampleController">
  20271. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  20272. <hr/>
  20273. <button ng-click="sortBy(null)">Set to unsorted</button>
  20274. <hr/>
  20275. <table class="friends">
  20276. <tr>
  20277. <th>
  20278. <button ng-click="sortBy('name')">Name</button>
  20279. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  20280. </th>
  20281. <th>
  20282. <button ng-click="sortBy('phone')">Phone Number</button>
  20283. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  20284. </th>
  20285. <th>
  20286. <button ng-click="sortBy('age')">Age</button>
  20287. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  20288. </th>
  20289. </tr>
  20290. <tr ng-repeat="friend in friends">
  20291. <td>{{friend.name}}</td>
  20292. <td>{{friend.phone}}</td>
  20293. <td>{{friend.age}}</td>
  20294. </tr>
  20295. </table>
  20296. </div>
  20297. </file>
  20298. <file name="script.js">
  20299. angular.module('orderByExample3', [])
  20300. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  20301. var friends = [
  20302. {name: 'John', phone: '555-1212', age: 10},
  20303. {name: 'Mary', phone: '555-9876', age: 19},
  20304. {name: 'Mike', phone: '555-4321', age: 21},
  20305. {name: 'Adam', phone: '555-5678', age: 35},
  20306. {name: 'Julie', phone: '555-8765', age: 29}
  20307. ];
  20308. $scope.propertyName = 'age';
  20309. $scope.reverse = true;
  20310. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  20311. $scope.sortBy = function(propertyName) {
  20312. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  20313. ? !$scope.reverse : false;
  20314. $scope.propertyName = propertyName;
  20315. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  20316. };
  20317. }]);
  20318. </file>
  20319. <file name="style.css">
  20320. .friends {
  20321. border-collapse: collapse;
  20322. }
  20323. .friends th {
  20324. border-bottom: 1px solid;
  20325. }
  20326. .friends td, .friends th {
  20327. border-left: 1px solid;
  20328. padding: 5px 10px;
  20329. }
  20330. .friends td:first-child, .friends th:first-child {
  20331. border-left: none;
  20332. }
  20333. .sortorder:after {
  20334. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  20335. }
  20336. .sortorder.reverse:after {
  20337. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  20338. }
  20339. </file>
  20340. <file name="protractor.js" type="protractor">
  20341. // Element locators
  20342. var unsortButton = element(by.partialButtonText('unsorted'));
  20343. var nameHeader = element(by.partialButtonText('Name'));
  20344. var phoneHeader = element(by.partialButtonText('Phone'));
  20345. var ageHeader = element(by.partialButtonText('Age'));
  20346. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  20347. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  20348. it('should sort friends by some property, when clicking on the column header', function() {
  20349. expect(firstName.getText()).toBe('Adam');
  20350. expect(lastName.getText()).toBe('John');
  20351. phoneHeader.click();
  20352. expect(firstName.getText()).toBe('John');
  20353. expect(lastName.getText()).toBe('Mary');
  20354. nameHeader.click();
  20355. expect(firstName.getText()).toBe('Adam');
  20356. expect(lastName.getText()).toBe('Mike');
  20357. ageHeader.click();
  20358. expect(firstName.getText()).toBe('John');
  20359. expect(lastName.getText()).toBe('Adam');
  20360. });
  20361. it('should sort friends in reverse order, when clicking on the same column', function() {
  20362. expect(firstName.getText()).toBe('Adam');
  20363. expect(lastName.getText()).toBe('John');
  20364. ageHeader.click();
  20365. expect(firstName.getText()).toBe('John');
  20366. expect(lastName.getText()).toBe('Adam');
  20367. ageHeader.click();
  20368. expect(firstName.getText()).toBe('Adam');
  20369. expect(lastName.getText()).toBe('John');
  20370. });
  20371. it('should restore the original order, when clicking "Set to unsorted"', function() {
  20372. expect(firstName.getText()).toBe('Adam');
  20373. expect(lastName.getText()).toBe('John');
  20374. unsortButton.click();
  20375. expect(firstName.getText()).toBe('John');
  20376. expect(lastName.getText()).toBe('Julie');
  20377. });
  20378. </file>
  20379. </example>
  20380. * <hr />
  20381. *
  20382. * @example
  20383. * ### Using a custom comparator
  20384. *
  20385. * If you have very specific requirements about the way items are sorted, you can pass your own
  20386. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  20387. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  20388. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  20389. *
  20390. <example name="orderBy-custom-comparator" module="orderByExample4">
  20391. <file name="index.html">
  20392. <div ng-controller="ExampleController">
  20393. <div class="friends-container custom-comparator">
  20394. <h3>Locale-sensitive Comparator</h3>
  20395. <table class="friends">
  20396. <tr>
  20397. <th>Name</th>
  20398. <th>Favorite Letter</th>
  20399. </tr>
  20400. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  20401. <td>{{friend.name}}</td>
  20402. <td>{{friend.favoriteLetter}}</td>
  20403. </tr>
  20404. </table>
  20405. </div>
  20406. <div class="friends-container default-comparator">
  20407. <h3>Default Comparator</h3>
  20408. <table class="friends">
  20409. <tr>
  20410. <th>Name</th>
  20411. <th>Favorite Letter</th>
  20412. </tr>
  20413. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  20414. <td>{{friend.name}}</td>
  20415. <td>{{friend.favoriteLetter}}</td>
  20416. </tr>
  20417. </table>
  20418. </div>
  20419. </div>
  20420. </file>
  20421. <file name="script.js">
  20422. angular.module('orderByExample4', [])
  20423. .controller('ExampleController', ['$scope', function($scope) {
  20424. $scope.friends = [
  20425. {name: 'John', favoriteLetter: 'Ä'},
  20426. {name: 'Mary', favoriteLetter: 'Ü'},
  20427. {name: 'Mike', favoriteLetter: 'Ö'},
  20428. {name: 'Adam', favoriteLetter: 'H'},
  20429. {name: 'Julie', favoriteLetter: 'Z'}
  20430. ];
  20431. $scope.localeSensitiveComparator = function(v1, v2) {
  20432. // If we don't get strings, just compare by index
  20433. if (v1.type !== 'string' || v2.type !== 'string') {
  20434. return (v1.index < v2.index) ? -1 : 1;
  20435. }
  20436. // Compare strings alphabetically, taking locale into account
  20437. return v1.value.localeCompare(v2.value);
  20438. };
  20439. }]);
  20440. </file>
  20441. <file name="style.css">
  20442. .friends-container {
  20443. display: inline-block;
  20444. margin: 0 30px;
  20445. }
  20446. .friends {
  20447. border-collapse: collapse;
  20448. }
  20449. .friends th {
  20450. border-bottom: 1px solid;
  20451. }
  20452. .friends td, .friends th {
  20453. border-left: 1px solid;
  20454. padding: 5px 10px;
  20455. }
  20456. .friends td:first-child, .friends th:first-child {
  20457. border-left: none;
  20458. }
  20459. </file>
  20460. <file name="protractor.js" type="protractor">
  20461. // Element locators
  20462. var container = element(by.css('.custom-comparator'));
  20463. var names = container.all(by.repeater('friends').column('friend.name'));
  20464. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  20465. expect(names.get(0).getText()).toBe('John');
  20466. expect(names.get(1).getText()).toBe('Adam');
  20467. expect(names.get(2).getText()).toBe('Mike');
  20468. expect(names.get(3).getText()).toBe('Mary');
  20469. expect(names.get(4).getText()).toBe('Julie');
  20470. });
  20471. </file>
  20472. </example>
  20473. *
  20474. */
  20475. orderByFilter.$inject = ['$parse'];
  20476. function orderByFilter($parse) {
  20477. return function(array, sortPredicate, reverseOrder, compareFn) {
  20478. if (array == null) return array;
  20479. if (!isArrayLike(array)) {
  20480. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  20481. }
  20482. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  20483. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  20484. var predicates = processPredicates(sortPredicate);
  20485. var descending = reverseOrder ? -1 : 1;
  20486. // Define the `compare()` function. Use a default comparator if none is specified.
  20487. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  20488. // The next three lines are a version of a Swartzian Transform idiom from Perl
  20489. // (sometimes called the Decorate-Sort-Undecorate idiom)
  20490. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  20491. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  20492. compareValues.sort(doComparison);
  20493. array = compareValues.map(function(item) { return item.value; });
  20494. return array;
  20495. function getComparisonObject(value, index) {
  20496. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  20497. // This will be used to keep the sort stable when none of the input predicates can
  20498. // distinguish between two elements.
  20499. return {
  20500. value: value,
  20501. tieBreaker: {value: index, type: 'number', index: index},
  20502. predicateValues: predicates.map(function(predicate) {
  20503. return getPredicateValue(predicate.get(value), index);
  20504. })
  20505. };
  20506. }
  20507. function doComparison(v1, v2) {
  20508. for (var i = 0, ii = predicates.length; i < ii; i++) {
  20509. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  20510. if (result) {
  20511. return result * predicates[i].descending * descending;
  20512. }
  20513. }
  20514. return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending;
  20515. }
  20516. };
  20517. function processPredicates(sortPredicates) {
  20518. return sortPredicates.map(function(predicate) {
  20519. var descending = 1, get = identity;
  20520. if (isFunction(predicate)) {
  20521. get = predicate;
  20522. } else if (isString(predicate)) {
  20523. if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
  20524. descending = predicate.charAt(0) === '-' ? -1 : 1;
  20525. predicate = predicate.substring(1);
  20526. }
  20527. if (predicate !== '') {
  20528. get = $parse(predicate);
  20529. if (get.constant) {
  20530. var key = get();
  20531. get = function(value) { return value[key]; };
  20532. }
  20533. }
  20534. }
  20535. return {get: get, descending: descending};
  20536. });
  20537. }
  20538. function isPrimitive(value) {
  20539. switch (typeof value) {
  20540. case 'number': /* falls through */
  20541. case 'boolean': /* falls through */
  20542. case 'string':
  20543. return true;
  20544. default:
  20545. return false;
  20546. }
  20547. }
  20548. function objectValue(value) {
  20549. // If `valueOf` is a valid function use that
  20550. if (isFunction(value.valueOf)) {
  20551. value = value.valueOf();
  20552. if (isPrimitive(value)) return value;
  20553. }
  20554. // If `toString` is a valid function and not the one from `Object.prototype` use that
  20555. if (hasCustomToString(value)) {
  20556. value = value.toString();
  20557. if (isPrimitive(value)) return value;
  20558. }
  20559. return value;
  20560. }
  20561. function getPredicateValue(value, index) {
  20562. var type = typeof value;
  20563. if (value === null) {
  20564. type = 'string';
  20565. value = 'null';
  20566. } else if (type === 'object') {
  20567. value = objectValue(value);
  20568. }
  20569. return {value: value, type: type, index: index};
  20570. }
  20571. function defaultCompare(v1, v2) {
  20572. var result = 0;
  20573. var type1 = v1.type;
  20574. var type2 = v2.type;
  20575. if (type1 === type2) {
  20576. var value1 = v1.value;
  20577. var value2 = v2.value;
  20578. if (type1 === 'string') {
  20579. // Compare strings case-insensitively
  20580. value1 = value1.toLowerCase();
  20581. value2 = value2.toLowerCase();
  20582. } else if (type1 === 'object') {
  20583. // For basic objects, use the position of the object
  20584. // in the collection instead of the value
  20585. if (isObject(value1)) value1 = v1.index;
  20586. if (isObject(value2)) value2 = v2.index;
  20587. }
  20588. if (value1 !== value2) {
  20589. result = value1 < value2 ? -1 : 1;
  20590. }
  20591. } else {
  20592. result = type1 < type2 ? -1 : 1;
  20593. }
  20594. return result;
  20595. }
  20596. }
  20597. function ngDirective(directive) {
  20598. if (isFunction(directive)) {
  20599. directive = {
  20600. link: directive
  20601. };
  20602. }
  20603. directive.restrict = directive.restrict || 'AC';
  20604. return valueFn(directive);
  20605. }
  20606. /**
  20607. * @ngdoc directive
  20608. * @name a
  20609. * @restrict E
  20610. *
  20611. * @description
  20612. * Modifies the default behavior of the html a tag so that the default action is prevented when
  20613. * the href attribute is empty.
  20614. *
  20615. * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
  20616. */
  20617. var htmlAnchorDirective = valueFn({
  20618. restrict: 'E',
  20619. compile: function(element, attr) {
  20620. if (!attr.href && !attr.xlinkHref) {
  20621. return function(scope, element) {
  20622. // If the linked element is not an anchor tag anymore, do nothing
  20623. if (element[0].nodeName.toLowerCase() !== 'a') return;
  20624. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  20625. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  20626. 'xlink:href' : 'href';
  20627. element.on('click', function(event) {
  20628. // if we have no href url, then don't navigate anywhere.
  20629. if (!element.attr(href)) {
  20630. event.preventDefault();
  20631. }
  20632. });
  20633. };
  20634. }
  20635. }
  20636. });
  20637. /**
  20638. * @ngdoc directive
  20639. * @name ngHref
  20640. * @restrict A
  20641. * @priority 99
  20642. *
  20643. * @description
  20644. * Using Angular markup like `{{hash}}` in an href attribute will
  20645. * make the link go to the wrong URL if the user clicks it before
  20646. * Angular has a chance to replace the `{{hash}}` markup with its
  20647. * value. Until Angular replaces the markup the link will be broken
  20648. * and will most likely return a 404 error. The `ngHref` directive
  20649. * solves this problem.
  20650. *
  20651. * The wrong way to write it:
  20652. * ```html
  20653. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20654. * ```
  20655. *
  20656. * The correct way to write it:
  20657. * ```html
  20658. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20659. * ```
  20660. *
  20661. * @element A
  20662. * @param {template} ngHref any string which can contain `{{}}` markup.
  20663. *
  20664. * @example
  20665. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  20666. * in links and their different behaviors:
  20667. <example name="ng-href">
  20668. <file name="index.html">
  20669. <input ng-model="value" /><br />
  20670. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  20671. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  20672. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  20673. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  20674. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  20675. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  20676. </file>
  20677. <file name="protractor.js" type="protractor">
  20678. it('should execute ng-click but not reload when href without value', function() {
  20679. element(by.id('link-1')).click();
  20680. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  20681. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  20682. });
  20683. it('should execute ng-click but not reload when href empty string', function() {
  20684. element(by.id('link-2')).click();
  20685. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  20686. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  20687. });
  20688. it('should execute ng-click and change url when ng-href specified', function() {
  20689. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  20690. element(by.id('link-3')).click();
  20691. // At this point, we navigate away from an Angular page, so we need
  20692. // to use browser.driver to get the base webdriver.
  20693. browser.wait(function() {
  20694. return browser.driver.getCurrentUrl().then(function(url) {
  20695. return url.match(/\/123$/);
  20696. });
  20697. }, 5000, 'page should navigate to /123');
  20698. });
  20699. it('should execute ng-click but not reload when href empty string and name specified', function() {
  20700. element(by.id('link-4')).click();
  20701. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  20702. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  20703. });
  20704. it('should execute ng-click but not reload when no href but name specified', function() {
  20705. element(by.id('link-5')).click();
  20706. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  20707. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  20708. });
  20709. it('should only change url when only ng-href', function() {
  20710. element(by.model('value')).clear();
  20711. element(by.model('value')).sendKeys('6');
  20712. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  20713. element(by.id('link-6')).click();
  20714. // At this point, we navigate away from an Angular page, so we need
  20715. // to use browser.driver to get the base webdriver.
  20716. browser.wait(function() {
  20717. return browser.driver.getCurrentUrl().then(function(url) {
  20718. return url.match(/\/6$/);
  20719. });
  20720. }, 5000, 'page should navigate to /6');
  20721. });
  20722. </file>
  20723. </example>
  20724. */
  20725. /**
  20726. * @ngdoc directive
  20727. * @name ngSrc
  20728. * @restrict A
  20729. * @priority 99
  20730. *
  20731. * @description
  20732. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  20733. * work right: The browser will fetch from the URL with the literal
  20734. * text `{{hash}}` until Angular replaces the expression inside
  20735. * `{{hash}}`. The `ngSrc` directive solves this problem.
  20736. *
  20737. * The buggy way to write it:
  20738. * ```html
  20739. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  20740. * ```
  20741. *
  20742. * The correct way to write it:
  20743. * ```html
  20744. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  20745. * ```
  20746. *
  20747. * @element IMG
  20748. * @param {template} ngSrc any string which can contain `{{}}` markup.
  20749. */
  20750. /**
  20751. * @ngdoc directive
  20752. * @name ngSrcset
  20753. * @restrict A
  20754. * @priority 99
  20755. *
  20756. * @description
  20757. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  20758. * work right: The browser will fetch from the URL with the literal
  20759. * text `{{hash}}` until Angular replaces the expression inside
  20760. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  20761. *
  20762. * The buggy way to write it:
  20763. * ```html
  20764. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  20765. * ```
  20766. *
  20767. * The correct way to write it:
  20768. * ```html
  20769. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  20770. * ```
  20771. *
  20772. * @element IMG
  20773. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  20774. */
  20775. /**
  20776. * @ngdoc directive
  20777. * @name ngDisabled
  20778. * @restrict A
  20779. * @priority 100
  20780. *
  20781. * @description
  20782. *
  20783. * This directive sets the `disabled` attribute on the element (typically a form control,
  20784. * e.g. `input`, `button`, `select` etc.) if the
  20785. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  20786. *
  20787. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  20788. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20789. *
  20790. * @example
  20791. <example name="ng-disabled">
  20792. <file name="index.html">
  20793. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  20794. <button ng-model="button" ng-disabled="checked">Button</button>
  20795. </file>
  20796. <file name="protractor.js" type="protractor">
  20797. it('should toggle button', function() {
  20798. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  20799. element(by.model('checked')).click();
  20800. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  20801. });
  20802. </file>
  20803. </example>
  20804. *
  20805. * @element INPUT
  20806. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  20807. * then the `disabled` attribute will be set on the element
  20808. */
  20809. /**
  20810. * @ngdoc directive
  20811. * @name ngChecked
  20812. * @restrict A
  20813. * @priority 100
  20814. *
  20815. * @description
  20816. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  20817. *
  20818. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  20819. * as this can lead to unexpected behavior.
  20820. *
  20821. * A special directive is necessary because we cannot use interpolation inside the `checked`
  20822. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20823. *
  20824. * @example
  20825. <example name="ng-checked">
  20826. <file name="index.html">
  20827. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  20828. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  20829. </file>
  20830. <file name="protractor.js" type="protractor">
  20831. it('should check both checkBoxes', function() {
  20832. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  20833. element(by.model('master')).click();
  20834. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  20835. });
  20836. </file>
  20837. </example>
  20838. *
  20839. * @element INPUT
  20840. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  20841. * then the `checked` attribute will be set on the element
  20842. */
  20843. /**
  20844. * @ngdoc directive
  20845. * @name ngReadonly
  20846. * @restrict A
  20847. * @priority 100
  20848. *
  20849. * @description
  20850. *
  20851. * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  20852. * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
  20853. * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
  20854. *
  20855. * A special directive is necessary because we cannot use interpolation inside the `readonly`
  20856. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20857. *
  20858. * @example
  20859. <example name="ng-readonly">
  20860. <file name="index.html">
  20861. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  20862. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  20863. </file>
  20864. <file name="protractor.js" type="protractor">
  20865. it('should toggle readonly attr', function() {
  20866. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  20867. element(by.model('checked')).click();
  20868. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  20869. });
  20870. </file>
  20871. </example>
  20872. *
  20873. * @element INPUT
  20874. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  20875. * then special attribute "readonly" will be set on the element
  20876. */
  20877. /**
  20878. * @ngdoc directive
  20879. * @name ngSelected
  20880. * @restrict A
  20881. * @priority 100
  20882. *
  20883. * @description
  20884. *
  20885. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  20886. *
  20887. * A special directive is necessary because we cannot use interpolation inside the `selected`
  20888. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20889. *
  20890. * <div class="alert alert-warning">
  20891. * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
  20892. * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
  20893. * should not use `ngSelected` on the options, as `ngModel` will set the select value and
  20894. * selected options.
  20895. * </div>
  20896. *
  20897. * @example
  20898. <example name="ng-selected">
  20899. <file name="index.html">
  20900. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  20901. <select aria-label="ngSelected demo">
  20902. <option>Hello!</option>
  20903. <option id="greet" ng-selected="selected">Greetings!</option>
  20904. </select>
  20905. </file>
  20906. <file name="protractor.js" type="protractor">
  20907. it('should select Greetings!', function() {
  20908. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  20909. element(by.model('selected')).click();
  20910. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  20911. });
  20912. </file>
  20913. </example>
  20914. *
  20915. * @element OPTION
  20916. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  20917. * then special attribute "selected" will be set on the element
  20918. */
  20919. /**
  20920. * @ngdoc directive
  20921. * @name ngOpen
  20922. * @restrict A
  20923. * @priority 100
  20924. *
  20925. * @description
  20926. *
  20927. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  20928. *
  20929. * A special directive is necessary because we cannot use interpolation inside the `open`
  20930. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20931. *
  20932. * ## A note about browser compatibility
  20933. *
  20934. * Internet Explorer and Edge do not support the `details` element, it is
  20935. * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
  20936. *
  20937. * @example
  20938. <example name="ng-open">
  20939. <file name="index.html">
  20940. <label>Toggle details: <input type="checkbox" ng-model="open"></label><br/>
  20941. <details id="details" ng-open="open">
  20942. <summary>List</summary>
  20943. <ul>
  20944. <li>Apple</li>
  20945. <li>Orange</li>
  20946. <li>Durian</li>
  20947. </ul>
  20948. </details>
  20949. </file>
  20950. <file name="protractor.js" type="protractor">
  20951. it('should toggle open', function() {
  20952. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  20953. element(by.model('open')).click();
  20954. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  20955. });
  20956. </file>
  20957. </example>
  20958. *
  20959. * @element DETAILS
  20960. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  20961. * then special attribute "open" will be set on the element
  20962. */
  20963. var ngAttributeAliasDirectives = {};
  20964. // boolean attrs are evaluated
  20965. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  20966. // binding to multiple is not supported
  20967. if (propName === 'multiple') return;
  20968. function defaultLinkFn(scope, element, attr) {
  20969. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  20970. attr.$set(attrName, !!value);
  20971. });
  20972. }
  20973. var normalized = directiveNormalize('ng-' + attrName);
  20974. var linkFn = defaultLinkFn;
  20975. if (propName === 'checked') {
  20976. linkFn = function(scope, element, attr) {
  20977. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  20978. if (attr.ngModel !== attr[normalized]) {
  20979. defaultLinkFn(scope, element, attr);
  20980. }
  20981. };
  20982. }
  20983. ngAttributeAliasDirectives[normalized] = function() {
  20984. return {
  20985. restrict: 'A',
  20986. priority: 100,
  20987. link: linkFn
  20988. };
  20989. };
  20990. });
  20991. // aliased input attrs are evaluated
  20992. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  20993. ngAttributeAliasDirectives[ngAttr] = function() {
  20994. return {
  20995. priority: 100,
  20996. link: function(scope, element, attr) {
  20997. //special case ngPattern when a literal regular expression value
  20998. //is used as the expression (this way we don't have to watch anything).
  20999. if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
  21000. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  21001. if (match) {
  21002. attr.$set('ngPattern', new RegExp(match[1], match[2]));
  21003. return;
  21004. }
  21005. }
  21006. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  21007. attr.$set(ngAttr, value);
  21008. });
  21009. }
  21010. };
  21011. };
  21012. });
  21013. // ng-src, ng-srcset, ng-href are interpolated
  21014. forEach(['src', 'srcset', 'href'], function(attrName) {
  21015. var normalized = directiveNormalize('ng-' + attrName);
  21016. ngAttributeAliasDirectives[normalized] = function() {
  21017. return {
  21018. priority: 99, // it needs to run after the attributes are interpolated
  21019. link: function(scope, element, attr) {
  21020. var propName = attrName,
  21021. name = attrName;
  21022. if (attrName === 'href' &&
  21023. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  21024. name = 'xlinkHref';
  21025. attr.$attr[name] = 'xlink:href';
  21026. propName = null;
  21027. }
  21028. attr.$observe(normalized, function(value) {
  21029. if (!value) {
  21030. if (attrName === 'href') {
  21031. attr.$set(name, null);
  21032. }
  21033. return;
  21034. }
  21035. attr.$set(name, value);
  21036. // Support: IE 9-11 only
  21037. // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  21038. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  21039. // to set the property as well to achieve the desired effect.
  21040. // We use attr[attrName] value since $set can sanitize the url.
  21041. if (msie && propName) element.prop(propName, attr[name]);
  21042. });
  21043. }
  21044. };
  21045. };
  21046. });
  21047. /* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS
  21048. */
  21049. var nullFormCtrl = {
  21050. $addControl: noop,
  21051. $$renameControl: nullFormRenameControl,
  21052. $removeControl: noop,
  21053. $setValidity: noop,
  21054. $setDirty: noop,
  21055. $setPristine: noop,
  21056. $setSubmitted: noop
  21057. },
  21058. PENDING_CLASS = 'ng-pending',
  21059. SUBMITTED_CLASS = 'ng-submitted';
  21060. function nullFormRenameControl(control, name) {
  21061. control.$name = name;
  21062. }
  21063. /**
  21064. * @ngdoc type
  21065. * @name form.FormController
  21066. *
  21067. * @property {boolean} $pristine True if user has not interacted with the form yet.
  21068. * @property {boolean} $dirty True if user has already interacted with the form.
  21069. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  21070. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  21071. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  21072. *
  21073. * @property {Object} $pending An object hash, containing references to controls or forms with
  21074. * pending validators, where:
  21075. *
  21076. * - keys are validations tokens (error names).
  21077. * - values are arrays of controls or forms that have a pending validator for the given error name.
  21078. *
  21079. * See {@link form.FormController#$error $error} for a list of built-in validation tokens.
  21080. *
  21081. * @property {Object} $error An object hash, containing references to controls or forms with failing
  21082. * validators, where:
  21083. *
  21084. * - keys are validation tokens (error names),
  21085. * - values are arrays of controls or forms that have a failing validator for the given error name.
  21086. *
  21087. * Built-in validation tokens:
  21088. * - `email`
  21089. * - `max`
  21090. * - `maxlength`
  21091. * - `min`
  21092. * - `minlength`
  21093. * - `number`
  21094. * - `pattern`
  21095. * - `required`
  21096. * - `url`
  21097. * - `date`
  21098. * - `datetimelocal`
  21099. * - `time`
  21100. * - `week`
  21101. * - `month`
  21102. *
  21103. * @description
  21104. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  21105. * such as being valid/invalid or dirty/pristine.
  21106. *
  21107. * Each {@link ng.directive:form form} directive creates an instance
  21108. * of `FormController`.
  21109. *
  21110. */
  21111. //asks for $scope to fool the BC controller module
  21112. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  21113. function FormController($element, $attrs, $scope, $animate, $interpolate) {
  21114. this.$$controls = [];
  21115. // init state
  21116. this.$error = {};
  21117. this.$$success = {};
  21118. this.$pending = undefined;
  21119. this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);
  21120. this.$dirty = false;
  21121. this.$pristine = true;
  21122. this.$valid = true;
  21123. this.$invalid = false;
  21124. this.$submitted = false;
  21125. this.$$parentForm = nullFormCtrl;
  21126. this.$$element = $element;
  21127. this.$$animate = $animate;
  21128. setupValidity(this);
  21129. }
  21130. FormController.prototype = {
  21131. /**
  21132. * @ngdoc method
  21133. * @name form.FormController#$rollbackViewValue
  21134. *
  21135. * @description
  21136. * Rollback all form controls pending updates to the `$modelValue`.
  21137. *
  21138. * Updates may be pending by a debounced event or because the input is waiting for a some future
  21139. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  21140. * a form that uses `ng-model-options` to pend updates.
  21141. */
  21142. $rollbackViewValue: function() {
  21143. forEach(this.$$controls, function(control) {
  21144. control.$rollbackViewValue();
  21145. });
  21146. },
  21147. /**
  21148. * @ngdoc method
  21149. * @name form.FormController#$commitViewValue
  21150. *
  21151. * @description
  21152. * Commit all form controls pending updates to the `$modelValue`.
  21153. *
  21154. * Updates may be pending by a debounced event or because the input is waiting for a some future
  21155. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  21156. * usually handles calling this in response to input events.
  21157. */
  21158. $commitViewValue: function() {
  21159. forEach(this.$$controls, function(control) {
  21160. control.$commitViewValue();
  21161. });
  21162. },
  21163. /**
  21164. * @ngdoc method
  21165. * @name form.FormController#$addControl
  21166. * @param {object} control control object, either a {@link form.FormController} or an
  21167. * {@link ngModel.NgModelController}
  21168. *
  21169. * @description
  21170. * Register a control with the form. Input elements using ngModelController do this automatically
  21171. * when they are linked.
  21172. *
  21173. * Note that the current state of the control will not be reflected on the new parent form. This
  21174. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  21175. * state.
  21176. *
  21177. * However, if the method is used programmatically, for example by adding dynamically created controls,
  21178. * or controls that have been previously removed without destroying their corresponding DOM element,
  21179. * it's the developers responsibility to make sure the current state propagates to the parent form.
  21180. *
  21181. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  21182. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  21183. */
  21184. $addControl: function(control) {
  21185. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  21186. // and not added to the scope. Now we throw an error.
  21187. assertNotHasOwnProperty(control.$name, 'input');
  21188. this.$$controls.push(control);
  21189. if (control.$name) {
  21190. this[control.$name] = control;
  21191. }
  21192. control.$$parentForm = this;
  21193. },
  21194. // Private API: rename a form control
  21195. $$renameControl: function(control, newName) {
  21196. var oldName = control.$name;
  21197. if (this[oldName] === control) {
  21198. delete this[oldName];
  21199. }
  21200. this[newName] = control;
  21201. control.$name = newName;
  21202. },
  21203. /**
  21204. * @ngdoc method
  21205. * @name form.FormController#$removeControl
  21206. * @param {object} control control object, either a {@link form.FormController} or an
  21207. * {@link ngModel.NgModelController}
  21208. *
  21209. * @description
  21210. * Deregister a control from the form.
  21211. *
  21212. * Input elements using ngModelController do this automatically when they are destroyed.
  21213. *
  21214. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  21215. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  21216. * different from case to case. For example, removing the only `$dirty` control from a form may or
  21217. * may not mean that the form is still `$dirty`.
  21218. */
  21219. $removeControl: function(control) {
  21220. if (control.$name && this[control.$name] === control) {
  21221. delete this[control.$name];
  21222. }
  21223. forEach(this.$pending, function(value, name) {
  21224. // eslint-disable-next-line no-invalid-this
  21225. this.$setValidity(name, null, control);
  21226. }, this);
  21227. forEach(this.$error, function(value, name) {
  21228. // eslint-disable-next-line no-invalid-this
  21229. this.$setValidity(name, null, control);
  21230. }, this);
  21231. forEach(this.$$success, function(value, name) {
  21232. // eslint-disable-next-line no-invalid-this
  21233. this.$setValidity(name, null, control);
  21234. }, this);
  21235. arrayRemove(this.$$controls, control);
  21236. control.$$parentForm = nullFormCtrl;
  21237. },
  21238. /**
  21239. * @ngdoc method
  21240. * @name form.FormController#$setDirty
  21241. *
  21242. * @description
  21243. * Sets the form to a dirty state.
  21244. *
  21245. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  21246. * state (ng-dirty class). This method will also propagate to parent forms.
  21247. */
  21248. $setDirty: function() {
  21249. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  21250. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  21251. this.$dirty = true;
  21252. this.$pristine = false;
  21253. this.$$parentForm.$setDirty();
  21254. },
  21255. /**
  21256. * @ngdoc method
  21257. * @name form.FormController#$setPristine
  21258. *
  21259. * @description
  21260. * Sets the form to its pristine state.
  21261. *
  21262. * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
  21263. * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
  21264. * state to false.
  21265. *
  21266. * This method will also propagate to all the controls contained in this form.
  21267. *
  21268. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  21269. * saving or resetting it.
  21270. */
  21271. $setPristine: function() {
  21272. this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  21273. this.$dirty = false;
  21274. this.$pristine = true;
  21275. this.$submitted = false;
  21276. forEach(this.$$controls, function(control) {
  21277. control.$setPristine();
  21278. });
  21279. },
  21280. /**
  21281. * @ngdoc method
  21282. * @name form.FormController#$setUntouched
  21283. *
  21284. * @description
  21285. * Sets the form to its untouched state.
  21286. *
  21287. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  21288. * untouched state (ng-untouched class).
  21289. *
  21290. * Setting a form controls back to their untouched state is often useful when setting the form
  21291. * back to its pristine state.
  21292. */
  21293. $setUntouched: function() {
  21294. forEach(this.$$controls, function(control) {
  21295. control.$setUntouched();
  21296. });
  21297. },
  21298. /**
  21299. * @ngdoc method
  21300. * @name form.FormController#$setSubmitted
  21301. *
  21302. * @description
  21303. * Sets the form to its submitted state.
  21304. */
  21305. $setSubmitted: function() {
  21306. this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);
  21307. this.$submitted = true;
  21308. this.$$parentForm.$setSubmitted();
  21309. }
  21310. };
  21311. /**
  21312. * @ngdoc method
  21313. * @name form.FormController#$setValidity
  21314. *
  21315. * @description
  21316. * Change the validity state of the form, and notify the parent form (if any).
  21317. *
  21318. * Application developers will rarely need to call this method directly. It is used internally, by
  21319. * {@link ngModel.NgModelController#$setValidity NgModelController.$setValidity()}, to propagate a
  21320. * control's validity state to the parent `FormController`.
  21321. *
  21322. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be
  21323. * assigned to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` (for
  21324. * unfulfilled `$asyncValidators`), so that it is available for data-binding. The
  21325. * `validationErrorKey` should be in camelCase and will get converted into dash-case for
  21326. * class name. Example: `myError` will result in `ng-valid-my-error` and
  21327. * `ng-invalid-my-error` classes and can be bound to as `{{ someForm.$error.myError }}`.
  21328. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending
  21329. * (undefined), or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  21330. * Skipped is used by AngularJS when validators do not run because of parse errors and when
  21331. * `$asyncValidators` do not run because any of the `$validators` failed.
  21332. * @param {NgModelController | FormController} controller - The controller whose validity state is
  21333. * triggering the change.
  21334. */
  21335. addSetValidityMethod({
  21336. clazz: FormController,
  21337. set: function(object, property, controller) {
  21338. var list = object[property];
  21339. if (!list) {
  21340. object[property] = [controller];
  21341. } else {
  21342. var index = list.indexOf(controller);
  21343. if (index === -1) {
  21344. list.push(controller);
  21345. }
  21346. }
  21347. },
  21348. unset: function(object, property, controller) {
  21349. var list = object[property];
  21350. if (!list) {
  21351. return;
  21352. }
  21353. arrayRemove(list, controller);
  21354. if (list.length === 0) {
  21355. delete object[property];
  21356. }
  21357. }
  21358. });
  21359. /**
  21360. * @ngdoc directive
  21361. * @name ngForm
  21362. * @restrict EAC
  21363. *
  21364. * @description
  21365. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  21366. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  21367. * sub-group of controls needs to be determined.
  21368. *
  21369. * Note: the purpose of `ngForm` is to group controls,
  21370. * but not to be a replacement for the `<form>` tag with all of its capabilities
  21371. * (e.g. posting to the server, ...).
  21372. *
  21373. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  21374. * related scope, under this name.
  21375. *
  21376. */
  21377. /**
  21378. * @ngdoc directive
  21379. * @name form
  21380. * @restrict E
  21381. *
  21382. * @description
  21383. * Directive that instantiates
  21384. * {@link form.FormController FormController}.
  21385. *
  21386. * If the `name` attribute is specified, the form controller is published onto the current scope under
  21387. * this name.
  21388. *
  21389. * # Alias: {@link ng.directive:ngForm `ngForm`}
  21390. *
  21391. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  21392. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  21393. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  21394. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  21395. * of controls needs to be determined.
  21396. *
  21397. * # CSS classes
  21398. * - `ng-valid` is set if the form is valid.
  21399. * - `ng-invalid` is set if the form is invalid.
  21400. * - `ng-pending` is set if the form is pending.
  21401. * - `ng-pristine` is set if the form is pristine.
  21402. * - `ng-dirty` is set if the form is dirty.
  21403. * - `ng-submitted` is set if the form was submitted.
  21404. *
  21405. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  21406. *
  21407. *
  21408. * # Submitting a form and preventing the default action
  21409. *
  21410. * Since the role of forms in client-side Angular applications is different than in classical
  21411. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  21412. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  21413. * to handle the form submission in an application-specific way.
  21414. *
  21415. * For this reason, Angular prevents the default action (form submission to the server) unless the
  21416. * `<form>` element has an `action` attribute specified.
  21417. *
  21418. * You can use one of the following two ways to specify what javascript method should be called when
  21419. * a form is submitted:
  21420. *
  21421. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  21422. * - {@link ng.directive:ngClick ngClick} directive on the first
  21423. * button or input field of type submit (input[type=submit])
  21424. *
  21425. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  21426. * or {@link ng.directive:ngClick ngClick} directives.
  21427. * This is because of the following form submission rules in the HTML specification:
  21428. *
  21429. * - If a form has only one input field then hitting enter in this field triggers form submit
  21430. * (`ngSubmit`)
  21431. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  21432. * doesn't trigger submit
  21433. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  21434. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  21435. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  21436. *
  21437. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  21438. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  21439. * to have access to the updated model.
  21440. *
  21441. * ## Animation Hooks
  21442. *
  21443. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  21444. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  21445. * other validations that are performed within the form. Animations in ngForm are similar to how
  21446. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  21447. * as JS animations.
  21448. *
  21449. * The following example shows a simple way to utilize CSS transitions to style a form element
  21450. * that has been rendered as invalid after it has been validated:
  21451. *
  21452. * <pre>
  21453. * //be sure to include ngAnimate as a module to hook into more
  21454. * //advanced animations
  21455. * .my-form {
  21456. * transition:0.5s linear all;
  21457. * background: white;
  21458. * }
  21459. * .my-form.ng-invalid {
  21460. * background: red;
  21461. * color:white;
  21462. * }
  21463. * </pre>
  21464. *
  21465. * @example
  21466. <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  21467. <file name="index.html">
  21468. <script>
  21469. angular.module('formExample', [])
  21470. .controller('FormController', ['$scope', function($scope) {
  21471. $scope.userType = 'guest';
  21472. }]);
  21473. </script>
  21474. <style>
  21475. .my-form {
  21476. transition:all linear 0.5s;
  21477. background: transparent;
  21478. }
  21479. .my-form.ng-invalid {
  21480. background: red;
  21481. }
  21482. </style>
  21483. <form name="myForm" ng-controller="FormController" class="my-form">
  21484. userType: <input name="input" ng-model="userType" required>
  21485. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  21486. <code>userType = {{userType}}</code><br>
  21487. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  21488. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  21489. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  21490. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  21491. </form>
  21492. </file>
  21493. <file name="protractor.js" type="protractor">
  21494. it('should initialize to model', function() {
  21495. var userType = element(by.binding('userType'));
  21496. var valid = element(by.binding('myForm.input.$valid'));
  21497. expect(userType.getText()).toContain('guest');
  21498. expect(valid.getText()).toContain('true');
  21499. });
  21500. it('should be invalid if empty', function() {
  21501. var userType = element(by.binding('userType'));
  21502. var valid = element(by.binding('myForm.input.$valid'));
  21503. var userInput = element(by.model('userType'));
  21504. userInput.clear();
  21505. userInput.sendKeys('');
  21506. expect(userType.getText()).toEqual('userType =');
  21507. expect(valid.getText()).toContain('false');
  21508. });
  21509. </file>
  21510. </example>
  21511. *
  21512. * @param {string=} name Name of the form. If specified, the form controller will be published into
  21513. * related scope, under this name.
  21514. */
  21515. var formDirectiveFactory = function(isNgForm) {
  21516. return ['$timeout', '$parse', function($timeout, $parse) {
  21517. var formDirective = {
  21518. name: 'form',
  21519. restrict: isNgForm ? 'EAC' : 'E',
  21520. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  21521. controller: FormController,
  21522. compile: function ngFormCompile(formElement, attr) {
  21523. // Setup initial state of the control
  21524. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  21525. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  21526. return {
  21527. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  21528. var controller = ctrls[0];
  21529. // if `action` attr is not present on the form, prevent the default action (submission)
  21530. if (!('action' in attr)) {
  21531. // we can't use jq events because if a form is destroyed during submission the default
  21532. // action is not prevented. see #1238
  21533. //
  21534. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  21535. // page reload if the form was destroyed by submission of the form via a click handler
  21536. // on a button in the form. Looks like an IE9 specific bug.
  21537. var handleFormSubmission = function(event) {
  21538. scope.$apply(function() {
  21539. controller.$commitViewValue();
  21540. controller.$setSubmitted();
  21541. });
  21542. event.preventDefault();
  21543. };
  21544. formElement[0].addEventListener('submit', handleFormSubmission);
  21545. // unregister the preventDefault listener so that we don't not leak memory but in a
  21546. // way that will achieve the prevention of the default action.
  21547. formElement.on('$destroy', function() {
  21548. $timeout(function() {
  21549. formElement[0].removeEventListener('submit', handleFormSubmission);
  21550. }, 0, false);
  21551. });
  21552. }
  21553. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  21554. parentFormCtrl.$addControl(controller);
  21555. var setter = nameAttr ? getSetter(controller.$name) : noop;
  21556. if (nameAttr) {
  21557. setter(scope, controller);
  21558. attr.$observe(nameAttr, function(newValue) {
  21559. if (controller.$name === newValue) return;
  21560. setter(scope, undefined);
  21561. controller.$$parentForm.$$renameControl(controller, newValue);
  21562. setter = getSetter(controller.$name);
  21563. setter(scope, controller);
  21564. });
  21565. }
  21566. formElement.on('$destroy', function() {
  21567. controller.$$parentForm.$removeControl(controller);
  21568. setter(scope, undefined);
  21569. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  21570. });
  21571. }
  21572. };
  21573. }
  21574. };
  21575. return formDirective;
  21576. function getSetter(expression) {
  21577. if (expression === '') {
  21578. //create an assignable expression, so forms with an empty name can be renamed later
  21579. return $parse('this[""]').assign;
  21580. }
  21581. return $parse(expression).assign || noop;
  21582. }
  21583. }];
  21584. };
  21585. var formDirective = formDirectiveFactory();
  21586. var ngFormDirective = formDirectiveFactory(true);
  21587. // helper methods
  21588. function setupValidity(instance) {
  21589. instance.$$classCache = {};
  21590. instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));
  21591. }
  21592. function addSetValidityMethod(context) {
  21593. var clazz = context.clazz,
  21594. set = context.set,
  21595. unset = context.unset;
  21596. clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {
  21597. if (isUndefined(state)) {
  21598. createAndSet(this, '$pending', validationErrorKey, controller);
  21599. } else {
  21600. unsetAndCleanup(this, '$pending', validationErrorKey, controller);
  21601. }
  21602. if (!isBoolean(state)) {
  21603. unset(this.$error, validationErrorKey, controller);
  21604. unset(this.$$success, validationErrorKey, controller);
  21605. } else {
  21606. if (state) {
  21607. unset(this.$error, validationErrorKey, controller);
  21608. set(this.$$success, validationErrorKey, controller);
  21609. } else {
  21610. set(this.$error, validationErrorKey, controller);
  21611. unset(this.$$success, validationErrorKey, controller);
  21612. }
  21613. }
  21614. if (this.$pending) {
  21615. cachedToggleClass(this, PENDING_CLASS, true);
  21616. this.$valid = this.$invalid = undefined;
  21617. toggleValidationCss(this, '', null);
  21618. } else {
  21619. cachedToggleClass(this, PENDING_CLASS, false);
  21620. this.$valid = isObjectEmpty(this.$error);
  21621. this.$invalid = !this.$valid;
  21622. toggleValidationCss(this, '', this.$valid);
  21623. }
  21624. // re-read the state as the set/unset methods could have
  21625. // combined state in this.$error[validationError] (used for forms),
  21626. // where setting/unsetting only increments/decrements the value,
  21627. // and does not replace it.
  21628. var combinedState;
  21629. if (this.$pending && this.$pending[validationErrorKey]) {
  21630. combinedState = undefined;
  21631. } else if (this.$error[validationErrorKey]) {
  21632. combinedState = false;
  21633. } else if (this.$$success[validationErrorKey]) {
  21634. combinedState = true;
  21635. } else {
  21636. combinedState = null;
  21637. }
  21638. toggleValidationCss(this, validationErrorKey, combinedState);
  21639. this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);
  21640. };
  21641. function createAndSet(ctrl, name, value, controller) {
  21642. if (!ctrl[name]) {
  21643. ctrl[name] = {};
  21644. }
  21645. set(ctrl[name], value, controller);
  21646. }
  21647. function unsetAndCleanup(ctrl, name, value, controller) {
  21648. if (ctrl[name]) {
  21649. unset(ctrl[name], value, controller);
  21650. }
  21651. if (isObjectEmpty(ctrl[name])) {
  21652. ctrl[name] = undefined;
  21653. }
  21654. }
  21655. function cachedToggleClass(ctrl, className, switchValue) {
  21656. if (switchValue && !ctrl.$$classCache[className]) {
  21657. ctrl.$$animate.addClass(ctrl.$$element, className);
  21658. ctrl.$$classCache[className] = true;
  21659. } else if (!switchValue && ctrl.$$classCache[className]) {
  21660. ctrl.$$animate.removeClass(ctrl.$$element, className);
  21661. ctrl.$$classCache[className] = false;
  21662. }
  21663. }
  21664. function toggleValidationCss(ctrl, validationErrorKey, isValid) {
  21665. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  21666. cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);
  21667. cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);
  21668. }
  21669. }
  21670. function isObjectEmpty(obj) {
  21671. if (obj) {
  21672. for (var prop in obj) {
  21673. if (obj.hasOwnProperty(prop)) {
  21674. return false;
  21675. }
  21676. }
  21677. }
  21678. return true;
  21679. }
  21680. /* global
  21681. VALID_CLASS: false,
  21682. INVALID_CLASS: false,
  21683. PRISTINE_CLASS: false,
  21684. DIRTY_CLASS: false,
  21685. ngModelMinErr: false
  21686. */
  21687. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  21688. 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)$/;
  21689. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  21690. // Note: We are being more lenient, because browsers are too.
  21691. // 1. Scheme
  21692. // 2. Slashes
  21693. // 3. Username
  21694. // 4. Password
  21695. // 5. Hostname
  21696. // 6. Port
  21697. // 7. Path
  21698. // 8. Query
  21699. // 9. Fragment
  21700. // 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
  21701. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  21702. // eslint-disable-next-line max-len
  21703. 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])?)*$/;
  21704. var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  21705. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  21706. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21707. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  21708. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  21709. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21710. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  21711. var PARTIAL_VALIDATION_TYPES = createMap();
  21712. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  21713. PARTIAL_VALIDATION_TYPES[type] = true;
  21714. });
  21715. var inputType = {
  21716. /**
  21717. * @ngdoc input
  21718. * @name input[text]
  21719. *
  21720. * @description
  21721. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  21722. *
  21723. *
  21724. * @param {string} ngModel Assignable angular expression to data-bind to.
  21725. * @param {string=} name Property name of the form under which the control is published.
  21726. * @param {string=} required Adds `required` validation error key if the value is not entered.
  21727. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21728. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21729. * `required` when you want to data-bind to the `required` attribute.
  21730. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21731. * minlength.
  21732. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21733. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21734. * any length.
  21735. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21736. * that contains the regular expression body that will be converted to a regular expression
  21737. * as in the ngPattern directive.
  21738. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21739. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21740. * If the expression evaluates to a RegExp object, then this is used directly.
  21741. * If the expression evaluates to a string, then it will be converted to a RegExp
  21742. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21743. * `new RegExp('^abc$')`.<br />
  21744. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21745. * start at the index of the last search's match, thus not taking the whole input value into
  21746. * account.
  21747. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21748. * interaction with the input element.
  21749. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21750. * This parameter is ignored for input[type=password] controls, which will never trim the
  21751. * input.
  21752. *
  21753. * @example
  21754. <example name="text-input-directive" module="textInputExample">
  21755. <file name="index.html">
  21756. <script>
  21757. angular.module('textInputExample', [])
  21758. .controller('ExampleController', ['$scope', function($scope) {
  21759. $scope.example = {
  21760. text: 'guest',
  21761. word: /^\s*\w*\s*$/
  21762. };
  21763. }]);
  21764. </script>
  21765. <form name="myForm" ng-controller="ExampleController">
  21766. <label>Single word:
  21767. <input type="text" name="input" ng-model="example.text"
  21768. ng-pattern="example.word" required ng-trim="false">
  21769. </label>
  21770. <div role="alert">
  21771. <span class="error" ng-show="myForm.input.$error.required">
  21772. Required!</span>
  21773. <span class="error" ng-show="myForm.input.$error.pattern">
  21774. Single word only!</span>
  21775. </div>
  21776. <code>text = {{example.text}}</code><br/>
  21777. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  21778. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  21779. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  21780. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  21781. </form>
  21782. </file>
  21783. <file name="protractor.js" type="protractor">
  21784. var text = element(by.binding('example.text'));
  21785. var valid = element(by.binding('myForm.input.$valid'));
  21786. var input = element(by.model('example.text'));
  21787. it('should initialize to model', function() {
  21788. expect(text.getText()).toContain('guest');
  21789. expect(valid.getText()).toContain('true');
  21790. });
  21791. it('should be invalid if empty', function() {
  21792. input.clear();
  21793. input.sendKeys('');
  21794. expect(text.getText()).toEqual('text =');
  21795. expect(valid.getText()).toContain('false');
  21796. });
  21797. it('should be invalid if multi word', function() {
  21798. input.clear();
  21799. input.sendKeys('hello world');
  21800. expect(valid.getText()).toContain('false');
  21801. });
  21802. </file>
  21803. </example>
  21804. */
  21805. 'text': textInputType,
  21806. /**
  21807. * @ngdoc input
  21808. * @name input[date]
  21809. *
  21810. * @description
  21811. * Input with date validation and transformation. In browsers that do not yet support
  21812. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  21813. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  21814. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  21815. * expected input format via a placeholder or label.
  21816. *
  21817. * The model must always be a Date object, otherwise Angular will throw an error.
  21818. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21819. *
  21820. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21821. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21822. *
  21823. * @param {string} ngModel Assignable angular expression to data-bind to.
  21824. * @param {string=} name Property name of the form under which the control is published.
  21825. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  21826. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21827. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  21828. * constraint validation.
  21829. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  21830. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21831. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  21832. * constraint validation.
  21833. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  21834. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21835. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  21836. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21837. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21838. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21839. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21840. * `required` when you want to data-bind to the `required` attribute.
  21841. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21842. * interaction with the input element.
  21843. *
  21844. * @example
  21845. <example name="date-input-directive" module="dateInputExample">
  21846. <file name="index.html">
  21847. <script>
  21848. angular.module('dateInputExample', [])
  21849. .controller('DateController', ['$scope', function($scope) {
  21850. $scope.example = {
  21851. value: new Date(2013, 9, 22)
  21852. };
  21853. }]);
  21854. </script>
  21855. <form name="myForm" ng-controller="DateController as dateCtrl">
  21856. <label for="exampleInput">Pick a date in 2013:</label>
  21857. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  21858. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  21859. <div role="alert">
  21860. <span class="error" ng-show="myForm.input.$error.required">
  21861. Required!</span>
  21862. <span class="error" ng-show="myForm.input.$error.date">
  21863. Not a valid date!</span>
  21864. </div>
  21865. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  21866. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21867. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21868. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21869. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21870. </form>
  21871. </file>
  21872. <file name="protractor.js" type="protractor">
  21873. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  21874. var valid = element(by.binding('myForm.input.$valid'));
  21875. // currently protractor/webdriver does not support
  21876. // sending keys to all known HTML5 input controls
  21877. // for various browsers (see https://github.com/angular/protractor/issues/562).
  21878. function setInput(val) {
  21879. // set the value of the element and force validation.
  21880. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21881. "ipt.value = '" + val + "';" +
  21882. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21883. browser.executeScript(scr);
  21884. }
  21885. it('should initialize to model', function() {
  21886. expect(value.getText()).toContain('2013-10-22');
  21887. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21888. });
  21889. it('should be invalid if empty', function() {
  21890. setInput('');
  21891. expect(value.getText()).toEqual('value =');
  21892. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21893. });
  21894. it('should be invalid if over max', function() {
  21895. setInput('2015-01-01');
  21896. expect(value.getText()).toContain('');
  21897. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21898. });
  21899. </file>
  21900. </example>
  21901. */
  21902. 'date': createDateInputType('date', DATE_REGEXP,
  21903. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  21904. 'yyyy-MM-dd'),
  21905. /**
  21906. * @ngdoc input
  21907. * @name input[datetime-local]
  21908. *
  21909. * @description
  21910. * Input with datetime validation and transformation. In browsers that do not yet support
  21911. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21912. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  21913. *
  21914. * The model must always be a Date object, otherwise Angular will throw an error.
  21915. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21916. *
  21917. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21918. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21919. *
  21920. * @param {string} ngModel Assignable angular expression to data-bind to.
  21921. * @param {string=} name Property name of the form under which the control is published.
  21922. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21923. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21924. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21925. * Note that `min` will also add native HTML5 constraint validation.
  21926. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21927. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21928. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21929. * Note that `max` will also add native HTML5 constraint validation.
  21930. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  21931. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21932. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  21933. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21934. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21935. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21936. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21937. * `required` when you want to data-bind to the `required` attribute.
  21938. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21939. * interaction with the input element.
  21940. *
  21941. * @example
  21942. <example name="datetimelocal-input-directive" module="dateExample">
  21943. <file name="index.html">
  21944. <script>
  21945. angular.module('dateExample', [])
  21946. .controller('DateController', ['$scope', function($scope) {
  21947. $scope.example = {
  21948. value: new Date(2010, 11, 28, 14, 57)
  21949. };
  21950. }]);
  21951. </script>
  21952. <form name="myForm" ng-controller="DateController as dateCtrl">
  21953. <label for="exampleInput">Pick a date between in 2013:</label>
  21954. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  21955. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  21956. <div role="alert">
  21957. <span class="error" ng-show="myForm.input.$error.required">
  21958. Required!</span>
  21959. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  21960. Not a valid date!</span>
  21961. </div>
  21962. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  21963. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21964. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21965. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21966. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21967. </form>
  21968. </file>
  21969. <file name="protractor.js" type="protractor">
  21970. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  21971. var valid = element(by.binding('myForm.input.$valid'));
  21972. // currently protractor/webdriver does not support
  21973. // sending keys to all known HTML5 input controls
  21974. // for various browsers (https://github.com/angular/protractor/issues/562).
  21975. function setInput(val) {
  21976. // set the value of the element and force validation.
  21977. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21978. "ipt.value = '" + val + "';" +
  21979. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21980. browser.executeScript(scr);
  21981. }
  21982. it('should initialize to model', function() {
  21983. expect(value.getText()).toContain('2010-12-28T14:57:00');
  21984. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21985. });
  21986. it('should be invalid if empty', function() {
  21987. setInput('');
  21988. expect(value.getText()).toEqual('value =');
  21989. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21990. });
  21991. it('should be invalid if over max', function() {
  21992. setInput('2015-01-01T23:59:00');
  21993. expect(value.getText()).toContain('');
  21994. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21995. });
  21996. </file>
  21997. </example>
  21998. */
  21999. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  22000. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  22001. 'yyyy-MM-ddTHH:mm:ss.sss'),
  22002. /**
  22003. * @ngdoc input
  22004. * @name input[time]
  22005. *
  22006. * @description
  22007. * Input with time validation and transformation. In browsers that do not yet support
  22008. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  22009. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  22010. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  22011. *
  22012. * The model must always be a Date object, otherwise Angular will throw an error.
  22013. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22014. *
  22015. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22016. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22017. *
  22018. * @param {string} ngModel Assignable angular expression to data-bind to.
  22019. * @param {string=} name Property name of the form under which the control is published.
  22020. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22021. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  22022. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  22023. * native HTML5 constraint validation.
  22024. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22025. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  22026. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  22027. * native HTML5 constraint validation.
  22028. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  22029. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22030. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  22031. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22032. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22033. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22034. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22035. * `required` when you want to data-bind to the `required` attribute.
  22036. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22037. * interaction with the input element.
  22038. *
  22039. * @example
  22040. <example name="time-input-directive" module="timeExample">
  22041. <file name="index.html">
  22042. <script>
  22043. angular.module('timeExample', [])
  22044. .controller('DateController', ['$scope', function($scope) {
  22045. $scope.example = {
  22046. value: new Date(1970, 0, 1, 14, 57, 0)
  22047. };
  22048. }]);
  22049. </script>
  22050. <form name="myForm" ng-controller="DateController as dateCtrl">
  22051. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  22052. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  22053. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  22054. <div role="alert">
  22055. <span class="error" ng-show="myForm.input.$error.required">
  22056. Required!</span>
  22057. <span class="error" ng-show="myForm.input.$error.time">
  22058. Not a valid date!</span>
  22059. </div>
  22060. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  22061. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22062. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22063. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22064. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22065. </form>
  22066. </file>
  22067. <file name="protractor.js" type="protractor">
  22068. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  22069. var valid = element(by.binding('myForm.input.$valid'));
  22070. // currently protractor/webdriver does not support
  22071. // sending keys to all known HTML5 input controls
  22072. // for various browsers (https://github.com/angular/protractor/issues/562).
  22073. function setInput(val) {
  22074. // set the value of the element and force validation.
  22075. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22076. "ipt.value = '" + val + "';" +
  22077. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22078. browser.executeScript(scr);
  22079. }
  22080. it('should initialize to model', function() {
  22081. expect(value.getText()).toContain('14:57:00');
  22082. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22083. });
  22084. it('should be invalid if empty', function() {
  22085. setInput('');
  22086. expect(value.getText()).toEqual('value =');
  22087. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22088. });
  22089. it('should be invalid if over max', function() {
  22090. setInput('23:59:00');
  22091. expect(value.getText()).toContain('');
  22092. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22093. });
  22094. </file>
  22095. </example>
  22096. */
  22097. 'time': createDateInputType('time', TIME_REGEXP,
  22098. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  22099. 'HH:mm:ss.sss'),
  22100. /**
  22101. * @ngdoc input
  22102. * @name input[week]
  22103. *
  22104. * @description
  22105. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  22106. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  22107. * week format (yyyy-W##), for example: `2013-W02`.
  22108. *
  22109. * The model must always be a Date object, otherwise Angular will throw an error.
  22110. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22111. *
  22112. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22113. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22114. *
  22115. * @param {string} ngModel Assignable angular expression to data-bind to.
  22116. * @param {string=} name Property name of the form under which the control is published.
  22117. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22118. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  22119. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  22120. * native HTML5 constraint validation.
  22121. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22122. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  22123. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  22124. * native HTML5 constraint validation.
  22125. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  22126. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22127. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  22128. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22129. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22130. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22131. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22132. * `required` when you want to data-bind to the `required` attribute.
  22133. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22134. * interaction with the input element.
  22135. *
  22136. * @example
  22137. <example name="week-input-directive" module="weekExample">
  22138. <file name="index.html">
  22139. <script>
  22140. angular.module('weekExample', [])
  22141. .controller('DateController', ['$scope', function($scope) {
  22142. $scope.example = {
  22143. value: new Date(2013, 0, 3)
  22144. };
  22145. }]);
  22146. </script>
  22147. <form name="myForm" ng-controller="DateController as dateCtrl">
  22148. <label>Pick a date between in 2013:
  22149. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  22150. placeholder="YYYY-W##" min="2012-W32"
  22151. max="2013-W52" required />
  22152. </label>
  22153. <div role="alert">
  22154. <span class="error" ng-show="myForm.input.$error.required">
  22155. Required!</span>
  22156. <span class="error" ng-show="myForm.input.$error.week">
  22157. Not a valid date!</span>
  22158. </div>
  22159. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  22160. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22161. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22162. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22163. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22164. </form>
  22165. </file>
  22166. <file name="protractor.js" type="protractor">
  22167. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  22168. var valid = element(by.binding('myForm.input.$valid'));
  22169. // currently protractor/webdriver does not support
  22170. // sending keys to all known HTML5 input controls
  22171. // for various browsers (https://github.com/angular/protractor/issues/562).
  22172. function setInput(val) {
  22173. // set the value of the element and force validation.
  22174. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22175. "ipt.value = '" + val + "';" +
  22176. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22177. browser.executeScript(scr);
  22178. }
  22179. it('should initialize to model', function() {
  22180. expect(value.getText()).toContain('2013-W01');
  22181. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22182. });
  22183. it('should be invalid if empty', function() {
  22184. setInput('');
  22185. expect(value.getText()).toEqual('value =');
  22186. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22187. });
  22188. it('should be invalid if over max', function() {
  22189. setInput('2015-W01');
  22190. expect(value.getText()).toContain('');
  22191. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22192. });
  22193. </file>
  22194. </example>
  22195. */
  22196. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  22197. /**
  22198. * @ngdoc input
  22199. * @name input[month]
  22200. *
  22201. * @description
  22202. * Input with month validation and transformation. In browsers that do not yet support
  22203. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  22204. * month format (yyyy-MM), for example: `2009-01`.
  22205. *
  22206. * The model must always be a Date object, otherwise Angular will throw an error.
  22207. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22208. * If the model is not set to the first of the month, the next view to model update will set it
  22209. * to the first of the month.
  22210. *
  22211. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22212. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22213. *
  22214. * @param {string} ngModel Assignable angular expression to data-bind to.
  22215. * @param {string=} name Property name of the form under which the control is published.
  22216. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22217. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  22218. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  22219. * native HTML5 constraint validation.
  22220. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22221. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  22222. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  22223. * native HTML5 constraint validation.
  22224. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  22225. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22226. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  22227. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22228. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22229. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22230. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22231. * `required` when you want to data-bind to the `required` attribute.
  22232. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22233. * interaction with the input element.
  22234. *
  22235. * @example
  22236. <example name="month-input-directive" module="monthExample">
  22237. <file name="index.html">
  22238. <script>
  22239. angular.module('monthExample', [])
  22240. .controller('DateController', ['$scope', function($scope) {
  22241. $scope.example = {
  22242. value: new Date(2013, 9, 1)
  22243. };
  22244. }]);
  22245. </script>
  22246. <form name="myForm" ng-controller="DateController as dateCtrl">
  22247. <label for="exampleInput">Pick a month in 2013:</label>
  22248. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  22249. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  22250. <div role="alert">
  22251. <span class="error" ng-show="myForm.input.$error.required">
  22252. Required!</span>
  22253. <span class="error" ng-show="myForm.input.$error.month">
  22254. Not a valid month!</span>
  22255. </div>
  22256. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  22257. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22258. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22259. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22260. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22261. </form>
  22262. </file>
  22263. <file name="protractor.js" type="protractor">
  22264. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  22265. var valid = element(by.binding('myForm.input.$valid'));
  22266. // currently protractor/webdriver does not support
  22267. // sending keys to all known HTML5 input controls
  22268. // for various browsers (https://github.com/angular/protractor/issues/562).
  22269. function setInput(val) {
  22270. // set the value of the element and force validation.
  22271. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22272. "ipt.value = '" + val + "';" +
  22273. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22274. browser.executeScript(scr);
  22275. }
  22276. it('should initialize to model', function() {
  22277. expect(value.getText()).toContain('2013-10');
  22278. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22279. });
  22280. it('should be invalid if empty', function() {
  22281. setInput('');
  22282. expect(value.getText()).toEqual('value =');
  22283. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22284. });
  22285. it('should be invalid if over max', function() {
  22286. setInput('2015-01');
  22287. expect(value.getText()).toContain('');
  22288. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22289. });
  22290. </file>
  22291. </example>
  22292. */
  22293. 'month': createDateInputType('month', MONTH_REGEXP,
  22294. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  22295. 'yyyy-MM'),
  22296. /**
  22297. * @ngdoc input
  22298. * @name input[number]
  22299. *
  22300. * @description
  22301. * Text input with number validation and transformation. Sets the `number` validation
  22302. * error if not a valid number.
  22303. *
  22304. * <div class="alert alert-warning">
  22305. * The model must always be of type `number` otherwise Angular will throw an error.
  22306. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  22307. * error docs for more information and an example of how to convert your model if necessary.
  22308. * </div>
  22309. *
  22310. * ## Issues with HTML5 constraint validation
  22311. *
  22312. * In browsers that follow the
  22313. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  22314. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  22315. * If a non-number is entered in the input, the browser will report the value as an empty string,
  22316. * which means the view / model values in `ngModel` and subsequently the scope value
  22317. * will also be an empty string.
  22318. *
  22319. *
  22320. * @param {string} ngModel Assignable angular expression to data-bind to.
  22321. * @param {string=} name Property name of the form under which the control is published.
  22322. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22323. * Can be interpolated.
  22324. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22325. * Can be interpolated.
  22326. * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
  22327. * but does not trigger HTML5 native validation. Takes an expression.
  22328. * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
  22329. * but does not trigger HTML5 native validation. Takes an expression.
  22330. * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
  22331. * Can be interpolated.
  22332. * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,
  22333. * but does not trigger HTML5 native validation. Takes an expression.
  22334. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22335. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22336. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22337. * `required` when you want to data-bind to the `required` attribute.
  22338. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22339. * minlength.
  22340. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22341. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22342. * any length.
  22343. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22344. * that contains the regular expression body that will be converted to a regular expression
  22345. * as in the ngPattern directive.
  22346. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22347. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22348. * If the expression evaluates to a RegExp object, then this is used directly.
  22349. * If the expression evaluates to a string, then it will be converted to a RegExp
  22350. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22351. * `new RegExp('^abc$')`.<br />
  22352. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22353. * start at the index of the last search's match, thus not taking the whole input value into
  22354. * account.
  22355. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22356. * interaction with the input element.
  22357. *
  22358. * @example
  22359. <example name="number-input-directive" module="numberExample">
  22360. <file name="index.html">
  22361. <script>
  22362. angular.module('numberExample', [])
  22363. .controller('ExampleController', ['$scope', function($scope) {
  22364. $scope.example = {
  22365. value: 12
  22366. };
  22367. }]);
  22368. </script>
  22369. <form name="myForm" ng-controller="ExampleController">
  22370. <label>Number:
  22371. <input type="number" name="input" ng-model="example.value"
  22372. min="0" max="99" required>
  22373. </label>
  22374. <div role="alert">
  22375. <span class="error" ng-show="myForm.input.$error.required">
  22376. Required!</span>
  22377. <span class="error" ng-show="myForm.input.$error.number">
  22378. Not valid number!</span>
  22379. </div>
  22380. <tt>value = {{example.value}}</tt><br/>
  22381. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22382. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22383. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22384. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22385. </form>
  22386. </file>
  22387. <file name="protractor.js" type="protractor">
  22388. var value = element(by.binding('example.value'));
  22389. var valid = element(by.binding('myForm.input.$valid'));
  22390. var input = element(by.model('example.value'));
  22391. it('should initialize to model', function() {
  22392. expect(value.getText()).toContain('12');
  22393. expect(valid.getText()).toContain('true');
  22394. });
  22395. it('should be invalid if empty', function() {
  22396. input.clear();
  22397. input.sendKeys('');
  22398. expect(value.getText()).toEqual('value =');
  22399. expect(valid.getText()).toContain('false');
  22400. });
  22401. it('should be invalid if over max', function() {
  22402. input.clear();
  22403. input.sendKeys('123');
  22404. expect(value.getText()).toEqual('value =');
  22405. expect(valid.getText()).toContain('false');
  22406. });
  22407. </file>
  22408. </example>
  22409. */
  22410. 'number': numberInputType,
  22411. /**
  22412. * @ngdoc input
  22413. * @name input[url]
  22414. *
  22415. * @description
  22416. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  22417. * valid URL.
  22418. *
  22419. * <div class="alert alert-warning">
  22420. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  22421. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  22422. * the built-in validators (see the {@link guide/forms Forms guide})
  22423. * </div>
  22424. *
  22425. * @param {string} ngModel Assignable angular expression to data-bind to.
  22426. * @param {string=} name Property name of the form under which the control is published.
  22427. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22428. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22429. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22430. * `required` when you want to data-bind to the `required` attribute.
  22431. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22432. * minlength.
  22433. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22434. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22435. * any length.
  22436. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22437. * that contains the regular expression body that will be converted to a regular expression
  22438. * as in the ngPattern directive.
  22439. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22440. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22441. * If the expression evaluates to a RegExp object, then this is used directly.
  22442. * If the expression evaluates to a string, then it will be converted to a RegExp
  22443. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22444. * `new RegExp('^abc$')`.<br />
  22445. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22446. * start at the index of the last search's match, thus not taking the whole input value into
  22447. * account.
  22448. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22449. * interaction with the input element.
  22450. *
  22451. * @example
  22452. <example name="url-input-directive" module="urlExample">
  22453. <file name="index.html">
  22454. <script>
  22455. angular.module('urlExample', [])
  22456. .controller('ExampleController', ['$scope', function($scope) {
  22457. $scope.url = {
  22458. text: 'http://google.com'
  22459. };
  22460. }]);
  22461. </script>
  22462. <form name="myForm" ng-controller="ExampleController">
  22463. <label>URL:
  22464. <input type="url" name="input" ng-model="url.text" required>
  22465. <label>
  22466. <div role="alert">
  22467. <span class="error" ng-show="myForm.input.$error.required">
  22468. Required!</span>
  22469. <span class="error" ng-show="myForm.input.$error.url">
  22470. Not valid url!</span>
  22471. </div>
  22472. <tt>text = {{url.text}}</tt><br/>
  22473. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22474. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22475. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22476. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22477. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  22478. </form>
  22479. </file>
  22480. <file name="protractor.js" type="protractor">
  22481. var text = element(by.binding('url.text'));
  22482. var valid = element(by.binding('myForm.input.$valid'));
  22483. var input = element(by.model('url.text'));
  22484. it('should initialize to model', function() {
  22485. expect(text.getText()).toContain('http://google.com');
  22486. expect(valid.getText()).toContain('true');
  22487. });
  22488. it('should be invalid if empty', function() {
  22489. input.clear();
  22490. input.sendKeys('');
  22491. expect(text.getText()).toEqual('text =');
  22492. expect(valid.getText()).toContain('false');
  22493. });
  22494. it('should be invalid if not url', function() {
  22495. input.clear();
  22496. input.sendKeys('box');
  22497. expect(valid.getText()).toContain('false');
  22498. });
  22499. </file>
  22500. </example>
  22501. */
  22502. 'url': urlInputType,
  22503. /**
  22504. * @ngdoc input
  22505. * @name input[email]
  22506. *
  22507. * @description
  22508. * Text input with email validation. Sets the `email` validation error key if not a valid email
  22509. * address.
  22510. *
  22511. * <div class="alert alert-warning">
  22512. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  22513. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  22514. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  22515. * </div>
  22516. *
  22517. * @param {string} ngModel Assignable angular expression to data-bind to.
  22518. * @param {string=} name Property name of the form under which the control is published.
  22519. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22520. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22521. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22522. * `required` when you want to data-bind to the `required` attribute.
  22523. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22524. * minlength.
  22525. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22526. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22527. * any length.
  22528. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22529. * that contains the regular expression body that will be converted to a regular expression
  22530. * as in the ngPattern directive.
  22531. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22532. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22533. * If the expression evaluates to a RegExp object, then this is used directly.
  22534. * If the expression evaluates to a string, then it will be converted to a RegExp
  22535. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22536. * `new RegExp('^abc$')`.<br />
  22537. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22538. * start at the index of the last search's match, thus not taking the whole input value into
  22539. * account.
  22540. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22541. * interaction with the input element.
  22542. *
  22543. * @example
  22544. <example name="email-input-directive" module="emailExample">
  22545. <file name="index.html">
  22546. <script>
  22547. angular.module('emailExample', [])
  22548. .controller('ExampleController', ['$scope', function($scope) {
  22549. $scope.email = {
  22550. text: 'me@example.com'
  22551. };
  22552. }]);
  22553. </script>
  22554. <form name="myForm" ng-controller="ExampleController">
  22555. <label>Email:
  22556. <input type="email" name="input" ng-model="email.text" required>
  22557. </label>
  22558. <div role="alert">
  22559. <span class="error" ng-show="myForm.input.$error.required">
  22560. Required!</span>
  22561. <span class="error" ng-show="myForm.input.$error.email">
  22562. Not valid email!</span>
  22563. </div>
  22564. <tt>text = {{email.text}}</tt><br/>
  22565. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22566. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22567. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22568. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22569. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  22570. </form>
  22571. </file>
  22572. <file name="protractor.js" type="protractor">
  22573. var text = element(by.binding('email.text'));
  22574. var valid = element(by.binding('myForm.input.$valid'));
  22575. var input = element(by.model('email.text'));
  22576. it('should initialize to model', function() {
  22577. expect(text.getText()).toContain('me@example.com');
  22578. expect(valid.getText()).toContain('true');
  22579. });
  22580. it('should be invalid if empty', function() {
  22581. input.clear();
  22582. input.sendKeys('');
  22583. expect(text.getText()).toEqual('text =');
  22584. expect(valid.getText()).toContain('false');
  22585. });
  22586. it('should be invalid if not email', function() {
  22587. input.clear();
  22588. input.sendKeys('xxx');
  22589. expect(valid.getText()).toContain('false');
  22590. });
  22591. </file>
  22592. </example>
  22593. */
  22594. 'email': emailInputType,
  22595. /**
  22596. * @ngdoc input
  22597. * @name input[radio]
  22598. *
  22599. * @description
  22600. * HTML radio button.
  22601. *
  22602. * @param {string} ngModel Assignable angular expression to data-bind to.
  22603. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  22604. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  22605. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  22606. * @param {string=} name Property name of the form under which the control is published.
  22607. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22608. * interaction with the input element.
  22609. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  22610. * is selected. Should be used instead of the `value` attribute if you need
  22611. * a non-string `ngModel` (`boolean`, `array`, ...).
  22612. *
  22613. * @example
  22614. <example name="radio-input-directive" module="radioExample">
  22615. <file name="index.html">
  22616. <script>
  22617. angular.module('radioExample', [])
  22618. .controller('ExampleController', ['$scope', function($scope) {
  22619. $scope.color = {
  22620. name: 'blue'
  22621. };
  22622. $scope.specialValue = {
  22623. "id": "12345",
  22624. "value": "green"
  22625. };
  22626. }]);
  22627. </script>
  22628. <form name="myForm" ng-controller="ExampleController">
  22629. <label>
  22630. <input type="radio" ng-model="color.name" value="red">
  22631. Red
  22632. </label><br/>
  22633. <label>
  22634. <input type="radio" ng-model="color.name" ng-value="specialValue">
  22635. Green
  22636. </label><br/>
  22637. <label>
  22638. <input type="radio" ng-model="color.name" value="blue">
  22639. Blue
  22640. </label><br/>
  22641. <tt>color = {{color.name | json}}</tt><br/>
  22642. </form>
  22643. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  22644. </file>
  22645. <file name="protractor.js" type="protractor">
  22646. it('should change state', function() {
  22647. var inputs = element.all(by.model('color.name'));
  22648. var color = element(by.binding('color.name'));
  22649. expect(color.getText()).toContain('blue');
  22650. inputs.get(0).click();
  22651. expect(color.getText()).toContain('red');
  22652. inputs.get(1).click();
  22653. expect(color.getText()).toContain('green');
  22654. });
  22655. </file>
  22656. </example>
  22657. */
  22658. 'radio': radioInputType,
  22659. /**
  22660. * @ngdoc input
  22661. * @name input[range]
  22662. *
  22663. * @description
  22664. * Native range input with validation and transformation.
  22665. *
  22666. * The model for the range input must always be a `Number`.
  22667. *
  22668. * IE9 and other browsers that do not support the `range` type fall back
  22669. * to a text input without any default values for `min`, `max` and `step`. Model binding,
  22670. * validation and number parsing are nevertheless supported.
  22671. *
  22672. * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
  22673. * in a way that never allows the input to hold an invalid value. That means:
  22674. * - any non-numerical value is set to `(max + min) / 2`.
  22675. * - any numerical value that is less than the current min val, or greater than the current max val
  22676. * is set to the min / max val respectively.
  22677. * - additionally, the current `step` is respected, so the nearest value that satisfies a step
  22678. * is used.
  22679. *
  22680. * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
  22681. * for more info.
  22682. *
  22683. * This has the following consequences for Angular:
  22684. *
  22685. * Since the element value should always reflect the current model value, a range input
  22686. * will set the bound ngModel expression to the value that the browser has set for the
  22687. * input element. For example, in the following input `<input type="range" ng-model="model.value">`,
  22688. * if the application sets `model.value = null`, the browser will set the input to `'50'`.
  22689. * Angular will then set the model to `50`, to prevent input and model value being out of sync.
  22690. *
  22691. * That means the model for range will immediately be set to `50` after `ngModel` has been
  22692. * initialized. It also means a range input can never have the required error.
  22693. *
  22694. * This does not only affect changes to the model value, but also to the values of the `min`,
  22695. * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
  22696. * the input value, Angular will also update the model value.
  22697. *
  22698. * Automatic value adjustment also means that a range input element can never have the `required`,
  22699. * `min`, or `max` errors.
  22700. *
  22701. * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
  22702. * when the step value changes dynamically - they do not adjust the element value correctly, but
  22703. * instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step`
  22704. * error on the input, and set the model to `undefined`.
  22705. *
  22706. * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
  22707. * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
  22708. * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
  22709. *
  22710. * @param {string} ngModel Assignable angular expression to data-bind to.
  22711. * @param {string=} name Property name of the form under which the control is published.
  22712. * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
  22713. * than `min`. Can be interpolated.
  22714. * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
  22715. * Can be interpolated.
  22716. * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
  22717. * Can be interpolated.
  22718. * @param {string=} ngChange Angular expression to be executed when the ngModel value changes due
  22719. * to user interaction with the input element.
  22720. * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
  22721. * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
  22722. * Checkout {@link ng.directive:ngChecked ngChecked} for usage.
  22723. *
  22724. * @example
  22725. <example name="range-input-directive" module="rangeExample">
  22726. <file name="index.html">
  22727. <script>
  22728. angular.module('rangeExample', [])
  22729. .controller('ExampleController', ['$scope', function($scope) {
  22730. $scope.value = 75;
  22731. $scope.min = 10;
  22732. $scope.max = 90;
  22733. }]);
  22734. </script>
  22735. <form name="myForm" ng-controller="ExampleController">
  22736. Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
  22737. <hr>
  22738. Model as number: <input type="number" ng-model="value"><br>
  22739. Min: <input type="number" ng-model="min"><br>
  22740. Max: <input type="number" ng-model="max"><br>
  22741. value = <code>{{value}}</code><br/>
  22742. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22743. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22744. </form>
  22745. </file>
  22746. </example>
  22747. * ## Range Input with ngMin & ngMax attributes
  22748. * @example
  22749. <example name="range-input-directive-ng" module="rangeExample">
  22750. <file name="index.html">
  22751. <script>
  22752. angular.module('rangeExample', [])
  22753. .controller('ExampleController', ['$scope', function($scope) {
  22754. $scope.value = 75;
  22755. $scope.min = 10;
  22756. $scope.max = 90;
  22757. }]);
  22758. </script>
  22759. <form name="myForm" ng-controller="ExampleController">
  22760. Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
  22761. <hr>
  22762. Model as number: <input type="number" ng-model="value"><br>
  22763. Min: <input type="number" ng-model="min"><br>
  22764. Max: <input type="number" ng-model="max"><br>
  22765. value = <code>{{value}}</code><br/>
  22766. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22767. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22768. </form>
  22769. </file>
  22770. </example>
  22771. */
  22772. 'range': rangeInputType,
  22773. /**
  22774. * @ngdoc input
  22775. * @name input[checkbox]
  22776. *
  22777. * @description
  22778. * HTML checkbox.
  22779. *
  22780. * @param {string} ngModel Assignable angular expression to data-bind to.
  22781. * @param {string=} name Property name of the form under which the control is published.
  22782. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  22783. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  22784. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22785. * interaction with the input element.
  22786. *
  22787. * @example
  22788. <example name="checkbox-input-directive" module="checkboxExample">
  22789. <file name="index.html">
  22790. <script>
  22791. angular.module('checkboxExample', [])
  22792. .controller('ExampleController', ['$scope', function($scope) {
  22793. $scope.checkboxModel = {
  22794. value1 : true,
  22795. value2 : 'YES'
  22796. };
  22797. }]);
  22798. </script>
  22799. <form name="myForm" ng-controller="ExampleController">
  22800. <label>Value1:
  22801. <input type="checkbox" ng-model="checkboxModel.value1">
  22802. </label><br/>
  22803. <label>Value2:
  22804. <input type="checkbox" ng-model="checkboxModel.value2"
  22805. ng-true-value="'YES'" ng-false-value="'NO'">
  22806. </label><br/>
  22807. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  22808. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  22809. </form>
  22810. </file>
  22811. <file name="protractor.js" type="protractor">
  22812. it('should change state', function() {
  22813. var value1 = element(by.binding('checkboxModel.value1'));
  22814. var value2 = element(by.binding('checkboxModel.value2'));
  22815. expect(value1.getText()).toContain('true');
  22816. expect(value2.getText()).toContain('YES');
  22817. element(by.model('checkboxModel.value1')).click();
  22818. element(by.model('checkboxModel.value2')).click();
  22819. expect(value1.getText()).toContain('false');
  22820. expect(value2.getText()).toContain('NO');
  22821. });
  22822. </file>
  22823. </example>
  22824. */
  22825. 'checkbox': checkboxInputType,
  22826. 'hidden': noop,
  22827. 'button': noop,
  22828. 'submit': noop,
  22829. 'reset': noop,
  22830. 'file': noop
  22831. };
  22832. function stringBasedInputType(ctrl) {
  22833. ctrl.$formatters.push(function(value) {
  22834. return ctrl.$isEmpty(value) ? value : value.toString();
  22835. });
  22836. }
  22837. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22838. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22839. stringBasedInputType(ctrl);
  22840. }
  22841. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22842. var type = lowercase(element[0].type);
  22843. // In composition mode, users are still inputting intermediate text buffer,
  22844. // hold the listener until composition is done.
  22845. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  22846. if (!$sniffer.android) {
  22847. var composing = false;
  22848. element.on('compositionstart', function() {
  22849. composing = true;
  22850. });
  22851. element.on('compositionend', function() {
  22852. composing = false;
  22853. listener();
  22854. });
  22855. }
  22856. var timeout;
  22857. var listener = function(ev) {
  22858. if (timeout) {
  22859. $browser.defer.cancel(timeout);
  22860. timeout = null;
  22861. }
  22862. if (composing) return;
  22863. var value = element.val(),
  22864. event = ev && ev.type;
  22865. // By default we will trim the value
  22866. // If the attribute ng-trim exists we will avoid trimming
  22867. // If input type is 'password', the value is never trimmed
  22868. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  22869. value = trim(value);
  22870. }
  22871. // If a control is suffering from bad input (due to native validators), browsers discard its
  22872. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  22873. // control's value is the same empty value twice in a row.
  22874. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  22875. ctrl.$setViewValue(value, event);
  22876. }
  22877. };
  22878. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  22879. // input event on backspace, delete or cut
  22880. if ($sniffer.hasEvent('input')) {
  22881. element.on('input', listener);
  22882. } else {
  22883. var deferListener = function(ev, input, origValue) {
  22884. if (!timeout) {
  22885. timeout = $browser.defer(function() {
  22886. timeout = null;
  22887. if (!input || input.value !== origValue) {
  22888. listener(ev);
  22889. }
  22890. });
  22891. }
  22892. };
  22893. element.on('keydown', /** @this */ function(event) {
  22894. var key = event.keyCode;
  22895. // ignore
  22896. // command modifiers arrows
  22897. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  22898. deferListener(event, this, this.value);
  22899. });
  22900. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  22901. if ($sniffer.hasEvent('paste')) {
  22902. element.on('paste cut', deferListener);
  22903. }
  22904. }
  22905. // if user paste into input using mouse on older browser
  22906. // or form autocomplete on newer browser, we need "change" event to catch it
  22907. element.on('change', listener);
  22908. // Some native input types (date-family) have the ability to change validity without
  22909. // firing any input/change events.
  22910. // For these event types, when native validators are present and the browser supports the type,
  22911. // check for validity changes on various DOM events.
  22912. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  22913. element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
  22914. if (!timeout) {
  22915. var validity = this[VALIDITY_STATE_PROPERTY];
  22916. var origBadInput = validity.badInput;
  22917. var origTypeMismatch = validity.typeMismatch;
  22918. timeout = $browser.defer(function() {
  22919. timeout = null;
  22920. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  22921. listener(ev);
  22922. }
  22923. });
  22924. }
  22925. });
  22926. }
  22927. ctrl.$render = function() {
  22928. // Workaround for Firefox validation #12102.
  22929. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  22930. if (element.val() !== value) {
  22931. element.val(value);
  22932. }
  22933. };
  22934. }
  22935. function weekParser(isoWeek, existingDate) {
  22936. if (isDate(isoWeek)) {
  22937. return isoWeek;
  22938. }
  22939. if (isString(isoWeek)) {
  22940. WEEK_REGEXP.lastIndex = 0;
  22941. var parts = WEEK_REGEXP.exec(isoWeek);
  22942. if (parts) {
  22943. var year = +parts[1],
  22944. week = +parts[2],
  22945. hours = 0,
  22946. minutes = 0,
  22947. seconds = 0,
  22948. milliseconds = 0,
  22949. firstThurs = getFirstThursdayOfYear(year),
  22950. addDays = (week - 1) * 7;
  22951. if (existingDate) {
  22952. hours = existingDate.getHours();
  22953. minutes = existingDate.getMinutes();
  22954. seconds = existingDate.getSeconds();
  22955. milliseconds = existingDate.getMilliseconds();
  22956. }
  22957. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  22958. }
  22959. }
  22960. return NaN;
  22961. }
  22962. function createDateParser(regexp, mapping) {
  22963. return function(iso, date) {
  22964. var parts, map;
  22965. if (isDate(iso)) {
  22966. return iso;
  22967. }
  22968. if (isString(iso)) {
  22969. // When a date is JSON'ified to wraps itself inside of an extra
  22970. // set of double quotes. This makes the date parsing code unable
  22971. // to match the date string and parse it as a date.
  22972. if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
  22973. iso = iso.substring(1, iso.length - 1);
  22974. }
  22975. if (ISO_DATE_REGEXP.test(iso)) {
  22976. return new Date(iso);
  22977. }
  22978. regexp.lastIndex = 0;
  22979. parts = regexp.exec(iso);
  22980. if (parts) {
  22981. parts.shift();
  22982. if (date) {
  22983. map = {
  22984. yyyy: date.getFullYear(),
  22985. MM: date.getMonth() + 1,
  22986. dd: date.getDate(),
  22987. HH: date.getHours(),
  22988. mm: date.getMinutes(),
  22989. ss: date.getSeconds(),
  22990. sss: date.getMilliseconds() / 1000
  22991. };
  22992. } else {
  22993. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  22994. }
  22995. forEach(parts, function(part, index) {
  22996. if (index < mapping.length) {
  22997. map[mapping[index]] = +part;
  22998. }
  22999. });
  23000. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  23001. }
  23002. }
  23003. return NaN;
  23004. };
  23005. }
  23006. function createDateInputType(type, regexp, parseDate, format) {
  23007. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  23008. badInputChecker(scope, element, attr, ctrl);
  23009. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23010. var timezone = ctrl && ctrl.$options.getOption('timezone');
  23011. var previousDate;
  23012. ctrl.$$parserName = type;
  23013. ctrl.$parsers.push(function(value) {
  23014. if (ctrl.$isEmpty(value)) return null;
  23015. if (regexp.test(value)) {
  23016. // Note: We cannot read ctrl.$modelValue, as there might be a different
  23017. // parser/formatter in the processing chain so that the model
  23018. // contains some different data format!
  23019. var parsedDate = parseDate(value, previousDate);
  23020. if (timezone) {
  23021. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  23022. }
  23023. return parsedDate;
  23024. }
  23025. return undefined;
  23026. });
  23027. ctrl.$formatters.push(function(value) {
  23028. if (value && !isDate(value)) {
  23029. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  23030. }
  23031. if (isValidDate(value)) {
  23032. previousDate = value;
  23033. if (previousDate && timezone) {
  23034. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  23035. }
  23036. return $filter('date')(value, format, timezone);
  23037. } else {
  23038. previousDate = null;
  23039. return '';
  23040. }
  23041. });
  23042. if (isDefined(attr.min) || attr.ngMin) {
  23043. var minVal;
  23044. ctrl.$validators.min = function(value) {
  23045. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  23046. };
  23047. attr.$observe('min', function(val) {
  23048. minVal = parseObservedDateValue(val);
  23049. ctrl.$validate();
  23050. });
  23051. }
  23052. if (isDefined(attr.max) || attr.ngMax) {
  23053. var maxVal;
  23054. ctrl.$validators.max = function(value) {
  23055. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  23056. };
  23057. attr.$observe('max', function(val) {
  23058. maxVal = parseObservedDateValue(val);
  23059. ctrl.$validate();
  23060. });
  23061. }
  23062. function isValidDate(value) {
  23063. // Invalid Date: getTime() returns NaN
  23064. return value && !(value.getTime && value.getTime() !== value.getTime());
  23065. }
  23066. function parseObservedDateValue(val) {
  23067. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  23068. }
  23069. };
  23070. }
  23071. function badInputChecker(scope, element, attr, ctrl) {
  23072. var node = element[0];
  23073. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  23074. if (nativeValidation) {
  23075. ctrl.$parsers.push(function(value) {
  23076. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  23077. return validity.badInput || validity.typeMismatch ? undefined : value;
  23078. });
  23079. }
  23080. }
  23081. function numberFormatterParser(ctrl) {
  23082. ctrl.$$parserName = 'number';
  23083. ctrl.$parsers.push(function(value) {
  23084. if (ctrl.$isEmpty(value)) return null;
  23085. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  23086. return undefined;
  23087. });
  23088. ctrl.$formatters.push(function(value) {
  23089. if (!ctrl.$isEmpty(value)) {
  23090. if (!isNumber(value)) {
  23091. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  23092. }
  23093. value = value.toString();
  23094. }
  23095. return value;
  23096. });
  23097. }
  23098. function parseNumberAttrVal(val) {
  23099. if (isDefined(val) && !isNumber(val)) {
  23100. val = parseFloat(val);
  23101. }
  23102. return !isNumberNaN(val) ? val : undefined;
  23103. }
  23104. function isNumberInteger(num) {
  23105. // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
  23106. // (minus the assumption that `num` is a number)
  23107. // eslint-disable-next-line no-bitwise
  23108. return (num | 0) === num;
  23109. }
  23110. function countDecimals(num) {
  23111. var numString = num.toString();
  23112. var decimalSymbolIndex = numString.indexOf('.');
  23113. if (decimalSymbolIndex === -1) {
  23114. if (-1 < num && num < 1) {
  23115. // It may be in the exponential notation format (`1e-X`)
  23116. var match = /e-(\d+)$/.exec(numString);
  23117. if (match) {
  23118. return Number(match[1]);
  23119. }
  23120. }
  23121. return 0;
  23122. }
  23123. return numString.length - decimalSymbolIndex - 1;
  23124. }
  23125. function isValidForStep(viewValue, stepBase, step) {
  23126. // At this point `stepBase` and `step` are expected to be non-NaN values
  23127. // and `viewValue` is expected to be a valid stringified number.
  23128. var value = Number(viewValue);
  23129. var isNonIntegerValue = !isNumberInteger(value);
  23130. var isNonIntegerStepBase = !isNumberInteger(stepBase);
  23131. var isNonIntegerStep = !isNumberInteger(step);
  23132. // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
  23133. // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
  23134. if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) {
  23135. var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0;
  23136. var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0;
  23137. var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0;
  23138. var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals);
  23139. var multiplier = Math.pow(10, decimalCount);
  23140. value = value * multiplier;
  23141. stepBase = stepBase * multiplier;
  23142. step = step * multiplier;
  23143. if (isNonIntegerValue) value = Math.round(value);
  23144. if (isNonIntegerStepBase) stepBase = Math.round(stepBase);
  23145. if (isNonIntegerStep) step = Math.round(step);
  23146. }
  23147. return (value - stepBase) % step === 0;
  23148. }
  23149. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23150. badInputChecker(scope, element, attr, ctrl);
  23151. numberFormatterParser(ctrl);
  23152. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23153. var minVal;
  23154. var maxVal;
  23155. if (isDefined(attr.min) || attr.ngMin) {
  23156. ctrl.$validators.min = function(value) {
  23157. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  23158. };
  23159. attr.$observe('min', function(val) {
  23160. minVal = parseNumberAttrVal(val);
  23161. // TODO(matsko): implement validateLater to reduce number of validations
  23162. ctrl.$validate();
  23163. });
  23164. }
  23165. if (isDefined(attr.max) || attr.ngMax) {
  23166. ctrl.$validators.max = function(value) {
  23167. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  23168. };
  23169. attr.$observe('max', function(val) {
  23170. maxVal = parseNumberAttrVal(val);
  23171. // TODO(matsko): implement validateLater to reduce number of validations
  23172. ctrl.$validate();
  23173. });
  23174. }
  23175. if (isDefined(attr.step) || attr.ngStep) {
  23176. var stepVal;
  23177. ctrl.$validators.step = function(modelValue, viewValue) {
  23178. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  23179. isValidForStep(viewValue, minVal || 0, stepVal);
  23180. };
  23181. attr.$observe('step', function(val) {
  23182. stepVal = parseNumberAttrVal(val);
  23183. // TODO(matsko): implement validateLater to reduce number of validations
  23184. ctrl.$validate();
  23185. });
  23186. }
  23187. }
  23188. function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23189. badInputChecker(scope, element, attr, ctrl);
  23190. numberFormatterParser(ctrl);
  23191. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23192. var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
  23193. minVal = supportsRange ? 0 : undefined,
  23194. maxVal = supportsRange ? 100 : undefined,
  23195. stepVal = supportsRange ? 1 : undefined,
  23196. validity = element[0].validity,
  23197. hasMinAttr = isDefined(attr.min),
  23198. hasMaxAttr = isDefined(attr.max),
  23199. hasStepAttr = isDefined(attr.step);
  23200. var originalRender = ctrl.$render;
  23201. ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
  23202. //Browsers that implement range will set these values automatically, but reading the adjusted values after
  23203. //$render would cause the min / max validators to be applied with the wrong value
  23204. function rangeRender() {
  23205. originalRender();
  23206. ctrl.$setViewValue(element.val());
  23207. } :
  23208. originalRender;
  23209. if (hasMinAttr) {
  23210. ctrl.$validators.min = supportsRange ?
  23211. // Since all browsers set the input to a valid value, we don't need to check validity
  23212. function noopMinValidator() { return true; } :
  23213. // non-support browsers validate the min val
  23214. function minValidator(modelValue, viewValue) {
  23215. return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
  23216. };
  23217. setInitialValueAndObserver('min', minChange);
  23218. }
  23219. if (hasMaxAttr) {
  23220. ctrl.$validators.max = supportsRange ?
  23221. // Since all browsers set the input to a valid value, we don't need to check validity
  23222. function noopMaxValidator() { return true; } :
  23223. // non-support browsers validate the max val
  23224. function maxValidator(modelValue, viewValue) {
  23225. return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
  23226. };
  23227. setInitialValueAndObserver('max', maxChange);
  23228. }
  23229. if (hasStepAttr) {
  23230. ctrl.$validators.step = supportsRange ?
  23231. function nativeStepValidator() {
  23232. // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
  23233. // input element value to a valid value). It's possible that other browsers set the stepMismatch
  23234. // validity error instead, so we can at least report an error in that case.
  23235. return !validity.stepMismatch;
  23236. } :
  23237. // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
  23238. function stepValidator(modelValue, viewValue) {
  23239. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  23240. isValidForStep(viewValue, minVal || 0, stepVal);
  23241. };
  23242. setInitialValueAndObserver('step', stepChange);
  23243. }
  23244. function setInitialValueAndObserver(htmlAttrName, changeFn) {
  23245. // interpolated attributes set the attribute value only after a digest, but we need the
  23246. // attribute value when the input is first rendered, so that the browser can adjust the
  23247. // input value based on the min/max value
  23248. element.attr(htmlAttrName, attr[htmlAttrName]);
  23249. attr.$observe(htmlAttrName, changeFn);
  23250. }
  23251. function minChange(val) {
  23252. minVal = parseNumberAttrVal(val);
  23253. // ignore changes before model is initialized
  23254. if (isNumberNaN(ctrl.$modelValue)) {
  23255. return;
  23256. }
  23257. if (supportsRange) {
  23258. var elVal = element.val();
  23259. // IE11 doesn't set the el val correctly if the minVal is greater than the element value
  23260. if (minVal > elVal) {
  23261. elVal = minVal;
  23262. element.val(elVal);
  23263. }
  23264. ctrl.$setViewValue(elVal);
  23265. } else {
  23266. // TODO(matsko): implement validateLater to reduce number of validations
  23267. ctrl.$validate();
  23268. }
  23269. }
  23270. function maxChange(val) {
  23271. maxVal = parseNumberAttrVal(val);
  23272. // ignore changes before model is initialized
  23273. if (isNumberNaN(ctrl.$modelValue)) {
  23274. return;
  23275. }
  23276. if (supportsRange) {
  23277. var elVal = element.val();
  23278. // IE11 doesn't set the el val correctly if the maxVal is less than the element value
  23279. if (maxVal < elVal) {
  23280. element.val(maxVal);
  23281. // IE11 and Chrome don't set the value to the minVal when max < min
  23282. elVal = maxVal < minVal ? minVal : maxVal;
  23283. }
  23284. ctrl.$setViewValue(elVal);
  23285. } else {
  23286. // TODO(matsko): implement validateLater to reduce number of validations
  23287. ctrl.$validate();
  23288. }
  23289. }
  23290. function stepChange(val) {
  23291. stepVal = parseNumberAttrVal(val);
  23292. // ignore changes before model is initialized
  23293. if (isNumberNaN(ctrl.$modelValue)) {
  23294. return;
  23295. }
  23296. // Some browsers don't adjust the input value correctly, but set the stepMismatch error
  23297. if (supportsRange && ctrl.$viewValue !== element.val()) {
  23298. ctrl.$setViewValue(element.val());
  23299. } else {
  23300. // TODO(matsko): implement validateLater to reduce number of validations
  23301. ctrl.$validate();
  23302. }
  23303. }
  23304. }
  23305. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23306. // Note: no badInputChecker here by purpose as `url` is only a validation
  23307. // in browsers, i.e. we can always read out input.value even if it is not valid!
  23308. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23309. stringBasedInputType(ctrl);
  23310. ctrl.$$parserName = 'url';
  23311. ctrl.$validators.url = function(modelValue, viewValue) {
  23312. var value = modelValue || viewValue;
  23313. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  23314. };
  23315. }
  23316. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23317. // Note: no badInputChecker here by purpose as `url` is only a validation
  23318. // in browsers, i.e. we can always read out input.value even if it is not valid!
  23319. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23320. stringBasedInputType(ctrl);
  23321. ctrl.$$parserName = 'email';
  23322. ctrl.$validators.email = function(modelValue, viewValue) {
  23323. var value = modelValue || viewValue;
  23324. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  23325. };
  23326. }
  23327. function radioInputType(scope, element, attr, ctrl) {
  23328. var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
  23329. // make the name unique, if not defined
  23330. if (isUndefined(attr.name)) {
  23331. element.attr('name', nextUid());
  23332. }
  23333. var listener = function(ev) {
  23334. var value;
  23335. if (element[0].checked) {
  23336. value = attr.value;
  23337. if (doTrim) {
  23338. value = trim(value);
  23339. }
  23340. ctrl.$setViewValue(value, ev && ev.type);
  23341. }
  23342. };
  23343. element.on('click', listener);
  23344. ctrl.$render = function() {
  23345. var value = attr.value;
  23346. if (doTrim) {
  23347. value = trim(value);
  23348. }
  23349. element[0].checked = (value === ctrl.$viewValue);
  23350. };
  23351. attr.$observe('value', ctrl.$render);
  23352. }
  23353. function parseConstantExpr($parse, context, name, expression, fallback) {
  23354. var parseFn;
  23355. if (isDefined(expression)) {
  23356. parseFn = $parse(expression);
  23357. if (!parseFn.constant) {
  23358. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  23359. '`{1}`.', name, expression);
  23360. }
  23361. return parseFn(context);
  23362. }
  23363. return fallback;
  23364. }
  23365. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  23366. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  23367. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  23368. var listener = function(ev) {
  23369. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  23370. };
  23371. element.on('click', listener);
  23372. ctrl.$render = function() {
  23373. element[0].checked = ctrl.$viewValue;
  23374. };
  23375. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  23376. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  23377. // it to a boolean.
  23378. ctrl.$isEmpty = function(value) {
  23379. return value === false;
  23380. };
  23381. ctrl.$formatters.push(function(value) {
  23382. return equals(value, trueValue);
  23383. });
  23384. ctrl.$parsers.push(function(value) {
  23385. return value ? trueValue : falseValue;
  23386. });
  23387. }
  23388. /**
  23389. * @ngdoc directive
  23390. * @name textarea
  23391. * @restrict E
  23392. *
  23393. * @description
  23394. * HTML textarea element control with angular data-binding. The data-binding and validation
  23395. * properties of this element are exactly the same as those of the
  23396. * {@link ng.directive:input input element}.
  23397. *
  23398. * @param {string} ngModel Assignable angular expression to data-bind to.
  23399. * @param {string=} name Property name of the form under which the control is published.
  23400. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23401. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23402. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23403. * `required` when you want to data-bind to the `required` attribute.
  23404. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23405. * minlength.
  23406. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23407. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  23408. * length.
  23409. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23410. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  23411. * If the expression evaluates to a RegExp object, then this is used directly.
  23412. * If the expression evaluates to a string, then it will be converted to a RegExp
  23413. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23414. * `new RegExp('^abc$')`.<br />
  23415. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23416. * start at the index of the last search's match, thus not taking the whole input value into
  23417. * account.
  23418. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  23419. * interaction with the input element.
  23420. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  23421. *
  23422. * @knownIssue
  23423. *
  23424. * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
  23425. * insert the placeholder value as the textarea's content. If the placeholder value contains
  23426. * interpolation (`{{ ... }}`), an error will be logged in the console when Angular tries to update
  23427. * the value of the by-then-removed text node. This doesn't affect the functionality of the
  23428. * textarea, but can be undesirable.
  23429. *
  23430. * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
  23431. * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
  23432. * find more details on `ngAttr` in the
  23433. * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
  23434. * Developer Guide.
  23435. */
  23436. /**
  23437. * @ngdoc directive
  23438. * @name input
  23439. * @restrict E
  23440. *
  23441. * @description
  23442. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  23443. * input state control, and validation.
  23444. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  23445. *
  23446. * <div class="alert alert-warning">
  23447. * **Note:** Not every feature offered is available for all input types.
  23448. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  23449. * </div>
  23450. *
  23451. * @param {string} ngModel Assignable angular expression to data-bind to.
  23452. * @param {string=} name Property name of the form under which the control is published.
  23453. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23454. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  23455. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23456. * minlength.
  23457. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23458. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  23459. * length.
  23460. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23461. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  23462. * If the expression evaluates to a RegExp object, then this is used directly.
  23463. * If the expression evaluates to a string, then it will be converted to a RegExp
  23464. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23465. * `new RegExp('^abc$')`.<br />
  23466. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23467. * start at the index of the last search's match, thus not taking the whole input value into
  23468. * account.
  23469. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  23470. * interaction with the input element.
  23471. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  23472. * This parameter is ignored for input[type=password] controls, which will never trim the
  23473. * input.
  23474. *
  23475. * @example
  23476. <example name="input-directive" module="inputExample">
  23477. <file name="index.html">
  23478. <script>
  23479. angular.module('inputExample', [])
  23480. .controller('ExampleController', ['$scope', function($scope) {
  23481. $scope.user = {name: 'guest', last: 'visitor'};
  23482. }]);
  23483. </script>
  23484. <div ng-controller="ExampleController">
  23485. <form name="myForm">
  23486. <label>
  23487. User name:
  23488. <input type="text" name="userName" ng-model="user.name" required>
  23489. </label>
  23490. <div role="alert">
  23491. <span class="error" ng-show="myForm.userName.$error.required">
  23492. Required!</span>
  23493. </div>
  23494. <label>
  23495. Last name:
  23496. <input type="text" name="lastName" ng-model="user.last"
  23497. ng-minlength="3" ng-maxlength="10">
  23498. </label>
  23499. <div role="alert">
  23500. <span class="error" ng-show="myForm.lastName.$error.minlength">
  23501. Too short!</span>
  23502. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  23503. Too long!</span>
  23504. </div>
  23505. </form>
  23506. <hr>
  23507. <tt>user = {{user}}</tt><br/>
  23508. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  23509. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  23510. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  23511. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  23512. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23513. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23514. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  23515. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  23516. </div>
  23517. </file>
  23518. <file name="protractor.js" type="protractor">
  23519. var user = element(by.exactBinding('user'));
  23520. var userNameValid = element(by.binding('myForm.userName.$valid'));
  23521. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  23522. var lastNameError = element(by.binding('myForm.lastName.$error'));
  23523. var formValid = element(by.binding('myForm.$valid'));
  23524. var userNameInput = element(by.model('user.name'));
  23525. var userLastInput = element(by.model('user.last'));
  23526. it('should initialize to model', function() {
  23527. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  23528. expect(userNameValid.getText()).toContain('true');
  23529. expect(formValid.getText()).toContain('true');
  23530. });
  23531. it('should be invalid if empty when required', function() {
  23532. userNameInput.clear();
  23533. userNameInput.sendKeys('');
  23534. expect(user.getText()).toContain('{"last":"visitor"}');
  23535. expect(userNameValid.getText()).toContain('false');
  23536. expect(formValid.getText()).toContain('false');
  23537. });
  23538. it('should be valid if empty when min length is set', function() {
  23539. userLastInput.clear();
  23540. userLastInput.sendKeys('');
  23541. expect(user.getText()).toContain('{"name":"guest","last":""}');
  23542. expect(lastNameValid.getText()).toContain('true');
  23543. expect(formValid.getText()).toContain('true');
  23544. });
  23545. it('should be invalid if less than required min length', function() {
  23546. userLastInput.clear();
  23547. userLastInput.sendKeys('xx');
  23548. expect(user.getText()).toContain('{"name":"guest"}');
  23549. expect(lastNameValid.getText()).toContain('false');
  23550. expect(lastNameError.getText()).toContain('minlength');
  23551. expect(formValid.getText()).toContain('false');
  23552. });
  23553. it('should be invalid if longer than max length', function() {
  23554. userLastInput.clear();
  23555. userLastInput.sendKeys('some ridiculously long name');
  23556. expect(user.getText()).toContain('{"name":"guest"}');
  23557. expect(lastNameValid.getText()).toContain('false');
  23558. expect(lastNameError.getText()).toContain('maxlength');
  23559. expect(formValid.getText()).toContain('false');
  23560. });
  23561. </file>
  23562. </example>
  23563. */
  23564. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  23565. function($browser, $sniffer, $filter, $parse) {
  23566. return {
  23567. restrict: 'E',
  23568. require: ['?ngModel'],
  23569. link: {
  23570. pre: function(scope, element, attr, ctrls) {
  23571. if (ctrls[0]) {
  23572. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  23573. $browser, $filter, $parse);
  23574. }
  23575. }
  23576. }
  23577. };
  23578. }];
  23579. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  23580. /**
  23581. * @ngdoc directive
  23582. * @name ngValue
  23583. *
  23584. * @description
  23585. * Binds the given expression to the value of the element.
  23586. *
  23587. * It is mainly used on {@link input[radio] `input[radio]`} and option elements,
  23588. * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
  23589. * {@link select `select`} parent element) is set to the bound value. It is especially useful
  23590. * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
  23591. *
  23592. * It can also be used to achieve one-way binding of a given expression to an input element
  23593. * such as an `input[text]` or a `textarea`, when that element does not use ngModel.
  23594. *
  23595. * @element input
  23596. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  23597. * and `value` property of the element.
  23598. *
  23599. * @example
  23600. <example name="ngValue-directive" module="valueExample">
  23601. <file name="index.html">
  23602. <script>
  23603. angular.module('valueExample', [])
  23604. .controller('ExampleController', ['$scope', function($scope) {
  23605. $scope.names = ['pizza', 'unicorns', 'robots'];
  23606. $scope.my = { favorite: 'unicorns' };
  23607. }]);
  23608. </script>
  23609. <form ng-controller="ExampleController">
  23610. <h2>Which is your favorite?</h2>
  23611. <label ng-repeat="name in names" for="{{name}}">
  23612. {{name}}
  23613. <input type="radio"
  23614. ng-model="my.favorite"
  23615. ng-value="name"
  23616. id="{{name}}"
  23617. name="favorite">
  23618. </label>
  23619. <div>You chose {{my.favorite}}</div>
  23620. </form>
  23621. </file>
  23622. <file name="protractor.js" type="protractor">
  23623. var favorite = element(by.binding('my.favorite'));
  23624. it('should initialize to model', function() {
  23625. expect(favorite.getText()).toContain('unicorns');
  23626. });
  23627. it('should bind the values to the inputs', function() {
  23628. element.all(by.model('my.favorite')).get(0).click();
  23629. expect(favorite.getText()).toContain('pizza');
  23630. });
  23631. </file>
  23632. </example>
  23633. */
  23634. var ngValueDirective = function() {
  23635. /**
  23636. * inputs use the value attribute as their default value if the value property is not set.
  23637. * Once the value property has been set (by adding input), it will not react to changes to
  23638. * the value attribute anymore. Setting both attribute and property fixes this behavior, and
  23639. * makes it possible to use ngValue as a sort of one-way bind.
  23640. */
  23641. function updateElementValue(element, attr, value) {
  23642. // Support: IE9 only
  23643. // In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`).
  23644. var propValue = isDefined(value) ? value : (msie === 9) ? '' : null;
  23645. element.prop('value', propValue);
  23646. attr.$set('value', value);
  23647. }
  23648. return {
  23649. restrict: 'A',
  23650. priority: 100,
  23651. compile: function(tpl, tplAttr) {
  23652. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  23653. return function ngValueConstantLink(scope, elm, attr) {
  23654. var value = scope.$eval(attr.ngValue);
  23655. updateElementValue(elm, attr, value);
  23656. };
  23657. } else {
  23658. return function ngValueLink(scope, elm, attr) {
  23659. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  23660. updateElementValue(elm, attr, value);
  23661. });
  23662. };
  23663. }
  23664. }
  23665. };
  23666. };
  23667. /**
  23668. * @ngdoc directive
  23669. * @name ngBind
  23670. * @restrict AC
  23671. *
  23672. * @description
  23673. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  23674. * with the value of a given expression, and to update the text content when the value of that
  23675. * expression changes.
  23676. *
  23677. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  23678. * `{{ expression }}` which is similar but less verbose.
  23679. *
  23680. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  23681. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  23682. * element attribute, it makes the bindings invisible to the user while the page is loading.
  23683. *
  23684. * An alternative solution to this problem would be using the
  23685. * {@link ng.directive:ngCloak ngCloak} directive.
  23686. *
  23687. *
  23688. * @element ANY
  23689. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  23690. *
  23691. * @example
  23692. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  23693. <example module="bindExample" name="ng-bind">
  23694. <file name="index.html">
  23695. <script>
  23696. angular.module('bindExample', [])
  23697. .controller('ExampleController', ['$scope', function($scope) {
  23698. $scope.name = 'Whirled';
  23699. }]);
  23700. </script>
  23701. <div ng-controller="ExampleController">
  23702. <label>Enter name: <input type="text" ng-model="name"></label><br>
  23703. Hello <span ng-bind="name"></span>!
  23704. </div>
  23705. </file>
  23706. <file name="protractor.js" type="protractor">
  23707. it('should check ng-bind', function() {
  23708. var nameInput = element(by.model('name'));
  23709. expect(element(by.binding('name')).getText()).toBe('Whirled');
  23710. nameInput.clear();
  23711. nameInput.sendKeys('world');
  23712. expect(element(by.binding('name')).getText()).toBe('world');
  23713. });
  23714. </file>
  23715. </example>
  23716. */
  23717. var ngBindDirective = ['$compile', function($compile) {
  23718. return {
  23719. restrict: 'AC',
  23720. compile: function ngBindCompile(templateElement) {
  23721. $compile.$$addBindingClass(templateElement);
  23722. return function ngBindLink(scope, element, attr) {
  23723. $compile.$$addBindingInfo(element, attr.ngBind);
  23724. element = element[0];
  23725. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  23726. element.textContent = stringify(value);
  23727. });
  23728. };
  23729. }
  23730. };
  23731. }];
  23732. /**
  23733. * @ngdoc directive
  23734. * @name ngBindTemplate
  23735. *
  23736. * @description
  23737. * The `ngBindTemplate` directive specifies that the element
  23738. * text content should be replaced with the interpolation of the template
  23739. * in the `ngBindTemplate` attribute.
  23740. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  23741. * expressions. This directive is needed since some HTML elements
  23742. * (such as TITLE and OPTION) cannot contain SPAN elements.
  23743. *
  23744. * @element ANY
  23745. * @param {string} ngBindTemplate template of form
  23746. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  23747. *
  23748. * @example
  23749. * Try it here: enter text in text box and watch the greeting change.
  23750. <example module="bindExample" name="ng-bind-template">
  23751. <file name="index.html">
  23752. <script>
  23753. angular.module('bindExample', [])
  23754. .controller('ExampleController', ['$scope', function($scope) {
  23755. $scope.salutation = 'Hello';
  23756. $scope.name = 'World';
  23757. }]);
  23758. </script>
  23759. <div ng-controller="ExampleController">
  23760. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  23761. <label>Name: <input type="text" ng-model="name"></label><br>
  23762. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  23763. </div>
  23764. </file>
  23765. <file name="protractor.js" type="protractor">
  23766. it('should check ng-bind', function() {
  23767. var salutationElem = element(by.binding('salutation'));
  23768. var salutationInput = element(by.model('salutation'));
  23769. var nameInput = element(by.model('name'));
  23770. expect(salutationElem.getText()).toBe('Hello World!');
  23771. salutationInput.clear();
  23772. salutationInput.sendKeys('Greetings');
  23773. nameInput.clear();
  23774. nameInput.sendKeys('user');
  23775. expect(salutationElem.getText()).toBe('Greetings user!');
  23776. });
  23777. </file>
  23778. </example>
  23779. */
  23780. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  23781. return {
  23782. compile: function ngBindTemplateCompile(templateElement) {
  23783. $compile.$$addBindingClass(templateElement);
  23784. return function ngBindTemplateLink(scope, element, attr) {
  23785. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  23786. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  23787. element = element[0];
  23788. attr.$observe('ngBindTemplate', function(value) {
  23789. element.textContent = isUndefined(value) ? '' : value;
  23790. });
  23791. };
  23792. }
  23793. };
  23794. }];
  23795. /**
  23796. * @ngdoc directive
  23797. * @name ngBindHtml
  23798. *
  23799. * @description
  23800. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  23801. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  23802. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  23803. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  23804. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  23805. *
  23806. * You may also bypass sanitization for values you know are safe. To do so, bind to
  23807. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  23808. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  23809. *
  23810. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  23811. * will have an exception (instead of an exploit.)
  23812. *
  23813. * @element ANY
  23814. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  23815. *
  23816. * @example
  23817. <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
  23818. <file name="index.html">
  23819. <div ng-controller="ExampleController">
  23820. <p ng-bind-html="myHTML"></p>
  23821. </div>
  23822. </file>
  23823. <file name="script.js">
  23824. angular.module('bindHtmlExample', ['ngSanitize'])
  23825. .controller('ExampleController', ['$scope', function($scope) {
  23826. $scope.myHTML =
  23827. 'I am an <code>HTML</code>string with ' +
  23828. '<a href="#">links!</a> and other <em>stuff</em>';
  23829. }]);
  23830. </file>
  23831. <file name="protractor.js" type="protractor">
  23832. it('should check ng-bind-html', function() {
  23833. expect(element(by.binding('myHTML')).getText()).toBe(
  23834. 'I am an HTMLstring with links! and other stuff');
  23835. });
  23836. </file>
  23837. </example>
  23838. */
  23839. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  23840. return {
  23841. restrict: 'A',
  23842. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  23843. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  23844. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  23845. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  23846. return $sce.valueOf(val);
  23847. });
  23848. $compile.$$addBindingClass(tElement);
  23849. return function ngBindHtmlLink(scope, element, attr) {
  23850. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  23851. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  23852. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  23853. var value = ngBindHtmlGetter(scope);
  23854. element.html($sce.getTrustedHtml(value) || '');
  23855. });
  23856. };
  23857. }
  23858. };
  23859. }];
  23860. /**
  23861. * @ngdoc directive
  23862. * @name ngChange
  23863. *
  23864. * @description
  23865. * Evaluate the given expression when the user changes the input.
  23866. * The expression is evaluated immediately, unlike the JavaScript onchange event
  23867. * which only triggers at the end of a change (usually, when the user leaves the
  23868. * form element or presses the return key).
  23869. *
  23870. * The `ngChange` expression is only evaluated when a change in the input value causes
  23871. * a new value to be committed to the model.
  23872. *
  23873. * It will not be evaluated:
  23874. * * if the value returned from the `$parsers` transformation pipeline has not changed
  23875. * * if the input has continued to be invalid since the model will stay `null`
  23876. * * if the model is changed programmatically and not by a change to the input value
  23877. *
  23878. *
  23879. * Note, this directive requires `ngModel` to be present.
  23880. *
  23881. * @element input
  23882. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  23883. * in input value.
  23884. *
  23885. * @example
  23886. * <example name="ngChange-directive" module="changeExample">
  23887. * <file name="index.html">
  23888. * <script>
  23889. * angular.module('changeExample', [])
  23890. * .controller('ExampleController', ['$scope', function($scope) {
  23891. * $scope.counter = 0;
  23892. * $scope.change = function() {
  23893. * $scope.counter++;
  23894. * };
  23895. * }]);
  23896. * </script>
  23897. * <div ng-controller="ExampleController">
  23898. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  23899. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  23900. * <label for="ng-change-example2">Confirmed</label><br />
  23901. * <tt>debug = {{confirmed}}</tt><br/>
  23902. * <tt>counter = {{counter}}</tt><br/>
  23903. * </div>
  23904. * </file>
  23905. * <file name="protractor.js" type="protractor">
  23906. * var counter = element(by.binding('counter'));
  23907. * var debug = element(by.binding('confirmed'));
  23908. *
  23909. * it('should evaluate the expression if changing from view', function() {
  23910. * expect(counter.getText()).toContain('0');
  23911. *
  23912. * element(by.id('ng-change-example1')).click();
  23913. *
  23914. * expect(counter.getText()).toContain('1');
  23915. * expect(debug.getText()).toContain('true');
  23916. * });
  23917. *
  23918. * it('should not evaluate the expression if changing from model', function() {
  23919. * element(by.id('ng-change-example2')).click();
  23920. * expect(counter.getText()).toContain('0');
  23921. * expect(debug.getText()).toContain('true');
  23922. * });
  23923. * </file>
  23924. * </example>
  23925. */
  23926. var ngChangeDirective = valueFn({
  23927. restrict: 'A',
  23928. require: 'ngModel',
  23929. link: function(scope, element, attr, ctrl) {
  23930. ctrl.$viewChangeListeners.push(function() {
  23931. scope.$eval(attr.ngChange);
  23932. });
  23933. }
  23934. });
  23935. /* exported
  23936. ngClassDirective,
  23937. ngClassEvenDirective,
  23938. ngClassOddDirective
  23939. */
  23940. function classDirective(name, selector) {
  23941. name = 'ngClass' + name;
  23942. var indexWatchExpression;
  23943. return ['$parse', function($parse) {
  23944. return {
  23945. restrict: 'AC',
  23946. link: function(scope, element, attr) {
  23947. var expression = attr[name].trim();
  23948. var isOneTime = (expression.charAt(0) === ':') && (expression.charAt(1) === ':');
  23949. var watchInterceptor = isOneTime ? toFlatValue : toClassString;
  23950. var watchExpression = $parse(expression, watchInterceptor);
  23951. var watchAction = isOneTime ? ngClassOneTimeWatchAction : ngClassWatchAction;
  23952. var classCounts = element.data('$classCounts');
  23953. var oldModulo = true;
  23954. var oldClassString;
  23955. if (!classCounts) {
  23956. // Use createMap() to prevent class assumptions involving property
  23957. // names in Object.prototype
  23958. classCounts = createMap();
  23959. element.data('$classCounts', classCounts);
  23960. }
  23961. if (name !== 'ngClass') {
  23962. if (!indexWatchExpression) {
  23963. indexWatchExpression = $parse('$index', function moduloTwo($index) {
  23964. // eslint-disable-next-line no-bitwise
  23965. return $index & 1;
  23966. });
  23967. }
  23968. scope.$watch(indexWatchExpression, ngClassIndexWatchAction);
  23969. }
  23970. scope.$watch(watchExpression, watchAction, isOneTime);
  23971. function addClasses(classString) {
  23972. classString = digestClassCounts(split(classString), 1);
  23973. attr.$addClass(classString);
  23974. }
  23975. function removeClasses(classString) {
  23976. classString = digestClassCounts(split(classString), -1);
  23977. attr.$removeClass(classString);
  23978. }
  23979. function updateClasses(oldClassString, newClassString) {
  23980. var oldClassArray = split(oldClassString);
  23981. var newClassArray = split(newClassString);
  23982. var toRemoveArray = arrayDifference(oldClassArray, newClassArray);
  23983. var toAddArray = arrayDifference(newClassArray, oldClassArray);
  23984. var toRemoveString = digestClassCounts(toRemoveArray, -1);
  23985. var toAddString = digestClassCounts(toAddArray, 1);
  23986. attr.$addClass(toAddString);
  23987. attr.$removeClass(toRemoveString);
  23988. }
  23989. function digestClassCounts(classArray, count) {
  23990. var classesToUpdate = [];
  23991. forEach(classArray, function(className) {
  23992. if (count > 0 || classCounts[className]) {
  23993. classCounts[className] = (classCounts[className] || 0) + count;
  23994. if (classCounts[className] === +(count > 0)) {
  23995. classesToUpdate.push(className);
  23996. }
  23997. }
  23998. });
  23999. return classesToUpdate.join(' ');
  24000. }
  24001. function ngClassIndexWatchAction(newModulo) {
  24002. // This watch-action should run before the `ngClass[OneTime]WatchAction()`, thus it
  24003. // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the
  24004. // `ngClass[OneTime]WatchAction()` will update the classes.
  24005. if (newModulo === selector) {
  24006. addClasses(oldClassString);
  24007. } else {
  24008. removeClasses(oldClassString);
  24009. }
  24010. oldModulo = newModulo;
  24011. }
  24012. function ngClassOneTimeWatchAction(newClassValue) {
  24013. var newClassString = toClassString(newClassValue);
  24014. if (newClassString !== oldClassString) {
  24015. ngClassWatchAction(newClassString);
  24016. }
  24017. }
  24018. function ngClassWatchAction(newClassString) {
  24019. if (oldModulo === selector) {
  24020. updateClasses(oldClassString, newClassString);
  24021. }
  24022. oldClassString = newClassString;
  24023. }
  24024. }
  24025. };
  24026. }];
  24027. // Helpers
  24028. function arrayDifference(tokens1, tokens2) {
  24029. if (!tokens1 || !tokens1.length) return [];
  24030. if (!tokens2 || !tokens2.length) return tokens1;
  24031. var values = [];
  24032. outer:
  24033. for (var i = 0; i < tokens1.length; i++) {
  24034. var token = tokens1[i];
  24035. for (var j = 0; j < tokens2.length; j++) {
  24036. if (token === tokens2[j]) continue outer;
  24037. }
  24038. values.push(token);
  24039. }
  24040. return values;
  24041. }
  24042. function split(classString) {
  24043. return classString && classString.split(' ');
  24044. }
  24045. function toClassString(classValue) {
  24046. var classString = classValue;
  24047. if (isArray(classValue)) {
  24048. classString = classValue.map(toClassString).join(' ');
  24049. } else if (isObject(classValue)) {
  24050. classString = Object.keys(classValue).
  24051. filter(function(key) { return classValue[key]; }).
  24052. join(' ');
  24053. }
  24054. return classString;
  24055. }
  24056. function toFlatValue(classValue) {
  24057. var flatValue = classValue;
  24058. if (isArray(classValue)) {
  24059. flatValue = classValue.map(toFlatValue);
  24060. } else if (isObject(classValue)) {
  24061. var hasUndefined = false;
  24062. flatValue = Object.keys(classValue).filter(function(key) {
  24063. var value = classValue[key];
  24064. if (!hasUndefined && isUndefined(value)) {
  24065. hasUndefined = true;
  24066. }
  24067. return value;
  24068. });
  24069. if (hasUndefined) {
  24070. // Prevent the `oneTimeLiteralWatchInterceptor` from unregistering
  24071. // the watcher, by including at least one `undefined` value.
  24072. flatValue.push(undefined);
  24073. }
  24074. }
  24075. return flatValue;
  24076. }
  24077. }
  24078. /**
  24079. * @ngdoc directive
  24080. * @name ngClass
  24081. * @restrict AC
  24082. *
  24083. * @description
  24084. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  24085. * an expression that represents all classes to be added.
  24086. *
  24087. * The directive operates in three different ways, depending on which of three types the expression
  24088. * evaluates to:
  24089. *
  24090. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  24091. * names.
  24092. *
  24093. * 2. If the expression evaluates to an object, then for each key-value pair of the
  24094. * object with a truthy value the corresponding key is used as a class name.
  24095. *
  24096. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  24097. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  24098. * to give you more control over what CSS classes appear. See the code below for an example of this.
  24099. *
  24100. *
  24101. * The directive won't add duplicate classes if a particular class was already set.
  24102. *
  24103. * When the expression changes, the previously added classes are removed and only then are the
  24104. * new classes added.
  24105. *
  24106. * @knownIssue
  24107. * You should not use {@link guide/interpolation interpolation} in the value of the `class`
  24108. * attribute, when using the `ngClass` directive on the same element.
  24109. * See {@link guide/interpolation#known-issues here} for more info.
  24110. *
  24111. * @animations
  24112. * | Animation | Occurs |
  24113. * |----------------------------------|-------------------------------------|
  24114. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  24115. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  24116. *
  24117. * @element ANY
  24118. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  24119. * of the evaluation can be a string representing space delimited class
  24120. * names, an array, or a map of class names to boolean values. In the case of a map, the
  24121. * names of the properties whose values are truthy will be added as css classes to the
  24122. * element.
  24123. *
  24124. * @example Example that demonstrates basic bindings via ngClass directive.
  24125. <example name="ng-class">
  24126. <file name="index.html">
  24127. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  24128. <label>
  24129. <input type="checkbox" ng-model="deleted">
  24130. deleted (apply "strike" class)
  24131. </label><br>
  24132. <label>
  24133. <input type="checkbox" ng-model="important">
  24134. important (apply "bold" class)
  24135. </label><br>
  24136. <label>
  24137. <input type="checkbox" ng-model="error">
  24138. error (apply "has-error" class)
  24139. </label>
  24140. <hr>
  24141. <p ng-class="style">Using String Syntax</p>
  24142. <input type="text" ng-model="style"
  24143. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  24144. <hr>
  24145. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  24146. <input ng-model="style1"
  24147. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  24148. <input ng-model="style2"
  24149. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  24150. <input ng-model="style3"
  24151. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  24152. <hr>
  24153. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  24154. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  24155. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  24156. </file>
  24157. <file name="style.css">
  24158. .strike {
  24159. text-decoration: line-through;
  24160. }
  24161. .bold {
  24162. font-weight: bold;
  24163. }
  24164. .red {
  24165. color: red;
  24166. }
  24167. .has-error {
  24168. color: red;
  24169. background-color: yellow;
  24170. }
  24171. .orange {
  24172. color: orange;
  24173. }
  24174. </file>
  24175. <file name="protractor.js" type="protractor">
  24176. var ps = element.all(by.css('p'));
  24177. it('should let you toggle the class', function() {
  24178. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  24179. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  24180. element(by.model('important')).click();
  24181. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  24182. element(by.model('error')).click();
  24183. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  24184. });
  24185. it('should let you toggle string example', function() {
  24186. expect(ps.get(1).getAttribute('class')).toBe('');
  24187. element(by.model('style')).clear();
  24188. element(by.model('style')).sendKeys('red');
  24189. expect(ps.get(1).getAttribute('class')).toBe('red');
  24190. });
  24191. it('array example should have 3 classes', function() {
  24192. expect(ps.get(2).getAttribute('class')).toBe('');
  24193. element(by.model('style1')).sendKeys('bold');
  24194. element(by.model('style2')).sendKeys('strike');
  24195. element(by.model('style3')).sendKeys('red');
  24196. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  24197. });
  24198. it('array with map example should have 2 classes', function() {
  24199. expect(ps.last().getAttribute('class')).toBe('');
  24200. element(by.model('style4')).sendKeys('bold');
  24201. element(by.model('warning')).click();
  24202. expect(ps.last().getAttribute('class')).toBe('bold orange');
  24203. });
  24204. </file>
  24205. </example>
  24206. ## Animations
  24207. The example below demonstrates how to perform animations using ngClass.
  24208. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
  24209. <file name="index.html">
  24210. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  24211. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  24212. <br>
  24213. <span class="base-class" ng-class="myVar">Sample Text</span>
  24214. </file>
  24215. <file name="style.css">
  24216. .base-class {
  24217. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24218. }
  24219. .base-class.my-class {
  24220. color: red;
  24221. font-size:3em;
  24222. }
  24223. </file>
  24224. <file name="protractor.js" type="protractor">
  24225. it('should check ng-class', function() {
  24226. expect(element(by.css('.base-class')).getAttribute('class')).not.
  24227. toMatch(/my-class/);
  24228. element(by.id('setbtn')).click();
  24229. expect(element(by.css('.base-class')).getAttribute('class')).
  24230. toMatch(/my-class/);
  24231. element(by.id('clearbtn')).click();
  24232. expect(element(by.css('.base-class')).getAttribute('class')).not.
  24233. toMatch(/my-class/);
  24234. });
  24235. </file>
  24236. </example>
  24237. ## ngClass and pre-existing CSS3 Transitions/Animations
  24238. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  24239. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  24240. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  24241. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  24242. {@link $animate#removeClass $animate.removeClass}.
  24243. */
  24244. var ngClassDirective = classDirective('', true);
  24245. /**
  24246. * @ngdoc directive
  24247. * @name ngClassOdd
  24248. * @restrict AC
  24249. *
  24250. * @description
  24251. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  24252. * {@link ng.directive:ngClass ngClass}, except they work in
  24253. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  24254. *
  24255. * This directive can be applied only within the scope of an
  24256. * {@link ng.directive:ngRepeat ngRepeat}.
  24257. *
  24258. * @element ANY
  24259. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  24260. * of the evaluation can be a string representing space delimited class names or an array.
  24261. *
  24262. * @example
  24263. <example name="ng-class-odd">
  24264. <file name="index.html">
  24265. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  24266. <li ng-repeat="name in names">
  24267. <span ng-class-odd="'odd'" ng-class-even="'even'">
  24268. {{name}}
  24269. </span>
  24270. </li>
  24271. </ol>
  24272. </file>
  24273. <file name="style.css">
  24274. .odd {
  24275. color: red;
  24276. }
  24277. .even {
  24278. color: blue;
  24279. }
  24280. </file>
  24281. <file name="protractor.js" type="protractor">
  24282. it('should check ng-class-odd and ng-class-even', function() {
  24283. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  24284. toMatch(/odd/);
  24285. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  24286. toMatch(/even/);
  24287. });
  24288. </file>
  24289. </example>
  24290. */
  24291. var ngClassOddDirective = classDirective('Odd', 0);
  24292. /**
  24293. * @ngdoc directive
  24294. * @name ngClassEven
  24295. * @restrict AC
  24296. *
  24297. * @description
  24298. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  24299. * {@link ng.directive:ngClass ngClass}, except they work in
  24300. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  24301. *
  24302. * This directive can be applied only within the scope of an
  24303. * {@link ng.directive:ngRepeat ngRepeat}.
  24304. *
  24305. * @element ANY
  24306. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  24307. * result of the evaluation can be a string representing space delimited class names or an array.
  24308. *
  24309. * @example
  24310. <example name="ng-class-even">
  24311. <file name="index.html">
  24312. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  24313. <li ng-repeat="name in names">
  24314. <span ng-class-odd="'odd'" ng-class-even="'even'">
  24315. {{name}} &nbsp; &nbsp; &nbsp;
  24316. </span>
  24317. </li>
  24318. </ol>
  24319. </file>
  24320. <file name="style.css">
  24321. .odd {
  24322. color: red;
  24323. }
  24324. .even {
  24325. color: blue;
  24326. }
  24327. </file>
  24328. <file name="protractor.js" type="protractor">
  24329. it('should check ng-class-odd and ng-class-even', function() {
  24330. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  24331. toMatch(/odd/);
  24332. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  24333. toMatch(/even/);
  24334. });
  24335. </file>
  24336. </example>
  24337. */
  24338. var ngClassEvenDirective = classDirective('Even', 1);
  24339. /**
  24340. * @ngdoc directive
  24341. * @name ngCloak
  24342. * @restrict AC
  24343. *
  24344. * @description
  24345. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  24346. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  24347. * directive to avoid the undesirable flicker effect caused by the html template display.
  24348. *
  24349. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  24350. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  24351. * of the browser view.
  24352. *
  24353. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  24354. * `angular.min.js`.
  24355. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24356. *
  24357. * ```css
  24358. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  24359. * display: none !important;
  24360. * }
  24361. * ```
  24362. *
  24363. * When this css rule is loaded by the browser, all html elements (including their children) that
  24364. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  24365. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  24366. * the compiled element visible.
  24367. *
  24368. * For the best result, the `angular.js` script must be loaded in the head section of the html
  24369. * document; alternatively, the css rule above must be included in the external stylesheet of the
  24370. * application.
  24371. *
  24372. * @element ANY
  24373. *
  24374. * @example
  24375. <example name="ng-cloak">
  24376. <file name="index.html">
  24377. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  24378. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  24379. </file>
  24380. <file name="protractor.js" type="protractor">
  24381. it('should remove the template directive and css class', function() {
  24382. expect($('#template1').getAttribute('ng-cloak')).
  24383. toBeNull();
  24384. expect($('#template2').getAttribute('ng-cloak')).
  24385. toBeNull();
  24386. });
  24387. </file>
  24388. </example>
  24389. *
  24390. */
  24391. var ngCloakDirective = ngDirective({
  24392. compile: function(element, attr) {
  24393. attr.$set('ngCloak', undefined);
  24394. element.removeClass('ng-cloak');
  24395. }
  24396. });
  24397. /**
  24398. * @ngdoc directive
  24399. * @name ngController
  24400. *
  24401. * @description
  24402. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  24403. * supports the principles behind the Model-View-Controller design pattern.
  24404. *
  24405. * MVC components in angular:
  24406. *
  24407. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  24408. * are accessed through bindings.
  24409. * * View — The template (HTML with data bindings) that is rendered into the View.
  24410. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  24411. * logic behind the application to decorate the scope with functions and values
  24412. *
  24413. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  24414. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  24415. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  24416. * and executed twice.
  24417. *
  24418. * @element ANY
  24419. * @scope
  24420. * @priority 500
  24421. * @param {expression} ngController Name of a constructor function registered with the current
  24422. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  24423. * that on the current scope evaluates to a constructor function.
  24424. *
  24425. * The controller instance can be published into a scope property by specifying
  24426. * `ng-controller="as propertyName"`.
  24427. *
  24428. * If the current `$controllerProvider` is configured to use globals (via
  24429. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  24430. * also be the name of a globally accessible constructor function (deprecated, not recommended).
  24431. *
  24432. * @example
  24433. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  24434. * greeting are methods declared on the controller (see source tab). These methods can
  24435. * easily be called from the angular markup. Any changes to the data are automatically reflected
  24436. * in the View without the need for a manual update.
  24437. *
  24438. * Two different declaration styles are included below:
  24439. *
  24440. * * one binds methods and properties directly onto the controller using `this`:
  24441. * `ng-controller="SettingsController1 as settings"`
  24442. * * one injects `$scope` into the controller:
  24443. * `ng-controller="SettingsController2"`
  24444. *
  24445. * The second option is more common in the Angular community, and is generally used in boilerplates
  24446. * and in this guide. However, there are advantages to binding properties directly to the controller
  24447. * and avoiding scope.
  24448. *
  24449. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  24450. * multiple controllers apply to an element.
  24451. * * If you are writing your controllers as classes you have easier access to the properties and
  24452. * methods, which will appear on the scope, from inside the controller code.
  24453. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  24454. * inheritance masking primitives.
  24455. *
  24456. * This example demonstrates the `controller as` syntax.
  24457. *
  24458. * <example name="ngControllerAs" module="controllerAsExample">
  24459. * <file name="index.html">
  24460. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  24461. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  24462. * <button ng-click="settings.greet()">greet</button><br/>
  24463. * Contact:
  24464. * <ul>
  24465. * <li ng-repeat="contact in settings.contacts">
  24466. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  24467. * <option>phone</option>
  24468. * <option>email</option>
  24469. * </select>
  24470. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24471. * <button ng-click="settings.clearContact(contact)">clear</button>
  24472. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  24473. * </li>
  24474. * <li><button ng-click="settings.addContact()">add</button></li>
  24475. * </ul>
  24476. * </div>
  24477. * </file>
  24478. * <file name="app.js">
  24479. * angular.module('controllerAsExample', [])
  24480. * .controller('SettingsController1', SettingsController1);
  24481. *
  24482. * function SettingsController1() {
  24483. * this.name = 'John Smith';
  24484. * this.contacts = [
  24485. * {type: 'phone', value: '408 555 1212'},
  24486. * {type: 'email', value: 'john.smith@example.org'}
  24487. * ];
  24488. * }
  24489. *
  24490. * SettingsController1.prototype.greet = function() {
  24491. * alert(this.name);
  24492. * };
  24493. *
  24494. * SettingsController1.prototype.addContact = function() {
  24495. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  24496. * };
  24497. *
  24498. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  24499. * var index = this.contacts.indexOf(contactToRemove);
  24500. * this.contacts.splice(index, 1);
  24501. * };
  24502. *
  24503. * SettingsController1.prototype.clearContact = function(contact) {
  24504. * contact.type = 'phone';
  24505. * contact.value = '';
  24506. * };
  24507. * </file>
  24508. * <file name="protractor.js" type="protractor">
  24509. * it('should check controller as', function() {
  24510. * var container = element(by.id('ctrl-as-exmpl'));
  24511. * expect(container.element(by.model('settings.name'))
  24512. * .getAttribute('value')).toBe('John Smith');
  24513. *
  24514. * var firstRepeat =
  24515. * container.element(by.repeater('contact in settings.contacts').row(0));
  24516. * var secondRepeat =
  24517. * container.element(by.repeater('contact in settings.contacts').row(1));
  24518. *
  24519. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24520. * .toBe('408 555 1212');
  24521. *
  24522. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24523. * .toBe('john.smith@example.org');
  24524. *
  24525. * firstRepeat.element(by.buttonText('clear')).click();
  24526. *
  24527. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24528. * .toBe('');
  24529. *
  24530. * container.element(by.buttonText('add')).click();
  24531. *
  24532. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  24533. * .element(by.model('contact.value'))
  24534. * .getAttribute('value'))
  24535. * .toBe('yourname@example.org');
  24536. * });
  24537. * </file>
  24538. * </example>
  24539. *
  24540. * This example demonstrates the "attach to `$scope`" style of controller.
  24541. *
  24542. * <example name="ngController" module="controllerExample">
  24543. * <file name="index.html">
  24544. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  24545. * <label>Name: <input type="text" ng-model="name"/></label>
  24546. * <button ng-click="greet()">greet</button><br/>
  24547. * Contact:
  24548. * <ul>
  24549. * <li ng-repeat="contact in contacts">
  24550. * <select ng-model="contact.type" id="select_{{$index}}">
  24551. * <option>phone</option>
  24552. * <option>email</option>
  24553. * </select>
  24554. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24555. * <button ng-click="clearContact(contact)">clear</button>
  24556. * <button ng-click="removeContact(contact)">X</button>
  24557. * </li>
  24558. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  24559. * </ul>
  24560. * </div>
  24561. * </file>
  24562. * <file name="app.js">
  24563. * angular.module('controllerExample', [])
  24564. * .controller('SettingsController2', ['$scope', SettingsController2]);
  24565. *
  24566. * function SettingsController2($scope) {
  24567. * $scope.name = 'John Smith';
  24568. * $scope.contacts = [
  24569. * {type:'phone', value:'408 555 1212'},
  24570. * {type:'email', value:'john.smith@example.org'}
  24571. * ];
  24572. *
  24573. * $scope.greet = function() {
  24574. * alert($scope.name);
  24575. * };
  24576. *
  24577. * $scope.addContact = function() {
  24578. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  24579. * };
  24580. *
  24581. * $scope.removeContact = function(contactToRemove) {
  24582. * var index = $scope.contacts.indexOf(contactToRemove);
  24583. * $scope.contacts.splice(index, 1);
  24584. * };
  24585. *
  24586. * $scope.clearContact = function(contact) {
  24587. * contact.type = 'phone';
  24588. * contact.value = '';
  24589. * };
  24590. * }
  24591. * </file>
  24592. * <file name="protractor.js" type="protractor">
  24593. * it('should check controller', function() {
  24594. * var container = element(by.id('ctrl-exmpl'));
  24595. *
  24596. * expect(container.element(by.model('name'))
  24597. * .getAttribute('value')).toBe('John Smith');
  24598. *
  24599. * var firstRepeat =
  24600. * container.element(by.repeater('contact in contacts').row(0));
  24601. * var secondRepeat =
  24602. * container.element(by.repeater('contact in contacts').row(1));
  24603. *
  24604. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24605. * .toBe('408 555 1212');
  24606. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24607. * .toBe('john.smith@example.org');
  24608. *
  24609. * firstRepeat.element(by.buttonText('clear')).click();
  24610. *
  24611. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24612. * .toBe('');
  24613. *
  24614. * container.element(by.buttonText('add')).click();
  24615. *
  24616. * expect(container.element(by.repeater('contact in contacts').row(2))
  24617. * .element(by.model('contact.value'))
  24618. * .getAttribute('value'))
  24619. * .toBe('yourname@example.org');
  24620. * });
  24621. * </file>
  24622. *</example>
  24623. */
  24624. var ngControllerDirective = [function() {
  24625. return {
  24626. restrict: 'A',
  24627. scope: true,
  24628. controller: '@',
  24629. priority: 500
  24630. };
  24631. }];
  24632. /**
  24633. * @ngdoc directive
  24634. * @name ngCsp
  24635. *
  24636. * @restrict A
  24637. * @element ANY
  24638. * @description
  24639. *
  24640. * Angular has some features that can conflict with certain restrictions that are applied when using
  24641. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  24642. *
  24643. * If you intend to implement CSP with these rules then you must tell Angular not to use these
  24644. * features.
  24645. *
  24646. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  24647. *
  24648. *
  24649. * The following default rules in CSP affect Angular:
  24650. *
  24651. * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute
  24652. * code from strings is forbidden. Angular makes use of this in the {@link $parse} service to
  24653. * provide a 30% increase in the speed of evaluating Angular expressions. (This CSP rule can be
  24654. * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would
  24655. * weaken the protections offered by CSP.)
  24656. *
  24657. * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden.
  24658. * This prevents apps from injecting custom styles directly into the document. Angular makes use of
  24659. * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these
  24660. * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css`
  24661. * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but
  24662. * it is generally not recommended as it would weaken the protections offered by CSP.)
  24663. *
  24664. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking dynamic code
  24665. * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically
  24666. * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a
  24667. * CSP error to be logged in the console:
  24668. *
  24669. * ```
  24670. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  24671. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  24672. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  24673. * ```
  24674. *
  24675. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  24676. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  24677. * the `angular.js` file.
  24678. *
  24679. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  24680. *
  24681. * You can specify which of the CSP related Angular features should be deactivated by providing
  24682. * a value for the `ng-csp` attribute. The options are as follows:
  24683. *
  24684. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  24685. *
  24686. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  24687. *
  24688. * You can use these values in the following combinations:
  24689. *
  24690. *
  24691. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  24692. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous
  24693. * versions of Angular.
  24694. *
  24695. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  24696. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous
  24697. * versions of Angular.
  24698. *
  24699. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can
  24700. * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  24701. *
  24702. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  24703. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  24704. *
  24705. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  24706. * styles nor use eval, which is the same as an empty: ng-csp.
  24707. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  24708. *
  24709. * @example
  24710. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  24711. ```html
  24712. <!doctype html>
  24713. <html ng-app ng-csp>
  24714. ...
  24715. ...
  24716. </html>
  24717. ```
  24718. * @example
  24719. <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! -->
  24720. <example name="example.csp" module="cspExample" ng-csp="true">
  24721. <file name="index.html">
  24722. <div ng-controller="MainController as ctrl">
  24723. <div>
  24724. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  24725. <span id="counter">
  24726. {{ctrl.counter}}
  24727. </span>
  24728. </div>
  24729. <div>
  24730. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  24731. <span id="evilError">
  24732. {{ctrl.evilError}}
  24733. </span>
  24734. </div>
  24735. </div>
  24736. </file>
  24737. <file name="script.js">
  24738. angular.module('cspExample', [])
  24739. .controller('MainController', function MainController() {
  24740. this.counter = 0;
  24741. this.inc = function() {
  24742. this.counter++;
  24743. };
  24744. this.evil = function() {
  24745. try {
  24746. eval('1+2'); // eslint-disable-line no-eval
  24747. } catch (e) {
  24748. this.evilError = e.message;
  24749. }
  24750. };
  24751. });
  24752. </file>
  24753. <file name="protractor.js" type="protractor">
  24754. var util, webdriver;
  24755. var incBtn = element(by.id('inc'));
  24756. var counter = element(by.id('counter'));
  24757. var evilBtn = element(by.id('evil'));
  24758. var evilError = element(by.id('evilError'));
  24759. function getAndClearSevereErrors() {
  24760. return browser.manage().logs().get('browser').then(function(browserLog) {
  24761. return browserLog.filter(function(logEntry) {
  24762. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  24763. });
  24764. });
  24765. }
  24766. function clearErrors() {
  24767. getAndClearSevereErrors();
  24768. }
  24769. function expectNoErrors() {
  24770. getAndClearSevereErrors().then(function(filteredLog) {
  24771. expect(filteredLog.length).toEqual(0);
  24772. if (filteredLog.length) {
  24773. console.log('browser console errors: ' + util.inspect(filteredLog));
  24774. }
  24775. });
  24776. }
  24777. function expectError(regex) {
  24778. getAndClearSevereErrors().then(function(filteredLog) {
  24779. var found = false;
  24780. filteredLog.forEach(function(log) {
  24781. if (log.message.match(regex)) {
  24782. found = true;
  24783. }
  24784. });
  24785. if (!found) {
  24786. throw new Error('expected an error that matches ' + regex);
  24787. }
  24788. });
  24789. }
  24790. beforeEach(function() {
  24791. util = require('util');
  24792. webdriver = require('selenium-webdriver');
  24793. });
  24794. // For now, we only test on Chrome,
  24795. // as Safari does not load the page with Protractor's injected scripts,
  24796. // and Firefox webdriver always disables content security policy (#6358)
  24797. if (browser.params.browser !== 'chrome') {
  24798. return;
  24799. }
  24800. it('should not report errors when the page is loaded', function() {
  24801. // clear errors so we are not dependent on previous tests
  24802. clearErrors();
  24803. // Need to reload the page as the page is already loaded when
  24804. // we come here
  24805. browser.driver.getCurrentUrl().then(function(url) {
  24806. browser.get(url);
  24807. });
  24808. expectNoErrors();
  24809. });
  24810. it('should evaluate expressions', function() {
  24811. expect(counter.getText()).toEqual('0');
  24812. incBtn.click();
  24813. expect(counter.getText()).toEqual('1');
  24814. expectNoErrors();
  24815. });
  24816. it('should throw and report an error when using "eval"', function() {
  24817. evilBtn.click();
  24818. expect(evilError.getText()).toMatch(/Content Security Policy/);
  24819. expectError(/Content Security Policy/);
  24820. });
  24821. </file>
  24822. </example>
  24823. */
  24824. // `ngCsp` is not implemented as a proper directive any more, because we need it be processed while
  24825. // we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()`
  24826. // fn that looks for the `ng-csp` attribute anywhere in the current doc.
  24827. /**
  24828. * @ngdoc directive
  24829. * @name ngClick
  24830. *
  24831. * @description
  24832. * The ngClick directive allows you to specify custom behavior when
  24833. * an element is clicked.
  24834. *
  24835. * @element ANY
  24836. * @priority 0
  24837. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  24838. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  24839. *
  24840. * @example
  24841. <example name="ng-click">
  24842. <file name="index.html">
  24843. <button ng-click="count = count + 1" ng-init="count=0">
  24844. Increment
  24845. </button>
  24846. <span>
  24847. count: {{count}}
  24848. </span>
  24849. </file>
  24850. <file name="protractor.js" type="protractor">
  24851. it('should check ng-click', function() {
  24852. expect(element(by.binding('count')).getText()).toMatch('0');
  24853. element(by.css('button')).click();
  24854. expect(element(by.binding('count')).getText()).toMatch('1');
  24855. });
  24856. </file>
  24857. </example>
  24858. */
  24859. /*
  24860. * A collection of directives that allows creation of custom event handlers that are defined as
  24861. * angular expressions and are compiled and executed within the current scope.
  24862. */
  24863. var ngEventDirectives = {};
  24864. // For events that might fire synchronously during DOM manipulation
  24865. // we need to execute their event handlers asynchronously using $evalAsync,
  24866. // so that they are not executed in an inconsistent state.
  24867. var forceAsyncEvents = {
  24868. 'blur': true,
  24869. 'focus': true
  24870. };
  24871. forEach(
  24872. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  24873. function(eventName) {
  24874. var directiveName = directiveNormalize('ng-' + eventName);
  24875. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  24876. return {
  24877. restrict: 'A',
  24878. compile: function($element, attr) {
  24879. // NOTE:
  24880. // We expose the powerful `$event` object on the scope that provides access to the Window,
  24881. // etc. This is OK, because expressions are not sandboxed any more (and the expression
  24882. // sandbox was never meant to be a security feature anyway).
  24883. var fn = $parse(attr[directiveName]);
  24884. return function ngEventHandler(scope, element) {
  24885. element.on(eventName, function(event) {
  24886. var callback = function() {
  24887. fn(scope, {$event: event});
  24888. };
  24889. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  24890. scope.$evalAsync(callback);
  24891. } else {
  24892. scope.$apply(callback);
  24893. }
  24894. });
  24895. };
  24896. }
  24897. };
  24898. }];
  24899. }
  24900. );
  24901. /**
  24902. * @ngdoc directive
  24903. * @name ngDblclick
  24904. *
  24905. * @description
  24906. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  24907. *
  24908. * @element ANY
  24909. * @priority 0
  24910. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  24911. * a dblclick. (The Event object is available as `$event`)
  24912. *
  24913. * @example
  24914. <example name="ng-dblclick">
  24915. <file name="index.html">
  24916. <button ng-dblclick="count = count + 1" ng-init="count=0">
  24917. Increment (on double click)
  24918. </button>
  24919. count: {{count}}
  24920. </file>
  24921. </example>
  24922. */
  24923. /**
  24924. * @ngdoc directive
  24925. * @name ngMousedown
  24926. *
  24927. * @description
  24928. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  24929. *
  24930. * @element ANY
  24931. * @priority 0
  24932. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  24933. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  24934. *
  24935. * @example
  24936. <example name="ng-mousedown">
  24937. <file name="index.html">
  24938. <button ng-mousedown="count = count + 1" ng-init="count=0">
  24939. Increment (on mouse down)
  24940. </button>
  24941. count: {{count}}
  24942. </file>
  24943. </example>
  24944. */
  24945. /**
  24946. * @ngdoc directive
  24947. * @name ngMouseup
  24948. *
  24949. * @description
  24950. * Specify custom behavior on mouseup event.
  24951. *
  24952. * @element ANY
  24953. * @priority 0
  24954. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  24955. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  24956. *
  24957. * @example
  24958. <example name="ng-mouseup">
  24959. <file name="index.html">
  24960. <button ng-mouseup="count = count + 1" ng-init="count=0">
  24961. Increment (on mouse up)
  24962. </button>
  24963. count: {{count}}
  24964. </file>
  24965. </example>
  24966. */
  24967. /**
  24968. * @ngdoc directive
  24969. * @name ngMouseover
  24970. *
  24971. * @description
  24972. * Specify custom behavior on mouseover event.
  24973. *
  24974. * @element ANY
  24975. * @priority 0
  24976. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  24977. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  24978. *
  24979. * @example
  24980. <example name="ng-mouseover">
  24981. <file name="index.html">
  24982. <button ng-mouseover="count = count + 1" ng-init="count=0">
  24983. Increment (when mouse is over)
  24984. </button>
  24985. count: {{count}}
  24986. </file>
  24987. </example>
  24988. */
  24989. /**
  24990. * @ngdoc directive
  24991. * @name ngMouseenter
  24992. *
  24993. * @description
  24994. * Specify custom behavior on mouseenter event.
  24995. *
  24996. * @element ANY
  24997. * @priority 0
  24998. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  24999. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  25000. *
  25001. * @example
  25002. <example name="ng-mouseenter">
  25003. <file name="index.html">
  25004. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  25005. Increment (when mouse enters)
  25006. </button>
  25007. count: {{count}}
  25008. </file>
  25009. </example>
  25010. */
  25011. /**
  25012. * @ngdoc directive
  25013. * @name ngMouseleave
  25014. *
  25015. * @description
  25016. * Specify custom behavior on mouseleave event.
  25017. *
  25018. * @element ANY
  25019. * @priority 0
  25020. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  25021. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  25022. *
  25023. * @example
  25024. <example name="ng-mouseleave">
  25025. <file name="index.html">
  25026. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  25027. Increment (when mouse leaves)
  25028. </button>
  25029. count: {{count}}
  25030. </file>
  25031. </example>
  25032. */
  25033. /**
  25034. * @ngdoc directive
  25035. * @name ngMousemove
  25036. *
  25037. * @description
  25038. * Specify custom behavior on mousemove event.
  25039. *
  25040. * @element ANY
  25041. * @priority 0
  25042. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  25043. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  25044. *
  25045. * @example
  25046. <example name="ng-mousemove">
  25047. <file name="index.html">
  25048. <button ng-mousemove="count = count + 1" ng-init="count=0">
  25049. Increment (when mouse moves)
  25050. </button>
  25051. count: {{count}}
  25052. </file>
  25053. </example>
  25054. */
  25055. /**
  25056. * @ngdoc directive
  25057. * @name ngKeydown
  25058. *
  25059. * @description
  25060. * Specify custom behavior on keydown event.
  25061. *
  25062. * @element ANY
  25063. * @priority 0
  25064. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  25065. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  25066. *
  25067. * @example
  25068. <example name="ng-keydown">
  25069. <file name="index.html">
  25070. <input ng-keydown="count = count + 1" ng-init="count=0">
  25071. key down count: {{count}}
  25072. </file>
  25073. </example>
  25074. */
  25075. /**
  25076. * @ngdoc directive
  25077. * @name ngKeyup
  25078. *
  25079. * @description
  25080. * Specify custom behavior on keyup event.
  25081. *
  25082. * @element ANY
  25083. * @priority 0
  25084. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  25085. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  25086. *
  25087. * @example
  25088. <example name="ng-keyup">
  25089. <file name="index.html">
  25090. <p>Typing in the input box below updates the key count</p>
  25091. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  25092. <p>Typing in the input box below updates the keycode</p>
  25093. <input ng-keyup="event=$event">
  25094. <p>event keyCode: {{ event.keyCode }}</p>
  25095. <p>event altKey: {{ event.altKey }}</p>
  25096. </file>
  25097. </example>
  25098. */
  25099. /**
  25100. * @ngdoc directive
  25101. * @name ngKeypress
  25102. *
  25103. * @description
  25104. * Specify custom behavior on keypress event.
  25105. *
  25106. * @element ANY
  25107. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  25108. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  25109. * and can be interrogated for keyCode, altKey, etc.)
  25110. *
  25111. * @example
  25112. <example name="ng-keypress">
  25113. <file name="index.html">
  25114. <input ng-keypress="count = count + 1" ng-init="count=0">
  25115. key press count: {{count}}
  25116. </file>
  25117. </example>
  25118. */
  25119. /**
  25120. * @ngdoc directive
  25121. * @name ngSubmit
  25122. *
  25123. * @description
  25124. * Enables binding angular expressions to onsubmit events.
  25125. *
  25126. * Additionally it prevents the default action (which for form means sending the request to the
  25127. * server and reloading the current page), but only if the form does not contain `action`,
  25128. * `data-action`, or `x-action` attributes.
  25129. *
  25130. * <div class="alert alert-warning">
  25131. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  25132. * `ngSubmit` handlers together. See the
  25133. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  25134. * for a detailed discussion of when `ngSubmit` may be triggered.
  25135. * </div>
  25136. *
  25137. * @element form
  25138. * @priority 0
  25139. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  25140. * ({@link guide/expression#-event- Event object is available as `$event`})
  25141. *
  25142. * @example
  25143. <example module="submitExample" name="ng-submit">
  25144. <file name="index.html">
  25145. <script>
  25146. angular.module('submitExample', [])
  25147. .controller('ExampleController', ['$scope', function($scope) {
  25148. $scope.list = [];
  25149. $scope.text = 'hello';
  25150. $scope.submit = function() {
  25151. if ($scope.text) {
  25152. $scope.list.push(this.text);
  25153. $scope.text = '';
  25154. }
  25155. };
  25156. }]);
  25157. </script>
  25158. <form ng-submit="submit()" ng-controller="ExampleController">
  25159. Enter text and hit enter:
  25160. <input type="text" ng-model="text" name="text" />
  25161. <input type="submit" id="submit" value="Submit" />
  25162. <pre>list={{list}}</pre>
  25163. </form>
  25164. </file>
  25165. <file name="protractor.js" type="protractor">
  25166. it('should check ng-submit', function() {
  25167. expect(element(by.binding('list')).getText()).toBe('list=[]');
  25168. element(by.css('#submit')).click();
  25169. expect(element(by.binding('list')).getText()).toContain('hello');
  25170. expect(element(by.model('text')).getAttribute('value')).toBe('');
  25171. });
  25172. it('should ignore empty strings', function() {
  25173. expect(element(by.binding('list')).getText()).toBe('list=[]');
  25174. element(by.css('#submit')).click();
  25175. element(by.css('#submit')).click();
  25176. expect(element(by.binding('list')).getText()).toContain('hello');
  25177. });
  25178. </file>
  25179. </example>
  25180. */
  25181. /**
  25182. * @ngdoc directive
  25183. * @name ngFocus
  25184. *
  25185. * @description
  25186. * Specify custom behavior on focus event.
  25187. *
  25188. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  25189. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  25190. * during an `$apply` to ensure a consistent state.
  25191. *
  25192. * @element window, input, select, textarea, a
  25193. * @priority 0
  25194. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  25195. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  25196. *
  25197. * @example
  25198. * See {@link ng.directive:ngClick ngClick}
  25199. */
  25200. /**
  25201. * @ngdoc directive
  25202. * @name ngBlur
  25203. *
  25204. * @description
  25205. * Specify custom behavior on blur event.
  25206. *
  25207. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  25208. * an element has lost focus.
  25209. *
  25210. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  25211. * (e.g. removing a focussed input),
  25212. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  25213. * during an `$apply` to ensure a consistent state.
  25214. *
  25215. * @element window, input, select, textarea, a
  25216. * @priority 0
  25217. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  25218. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  25219. *
  25220. * @example
  25221. * See {@link ng.directive:ngClick ngClick}
  25222. */
  25223. /**
  25224. * @ngdoc directive
  25225. * @name ngCopy
  25226. *
  25227. * @description
  25228. * Specify custom behavior on copy event.
  25229. *
  25230. * @element window, input, select, textarea, a
  25231. * @priority 0
  25232. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  25233. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  25234. *
  25235. * @example
  25236. <example name="ng-copy">
  25237. <file name="index.html">
  25238. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  25239. copied: {{copied}}
  25240. </file>
  25241. </example>
  25242. */
  25243. /**
  25244. * @ngdoc directive
  25245. * @name ngCut
  25246. *
  25247. * @description
  25248. * Specify custom behavior on cut event.
  25249. *
  25250. * @element window, input, select, textarea, a
  25251. * @priority 0
  25252. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  25253. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  25254. *
  25255. * @example
  25256. <example name="ng-cut">
  25257. <file name="index.html">
  25258. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  25259. cut: {{cut}}
  25260. </file>
  25261. </example>
  25262. */
  25263. /**
  25264. * @ngdoc directive
  25265. * @name ngPaste
  25266. *
  25267. * @description
  25268. * Specify custom behavior on paste event.
  25269. *
  25270. * @element window, input, select, textarea, a
  25271. * @priority 0
  25272. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  25273. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  25274. *
  25275. * @example
  25276. <example name="ng-paste">
  25277. <file name="index.html">
  25278. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  25279. pasted: {{paste}}
  25280. </file>
  25281. </example>
  25282. */
  25283. /**
  25284. * @ngdoc directive
  25285. * @name ngIf
  25286. * @restrict A
  25287. * @multiElement
  25288. *
  25289. * @description
  25290. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  25291. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  25292. * value then the element is removed from the DOM, otherwise a clone of the
  25293. * element is reinserted into the DOM.
  25294. *
  25295. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  25296. * element in the DOM rather than changing its visibility via the `display` css property. A common
  25297. * case when this difference is significant is when using css selectors that rely on an element's
  25298. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  25299. *
  25300. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  25301. * is created when the element is restored. The scope created within `ngIf` inherits from
  25302. * its parent scope using
  25303. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  25304. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  25305. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  25306. * variable within the child scope will override (hide) the value in the parent scope.
  25307. *
  25308. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  25309. * is if an element's class attribute is directly modified after it's compiled, using something like
  25310. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  25311. * the added class will be lost because the original compiled state is used to regenerate the element.
  25312. *
  25313. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  25314. * and `leave` effects.
  25315. *
  25316. * @animations
  25317. * | Animation | Occurs |
  25318. * |----------------------------------|-------------------------------------|
  25319. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  25320. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  25321. *
  25322. * @element ANY
  25323. * @scope
  25324. * @priority 600
  25325. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  25326. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  25327. * element is added to the DOM tree.
  25328. *
  25329. * @example
  25330. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
  25331. <file name="index.html">
  25332. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  25333. Show when checked:
  25334. <span ng-if="checked" class="animate-if">
  25335. This is removed when the checkbox is unchecked.
  25336. </span>
  25337. </file>
  25338. <file name="animations.css">
  25339. .animate-if {
  25340. background:white;
  25341. border:1px solid black;
  25342. padding:10px;
  25343. }
  25344. .animate-if.ng-enter, .animate-if.ng-leave {
  25345. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25346. }
  25347. .animate-if.ng-enter,
  25348. .animate-if.ng-leave.ng-leave-active {
  25349. opacity:0;
  25350. }
  25351. .animate-if.ng-leave,
  25352. .animate-if.ng-enter.ng-enter-active {
  25353. opacity:1;
  25354. }
  25355. </file>
  25356. </example>
  25357. */
  25358. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  25359. return {
  25360. multiElement: true,
  25361. transclude: 'element',
  25362. priority: 600,
  25363. terminal: true,
  25364. restrict: 'A',
  25365. $$tlb: true,
  25366. link: function($scope, $element, $attr, ctrl, $transclude) {
  25367. var block, childScope, previousElements;
  25368. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  25369. if (value) {
  25370. if (!childScope) {
  25371. $transclude(function(clone, newScope) {
  25372. childScope = newScope;
  25373. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  25374. // Note: We only need the first/last node of the cloned nodes.
  25375. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  25376. // by a directive with templateUrl when its template arrives.
  25377. block = {
  25378. clone: clone
  25379. };
  25380. $animate.enter(clone, $element.parent(), $element);
  25381. });
  25382. }
  25383. } else {
  25384. if (previousElements) {
  25385. previousElements.remove();
  25386. previousElements = null;
  25387. }
  25388. if (childScope) {
  25389. childScope.$destroy();
  25390. childScope = null;
  25391. }
  25392. if (block) {
  25393. previousElements = getBlockNodes(block.clone);
  25394. $animate.leave(previousElements).done(function(response) {
  25395. if (response !== false) previousElements = null;
  25396. });
  25397. block = null;
  25398. }
  25399. }
  25400. });
  25401. }
  25402. };
  25403. }];
  25404. /**
  25405. * @ngdoc directive
  25406. * @name ngInclude
  25407. * @restrict ECA
  25408. *
  25409. * @description
  25410. * Fetches, compiles and includes an external HTML fragment.
  25411. *
  25412. * By default, the template URL is restricted to the same domain and protocol as the
  25413. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  25414. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  25415. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  25416. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  25417. * ng.$sce Strict Contextual Escaping}.
  25418. *
  25419. * In addition, the browser's
  25420. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  25421. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  25422. * policy may further restrict whether the template is successfully loaded.
  25423. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  25424. * access on some browsers.
  25425. *
  25426. * @animations
  25427. * | Animation | Occurs |
  25428. * |----------------------------------|-------------------------------------|
  25429. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  25430. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  25431. *
  25432. * The enter and leave animation occur concurrently.
  25433. *
  25434. * @scope
  25435. * @priority 400
  25436. *
  25437. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  25438. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  25439. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  25440. * <div class="alert alert-warning">
  25441. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  25442. * a function with the name on the window element, which will usually throw a
  25443. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  25444. * different form that {@link guide/directive#normalization matches} `onload`.
  25445. * </div>
  25446. *
  25447. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  25448. * $anchorScroll} to scroll the viewport after the content is loaded.
  25449. *
  25450. * - If the attribute is not set, disable scrolling.
  25451. * - If the attribute is set without value, enable scrolling.
  25452. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  25453. *
  25454. * @example
  25455. <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
  25456. <file name="index.html">
  25457. <div ng-controller="ExampleController">
  25458. <select ng-model="template" ng-options="t.name for t in templates">
  25459. <option value="">(blank)</option>
  25460. </select>
  25461. url of the template: <code>{{template.url}}</code>
  25462. <hr/>
  25463. <div class="slide-animate-container">
  25464. <div class="slide-animate" ng-include="template.url"></div>
  25465. </div>
  25466. </div>
  25467. </file>
  25468. <file name="script.js">
  25469. angular.module('includeExample', ['ngAnimate'])
  25470. .controller('ExampleController', ['$scope', function($scope) {
  25471. $scope.templates =
  25472. [{ name: 'template1.html', url: 'template1.html'},
  25473. { name: 'template2.html', url: 'template2.html'}];
  25474. $scope.template = $scope.templates[0];
  25475. }]);
  25476. </file>
  25477. <file name="template1.html">
  25478. Content of template1.html
  25479. </file>
  25480. <file name="template2.html">
  25481. Content of template2.html
  25482. </file>
  25483. <file name="animations.css">
  25484. .slide-animate-container {
  25485. position:relative;
  25486. background:white;
  25487. border:1px solid black;
  25488. height:40px;
  25489. overflow:hidden;
  25490. }
  25491. .slide-animate {
  25492. padding:10px;
  25493. }
  25494. .slide-animate.ng-enter, .slide-animate.ng-leave {
  25495. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25496. position:absolute;
  25497. top:0;
  25498. left:0;
  25499. right:0;
  25500. bottom:0;
  25501. display:block;
  25502. padding:10px;
  25503. }
  25504. .slide-animate.ng-enter {
  25505. top:-50px;
  25506. }
  25507. .slide-animate.ng-enter.ng-enter-active {
  25508. top:0;
  25509. }
  25510. .slide-animate.ng-leave {
  25511. top:0;
  25512. }
  25513. .slide-animate.ng-leave.ng-leave-active {
  25514. top:50px;
  25515. }
  25516. </file>
  25517. <file name="protractor.js" type="protractor">
  25518. var templateSelect = element(by.model('template'));
  25519. var includeElem = element(by.css('[ng-include]'));
  25520. it('should load template1.html', function() {
  25521. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  25522. });
  25523. it('should load template2.html', function() {
  25524. if (browser.params.browser === 'firefox') {
  25525. // Firefox can't handle using selects
  25526. // See https://github.com/angular/protractor/issues/480
  25527. return;
  25528. }
  25529. templateSelect.click();
  25530. templateSelect.all(by.css('option')).get(2).click();
  25531. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  25532. });
  25533. it('should change to blank', function() {
  25534. if (browser.params.browser === 'firefox') {
  25535. // Firefox can't handle using selects
  25536. return;
  25537. }
  25538. templateSelect.click();
  25539. templateSelect.all(by.css('option')).get(0).click();
  25540. expect(includeElem.isPresent()).toBe(false);
  25541. });
  25542. </file>
  25543. </example>
  25544. */
  25545. /**
  25546. * @ngdoc event
  25547. * @name ngInclude#$includeContentRequested
  25548. * @eventType emit on the scope ngInclude was declared in
  25549. * @description
  25550. * Emitted every time the ngInclude content is requested.
  25551. *
  25552. * @param {Object} angularEvent Synthetic event object.
  25553. * @param {String} src URL of content to load.
  25554. */
  25555. /**
  25556. * @ngdoc event
  25557. * @name ngInclude#$includeContentLoaded
  25558. * @eventType emit on the current ngInclude scope
  25559. * @description
  25560. * Emitted every time the ngInclude content is reloaded.
  25561. *
  25562. * @param {Object} angularEvent Synthetic event object.
  25563. * @param {String} src URL of content to load.
  25564. */
  25565. /**
  25566. * @ngdoc event
  25567. * @name ngInclude#$includeContentError
  25568. * @eventType emit on the scope ngInclude was declared in
  25569. * @description
  25570. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  25571. *
  25572. * @param {Object} angularEvent Synthetic event object.
  25573. * @param {String} src URL of content to load.
  25574. */
  25575. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  25576. function($templateRequest, $anchorScroll, $animate) {
  25577. return {
  25578. restrict: 'ECA',
  25579. priority: 400,
  25580. terminal: true,
  25581. transclude: 'element',
  25582. controller: angular.noop,
  25583. compile: function(element, attr) {
  25584. var srcExp = attr.ngInclude || attr.src,
  25585. onloadExp = attr.onload || '',
  25586. autoScrollExp = attr.autoscroll;
  25587. return function(scope, $element, $attr, ctrl, $transclude) {
  25588. var changeCounter = 0,
  25589. currentScope,
  25590. previousElement,
  25591. currentElement;
  25592. var cleanupLastIncludeContent = function() {
  25593. if (previousElement) {
  25594. previousElement.remove();
  25595. previousElement = null;
  25596. }
  25597. if (currentScope) {
  25598. currentScope.$destroy();
  25599. currentScope = null;
  25600. }
  25601. if (currentElement) {
  25602. $animate.leave(currentElement).done(function(response) {
  25603. if (response !== false) previousElement = null;
  25604. });
  25605. previousElement = currentElement;
  25606. currentElement = null;
  25607. }
  25608. };
  25609. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  25610. var afterAnimation = function(response) {
  25611. if (response !== false && isDefined(autoScrollExp) &&
  25612. (!autoScrollExp || scope.$eval(autoScrollExp))) {
  25613. $anchorScroll();
  25614. }
  25615. };
  25616. var thisChangeId = ++changeCounter;
  25617. if (src) {
  25618. //set the 2nd param to true to ignore the template request error so that the inner
  25619. //contents and scope can be cleaned up.
  25620. $templateRequest(src, true).then(function(response) {
  25621. if (scope.$$destroyed) return;
  25622. if (thisChangeId !== changeCounter) return;
  25623. var newScope = scope.$new();
  25624. ctrl.template = response;
  25625. // Note: This will also link all children of ng-include that were contained in the original
  25626. // html. If that content contains controllers, ... they could pollute/change the scope.
  25627. // However, using ng-include on an element with additional content does not make sense...
  25628. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  25629. // function is called before linking the content, which would apply child
  25630. // directives to non existing elements.
  25631. var clone = $transclude(newScope, function(clone) {
  25632. cleanupLastIncludeContent();
  25633. $animate.enter(clone, null, $element).done(afterAnimation);
  25634. });
  25635. currentScope = newScope;
  25636. currentElement = clone;
  25637. currentScope.$emit('$includeContentLoaded', src);
  25638. scope.$eval(onloadExp);
  25639. }, function() {
  25640. if (scope.$$destroyed) return;
  25641. if (thisChangeId === changeCounter) {
  25642. cleanupLastIncludeContent();
  25643. scope.$emit('$includeContentError', src);
  25644. }
  25645. });
  25646. scope.$emit('$includeContentRequested', src);
  25647. } else {
  25648. cleanupLastIncludeContent();
  25649. ctrl.template = null;
  25650. }
  25651. });
  25652. };
  25653. }
  25654. };
  25655. }];
  25656. // This directive is called during the $transclude call of the first `ngInclude` directive.
  25657. // It will replace and compile the content of the element with the loaded template.
  25658. // We need this directive so that the element content is already filled when
  25659. // the link function of another directive on the same element as ngInclude
  25660. // is called.
  25661. var ngIncludeFillContentDirective = ['$compile',
  25662. function($compile) {
  25663. return {
  25664. restrict: 'ECA',
  25665. priority: -400,
  25666. require: 'ngInclude',
  25667. link: function(scope, $element, $attr, ctrl) {
  25668. if (toString.call($element[0]).match(/SVG/)) {
  25669. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  25670. // support innerHTML, so detect this here and try to generate the contents
  25671. // specially.
  25672. $element.empty();
  25673. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  25674. function namespaceAdaptedClone(clone) {
  25675. $element.append(clone);
  25676. }, {futureParentElement: $element});
  25677. return;
  25678. }
  25679. $element.html(ctrl.template);
  25680. $compile($element.contents())(scope);
  25681. }
  25682. };
  25683. }];
  25684. /**
  25685. * @ngdoc directive
  25686. * @name ngInit
  25687. * @restrict AC
  25688. *
  25689. * @description
  25690. * The `ngInit` directive allows you to evaluate an expression in the
  25691. * current scope.
  25692. *
  25693. * <div class="alert alert-danger">
  25694. * This directive can be abused to add unnecessary amounts of logic into your templates.
  25695. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  25696. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  25697. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  25698. * rather than `ngInit` to initialize values on a scope.
  25699. * </div>
  25700. *
  25701. * <div class="alert alert-warning">
  25702. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  25703. * sure you have parentheses to ensure correct operator precedence:
  25704. * <pre class="prettyprint">
  25705. * `<div ng-init="test1 = ($index | toString)"></div>`
  25706. * </pre>
  25707. * </div>
  25708. *
  25709. * @priority 450
  25710. *
  25711. * @element ANY
  25712. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  25713. *
  25714. * @example
  25715. <example module="initExample" name="ng-init">
  25716. <file name="index.html">
  25717. <script>
  25718. angular.module('initExample', [])
  25719. .controller('ExampleController', ['$scope', function($scope) {
  25720. $scope.list = [['a', 'b'], ['c', 'd']];
  25721. }]);
  25722. </script>
  25723. <div ng-controller="ExampleController">
  25724. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  25725. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  25726. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  25727. </div>
  25728. </div>
  25729. </div>
  25730. </file>
  25731. <file name="protractor.js" type="protractor">
  25732. it('should alias index positions', function() {
  25733. var elements = element.all(by.css('.example-init'));
  25734. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  25735. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  25736. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  25737. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  25738. });
  25739. </file>
  25740. </example>
  25741. */
  25742. var ngInitDirective = ngDirective({
  25743. priority: 450,
  25744. compile: function() {
  25745. return {
  25746. pre: function(scope, element, attrs) {
  25747. scope.$eval(attrs.ngInit);
  25748. }
  25749. };
  25750. }
  25751. });
  25752. /**
  25753. * @ngdoc directive
  25754. * @name ngList
  25755. *
  25756. * @description
  25757. * Text input that converts between a delimited string and an array of strings. The default
  25758. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  25759. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  25760. *
  25761. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  25762. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  25763. * list item is respected. This implies that the user of the directive is responsible for
  25764. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  25765. * tab or newline character.
  25766. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  25767. * when joining the list items back together) and whitespace around each list item is stripped
  25768. * before it is added to the model.
  25769. *
  25770. * ### Example with Validation
  25771. *
  25772. * <example name="ngList-directive" module="listExample">
  25773. * <file name="app.js">
  25774. * angular.module('listExample', [])
  25775. * .controller('ExampleController', ['$scope', function($scope) {
  25776. * $scope.names = ['morpheus', 'neo', 'trinity'];
  25777. * }]);
  25778. * </file>
  25779. * <file name="index.html">
  25780. * <form name="myForm" ng-controller="ExampleController">
  25781. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  25782. * <span role="alert">
  25783. * <span class="error" ng-show="myForm.namesInput.$error.required">
  25784. * Required!</span>
  25785. * </span>
  25786. * <br>
  25787. * <tt>names = {{names}}</tt><br/>
  25788. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  25789. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  25790. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  25791. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  25792. * </form>
  25793. * </file>
  25794. * <file name="protractor.js" type="protractor">
  25795. * var listInput = element(by.model('names'));
  25796. * var names = element(by.exactBinding('names'));
  25797. * var valid = element(by.binding('myForm.namesInput.$valid'));
  25798. * var error = element(by.css('span.error'));
  25799. *
  25800. * it('should initialize to model', function() {
  25801. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  25802. * expect(valid.getText()).toContain('true');
  25803. * expect(error.getCssValue('display')).toBe('none');
  25804. * });
  25805. *
  25806. * it('should be invalid if empty', function() {
  25807. * listInput.clear();
  25808. * listInput.sendKeys('');
  25809. *
  25810. * expect(names.getText()).toContain('');
  25811. * expect(valid.getText()).toContain('false');
  25812. * expect(error.getCssValue('display')).not.toBe('none');
  25813. * });
  25814. * </file>
  25815. * </example>
  25816. *
  25817. * ### Example - splitting on newline
  25818. * <example name="ngList-directive-newlines">
  25819. * <file name="index.html">
  25820. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  25821. * <pre>{{ list | json }}</pre>
  25822. * </file>
  25823. * <file name="protractor.js" type="protractor">
  25824. * it("should split the text by newlines", function() {
  25825. * var listInput = element(by.model('list'));
  25826. * var output = element(by.binding('list | json'));
  25827. * listInput.sendKeys('abc\ndef\nghi');
  25828. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  25829. * });
  25830. * </file>
  25831. * </example>
  25832. *
  25833. * @element input
  25834. * @param {string=} ngList optional delimiter that should be used to split the value.
  25835. */
  25836. var ngListDirective = function() {
  25837. return {
  25838. restrict: 'A',
  25839. priority: 100,
  25840. require: 'ngModel',
  25841. link: function(scope, element, attr, ctrl) {
  25842. var ngList = attr.ngList || ', ';
  25843. var trimValues = attr.ngTrim !== 'false';
  25844. var separator = trimValues ? trim(ngList) : ngList;
  25845. var parse = function(viewValue) {
  25846. // If the viewValue is invalid (say required but empty) it will be `undefined`
  25847. if (isUndefined(viewValue)) return;
  25848. var list = [];
  25849. if (viewValue) {
  25850. forEach(viewValue.split(separator), function(value) {
  25851. if (value) list.push(trimValues ? trim(value) : value);
  25852. });
  25853. }
  25854. return list;
  25855. };
  25856. ctrl.$parsers.push(parse);
  25857. ctrl.$formatters.push(function(value) {
  25858. if (isArray(value)) {
  25859. return value.join(ngList);
  25860. }
  25861. return undefined;
  25862. });
  25863. // Override the standard $isEmpty because an empty array means the input is empty.
  25864. ctrl.$isEmpty = function(value) {
  25865. return !value || !value.length;
  25866. };
  25867. }
  25868. };
  25869. };
  25870. /* global VALID_CLASS: true,
  25871. INVALID_CLASS: true,
  25872. PRISTINE_CLASS: true,
  25873. DIRTY_CLASS: true,
  25874. UNTOUCHED_CLASS: true,
  25875. TOUCHED_CLASS: true,
  25876. PENDING_CLASS: true,
  25877. addSetValidityMethod: true,
  25878. setupValidity: true,
  25879. defaultModelOptions: false
  25880. */
  25881. var VALID_CLASS = 'ng-valid',
  25882. INVALID_CLASS = 'ng-invalid',
  25883. PRISTINE_CLASS = 'ng-pristine',
  25884. DIRTY_CLASS = 'ng-dirty',
  25885. UNTOUCHED_CLASS = 'ng-untouched',
  25886. TOUCHED_CLASS = 'ng-touched',
  25887. EMPTY_CLASS = 'ng-empty',
  25888. NOT_EMPTY_CLASS = 'ng-not-empty';
  25889. var ngModelMinErr = minErr('ngModel');
  25890. /**
  25891. * @ngdoc type
  25892. * @name ngModel.NgModelController
  25893. *
  25894. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  25895. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  25896. * is set.
  25897. *
  25898. * @property {*} $modelValue The value in the model that the control is bound to.
  25899. *
  25900. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  25901. * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue
  25902. `$viewValue`} from the DOM, usually via user input.
  25903. See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation.
  25904. Note that the `$parsers` are not called when the bound ngModel expression changes programmatically.
  25905. The functions are called in array order, each passing
  25906. its return value through to the next. The last return value is forwarded to the
  25907. {@link ngModel.NgModelController#$validators `$validators`} collection.
  25908. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  25909. `$viewValue`}.
  25910. Returning `undefined` from a parser means a parse error occurred. In that case,
  25911. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  25912. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  25913. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  25914. This simple example shows a parser that would convert text input value to lowercase:
  25915. * ```js
  25916. * function parse(value) {
  25917. * if (value) {
  25918. * return value.toLowerCase();
  25919. * }
  25920. * }
  25921. * ngModelController.$parsers.push(parse);
  25922. * ```
  25923. *
  25924. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  25925. the bound ngModel expression changes programmatically. The `$formatters` are not called when the
  25926. value of the control is changed by user interaction.
  25927. Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue
  25928. `$modelValue`} for display in the control.
  25929. The functions are called in reverse array order, each passing the value through to the
  25930. next. The last return value is used as the actual DOM value.
  25931. This simple example shows a formatter that would convert the model value to uppercase:
  25932. * ```js
  25933. * function format(value) {
  25934. * if (value) {
  25935. * return value.toUpperCase();
  25936. * }
  25937. * }
  25938. * ngModel.$formatters.push(format);
  25939. * ```
  25940. *
  25941. * @property {Object.<string, function>} $validators A collection of validators that are applied
  25942. * whenever the model value changes. The key value within the object refers to the name of the
  25943. * validator while the function refers to the validation operation. The validation operation is
  25944. * provided with the model value as an argument and must return a true or false value depending
  25945. * on the response of that validation.
  25946. *
  25947. * ```js
  25948. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  25949. * var value = modelValue || viewValue;
  25950. * return /[0-9]+/.test(value) &&
  25951. * /[a-z]+/.test(value) &&
  25952. * /[A-Z]+/.test(value) &&
  25953. * /\W+/.test(value);
  25954. * };
  25955. * ```
  25956. *
  25957. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  25958. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  25959. * is expected to return a promise when it is run during the model validation process. Once the promise
  25960. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  25961. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  25962. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  25963. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  25964. * will only run once all synchronous validators have passed.
  25965. *
  25966. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  25967. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  25968. *
  25969. * ```js
  25970. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  25971. * var value = modelValue || viewValue;
  25972. *
  25973. * // Lookup user by username
  25974. * return $http.get('/api/users/' + value).
  25975. * then(function resolved() {
  25976. * //username exists, this means validation fails
  25977. * return $q.reject('exists');
  25978. * }, function rejected() {
  25979. * //username does not exist, therefore this validation passes
  25980. * return true;
  25981. * });
  25982. * };
  25983. * ```
  25984. *
  25985. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  25986. * view value has changed. It is called with no arguments, and its return value is ignored.
  25987. * This can be used in place of additional $watches against the model value.
  25988. *
  25989. * @property {Object} $error An object hash with all failing validator ids as keys.
  25990. * @property {Object} $pending An object hash with all pending validator ids as keys.
  25991. *
  25992. * @property {boolean} $untouched True if control has not lost focus yet.
  25993. * @property {boolean} $touched True if control has lost focus.
  25994. * @property {boolean} $pristine True if user has not interacted with the control yet.
  25995. * @property {boolean} $dirty True if user has already interacted with the control.
  25996. * @property {boolean} $valid True if there is no error.
  25997. * @property {boolean} $invalid True if at least one error on the control.
  25998. * @property {string} $name The name attribute of the control.
  25999. *
  26000. * @description
  26001. *
  26002. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  26003. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  26004. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  26005. * listening to DOM events.
  26006. * Such DOM related logic should be provided by other directives which make use of
  26007. * `NgModelController` for data-binding to control elements.
  26008. * Angular provides this DOM logic for most {@link input `input`} elements.
  26009. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  26010. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  26011. *
  26012. * @example
  26013. * ### Custom Control Example
  26014. * This example shows how to use `NgModelController` with a custom control to achieve
  26015. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  26016. * collaborate together to achieve the desired result.
  26017. *
  26018. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  26019. * contents be edited in place by the user.
  26020. *
  26021. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  26022. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  26023. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  26024. * that content using the `$sce` service.
  26025. *
  26026. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  26027. <file name="style.css">
  26028. [contenteditable] {
  26029. border: 1px solid black;
  26030. background-color: white;
  26031. min-height: 20px;
  26032. }
  26033. .ng-invalid {
  26034. border: 1px solid red;
  26035. }
  26036. </file>
  26037. <file name="script.js">
  26038. angular.module('customControl', ['ngSanitize']).
  26039. directive('contenteditable', ['$sce', function($sce) {
  26040. return {
  26041. restrict: 'A', // only activate on element attribute
  26042. require: '?ngModel', // get a hold of NgModelController
  26043. link: function(scope, element, attrs, ngModel) {
  26044. if (!ngModel) return; // do nothing if no ng-model
  26045. // Specify how UI should be updated
  26046. ngModel.$render = function() {
  26047. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  26048. };
  26049. // Listen for change events to enable binding
  26050. element.on('blur keyup change', function() {
  26051. scope.$evalAsync(read);
  26052. });
  26053. read(); // initialize
  26054. // Write data to the model
  26055. function read() {
  26056. var html = element.html();
  26057. // When we clear the content editable the browser leaves a <br> behind
  26058. // If strip-br attribute is provided then we strip this out
  26059. if (attrs.stripBr && html === '<br>') {
  26060. html = '';
  26061. }
  26062. ngModel.$setViewValue(html);
  26063. }
  26064. }
  26065. };
  26066. }]);
  26067. </file>
  26068. <file name="index.html">
  26069. <form name="myForm">
  26070. <div contenteditable
  26071. name="myWidget" ng-model="userContent"
  26072. strip-br="true"
  26073. required>Change me!</div>
  26074. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  26075. <hr>
  26076. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  26077. </form>
  26078. </file>
  26079. <file name="protractor.js" type="protractor">
  26080. it('should data-bind and become invalid', function() {
  26081. if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
  26082. // SafariDriver can't handle contenteditable
  26083. // and Firefox driver can't clear contenteditables very well
  26084. return;
  26085. }
  26086. var contentEditable = element(by.css('[contenteditable]'));
  26087. var content = 'Change me!';
  26088. expect(contentEditable.getText()).toEqual(content);
  26089. contentEditable.clear();
  26090. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  26091. expect(contentEditable.getText()).toEqual('');
  26092. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  26093. });
  26094. </file>
  26095. * </example>
  26096. *
  26097. *
  26098. */
  26099. NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];
  26100. function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {
  26101. this.$viewValue = Number.NaN;
  26102. this.$modelValue = Number.NaN;
  26103. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  26104. this.$validators = {};
  26105. this.$asyncValidators = {};
  26106. this.$parsers = [];
  26107. this.$formatters = [];
  26108. this.$viewChangeListeners = [];
  26109. this.$untouched = true;
  26110. this.$touched = false;
  26111. this.$pristine = true;
  26112. this.$dirty = false;
  26113. this.$valid = true;
  26114. this.$invalid = false;
  26115. this.$error = {}; // keep invalid keys here
  26116. this.$$success = {}; // keep valid keys here
  26117. this.$pending = undefined; // keep pending keys here
  26118. this.$name = $interpolate($attr.name || '', false)($scope);
  26119. this.$$parentForm = nullFormCtrl;
  26120. this.$options = defaultModelOptions;
  26121. this.$$parsedNgModel = $parse($attr.ngModel);
  26122. this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;
  26123. this.$$ngModelGet = this.$$parsedNgModel;
  26124. this.$$ngModelSet = this.$$parsedNgModelAssign;
  26125. this.$$pendingDebounce = null;
  26126. this.$$parserValid = undefined;
  26127. this.$$currentValidationRunId = 0;
  26128. // https://github.com/angular/angular.js/issues/15833
  26129. // Prevent `$$scope` from being iterated over by `copy` when NgModelController is deep watched
  26130. Object.defineProperty(this, '$$scope', {value: $scope});
  26131. this.$$attr = $attr;
  26132. this.$$element = $element;
  26133. this.$$animate = $animate;
  26134. this.$$timeout = $timeout;
  26135. this.$$parse = $parse;
  26136. this.$$q = $q;
  26137. this.$$exceptionHandler = $exceptionHandler;
  26138. setupValidity(this);
  26139. setupModelWatcher(this);
  26140. }
  26141. NgModelController.prototype = {
  26142. $$initGetterSetters: function() {
  26143. if (this.$options.getOption('getterSetter')) {
  26144. var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),
  26145. invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');
  26146. this.$$ngModelGet = function($scope) {
  26147. var modelValue = this.$$parsedNgModel($scope);
  26148. if (isFunction(modelValue)) {
  26149. modelValue = invokeModelGetter($scope);
  26150. }
  26151. return modelValue;
  26152. };
  26153. this.$$ngModelSet = function($scope, newValue) {
  26154. if (isFunction(this.$$parsedNgModel($scope))) {
  26155. invokeModelSetter($scope, {$$$p: newValue});
  26156. } else {
  26157. this.$$parsedNgModelAssign($scope, newValue);
  26158. }
  26159. };
  26160. } else if (!this.$$parsedNgModel.assign) {
  26161. throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
  26162. this.$$attr.ngModel, startingTag(this.$$element));
  26163. }
  26164. },
  26165. /**
  26166. * @ngdoc method
  26167. * @name ngModel.NgModelController#$render
  26168. *
  26169. * @description
  26170. * Called when the view needs to be updated. It is expected that the user of the ng-model
  26171. * directive will implement this method.
  26172. *
  26173. * The `$render()` method is invoked in the following situations:
  26174. *
  26175. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  26176. * committed value then `$render()` is called to update the input control.
  26177. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  26178. * the `$viewValue` are different from last time.
  26179. *
  26180. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  26181. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  26182. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  26183. * invoked if you only change a property on the objects.
  26184. */
  26185. $render: noop,
  26186. /**
  26187. * @ngdoc method
  26188. * @name ngModel.NgModelController#$isEmpty
  26189. *
  26190. * @description
  26191. * This is called when we need to determine if the value of an input is empty.
  26192. *
  26193. * For instance, the required directive does this to work out if the input has data or not.
  26194. *
  26195. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  26196. *
  26197. * You can override this for input directives whose concept of being empty is different from the
  26198. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  26199. * implies empty.
  26200. *
  26201. * @param {*} value The value of the input to check for emptiness.
  26202. * @returns {boolean} True if `value` is "empty".
  26203. */
  26204. $isEmpty: function(value) {
  26205. // eslint-disable-next-line no-self-compare
  26206. return isUndefined(value) || value === '' || value === null || value !== value;
  26207. },
  26208. $$updateEmptyClasses: function(value) {
  26209. if (this.$isEmpty(value)) {
  26210. this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);
  26211. this.$$animate.addClass(this.$$element, EMPTY_CLASS);
  26212. } else {
  26213. this.$$animate.removeClass(this.$$element, EMPTY_CLASS);
  26214. this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);
  26215. }
  26216. },
  26217. /**
  26218. * @ngdoc method
  26219. * @name ngModel.NgModelController#$setPristine
  26220. *
  26221. * @description
  26222. * Sets the control to its pristine state.
  26223. *
  26224. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  26225. * state (`ng-pristine` class). A model is considered to be pristine when the control
  26226. * has not been changed from when first compiled.
  26227. */
  26228. $setPristine: function() {
  26229. this.$dirty = false;
  26230. this.$pristine = true;
  26231. this.$$animate.removeClass(this.$$element, DIRTY_CLASS);
  26232. this.$$animate.addClass(this.$$element, PRISTINE_CLASS);
  26233. },
  26234. /**
  26235. * @ngdoc method
  26236. * @name ngModel.NgModelController#$setDirty
  26237. *
  26238. * @description
  26239. * Sets the control to its dirty state.
  26240. *
  26241. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  26242. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  26243. * from when first compiled.
  26244. */
  26245. $setDirty: function() {
  26246. this.$dirty = true;
  26247. this.$pristine = false;
  26248. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  26249. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  26250. this.$$parentForm.$setDirty();
  26251. },
  26252. /**
  26253. * @ngdoc method
  26254. * @name ngModel.NgModelController#$setUntouched
  26255. *
  26256. * @description
  26257. * Sets the control to its untouched state.
  26258. *
  26259. * This method can be called to remove the `ng-touched` class and set the control to its
  26260. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  26261. * by default, however this function can be used to restore that state if the model has
  26262. * already been touched by the user.
  26263. */
  26264. $setUntouched: function() {
  26265. this.$touched = false;
  26266. this.$untouched = true;
  26267. this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  26268. },
  26269. /**
  26270. * @ngdoc method
  26271. * @name ngModel.NgModelController#$setTouched
  26272. *
  26273. * @description
  26274. * Sets the control to its touched state.
  26275. *
  26276. * This method can be called to remove the `ng-untouched` class and set the control to its
  26277. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  26278. * first focused the control element and then shifted focus away from the control (blur event).
  26279. */
  26280. $setTouched: function() {
  26281. this.$touched = true;
  26282. this.$untouched = false;
  26283. this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  26284. },
  26285. /**
  26286. * @ngdoc method
  26287. * @name ngModel.NgModelController#$rollbackViewValue
  26288. *
  26289. * @description
  26290. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  26291. * which may be caused by a pending debounced event or because the input is waiting for some
  26292. * future event.
  26293. *
  26294. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  26295. * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of
  26296. * sync with the ngModel's `$modelValue`.
  26297. *
  26298. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  26299. * and reset the input to the last committed view value.
  26300. *
  26301. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  26302. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  26303. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  26304. *
  26305. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  26306. * input which may have such events pending. This is important in order to make sure that the
  26307. * input field will be updated with the new model value and any pending operations are cancelled.
  26308. *
  26309. * <example name="ng-model-cancel-update" module="cancel-update-example">
  26310. * <file name="app.js">
  26311. * angular.module('cancel-update-example', [])
  26312. *
  26313. * .controller('CancelUpdateController', ['$scope', function($scope) {
  26314. * $scope.model = {value1: '', value2: ''};
  26315. *
  26316. * $scope.setEmpty = function(e, value, rollback) {
  26317. * if (e.keyCode === 27) {
  26318. * e.preventDefault();
  26319. * if (rollback) {
  26320. * $scope.myForm[value].$rollbackViewValue();
  26321. * }
  26322. * $scope.model[value] = '';
  26323. * }
  26324. * };
  26325. * }]);
  26326. * </file>
  26327. * <file name="index.html">
  26328. * <div ng-controller="CancelUpdateController">
  26329. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  26330. * empty them. Follow these steps and observe the difference:</p>
  26331. * <ol>
  26332. * <li>Type something in the input. You will see that the model is not yet updated</li>
  26333. * <li>Press the Escape key.
  26334. * <ol>
  26335. * <li> In the first example, nothing happens, because the model is already '', and no
  26336. * update is detected. If you blur the input, the model will be set to the current view.
  26337. * </li>
  26338. * <li> In the second example, the pending update is cancelled, and the input is set back
  26339. * to the last committed view value (''). Blurring the input does nothing.
  26340. * </li>
  26341. * </ol>
  26342. * </li>
  26343. * </ol>
  26344. *
  26345. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  26346. * <div>
  26347. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  26348. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  26349. * ng-keydown="setEmpty($event, 'value1')">
  26350. * value1: "{{ model.value1 }}"
  26351. * </div>
  26352. *
  26353. * <div>
  26354. * <p id="inputDescription2">With $rollbackViewValue():</p>
  26355. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  26356. * ng-keydown="setEmpty($event, 'value2', true)">
  26357. * value2: "{{ model.value2 }}"
  26358. * </div>
  26359. * </form>
  26360. * </div>
  26361. * </file>
  26362. <file name="style.css">
  26363. div {
  26364. display: table-cell;
  26365. }
  26366. div:nth-child(1) {
  26367. padding-right: 30px;
  26368. }
  26369. </file>
  26370. * </example>
  26371. */
  26372. $rollbackViewValue: function() {
  26373. this.$$timeout.cancel(this.$$pendingDebounce);
  26374. this.$viewValue = this.$$lastCommittedViewValue;
  26375. this.$render();
  26376. },
  26377. /**
  26378. * @ngdoc method
  26379. * @name ngModel.NgModelController#$validate
  26380. *
  26381. * @description
  26382. * Runs each of the registered validators (first synchronous validators and then
  26383. * asynchronous validators).
  26384. * If the validity changes to invalid, the model will be set to `undefined`,
  26385. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  26386. * If the validity changes to valid, it will set the model to the last available valid
  26387. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  26388. */
  26389. $validate: function() {
  26390. // ignore $validate before model is initialized
  26391. if (isNumberNaN(this.$modelValue)) {
  26392. return;
  26393. }
  26394. var viewValue = this.$$lastCommittedViewValue;
  26395. // Note: we use the $$rawModelValue as $modelValue might have been
  26396. // set to undefined during a view -> model update that found validation
  26397. // errors. We can't parse the view here, since that could change
  26398. // the model although neither viewValue nor the model on the scope changed
  26399. var modelValue = this.$$rawModelValue;
  26400. var prevValid = this.$valid;
  26401. var prevModelValue = this.$modelValue;
  26402. var allowInvalid = this.$options.getOption('allowInvalid');
  26403. var that = this;
  26404. this.$$runValidators(modelValue, viewValue, function(allValid) {
  26405. // If there was no change in validity, don't update the model
  26406. // This prevents changing an invalid modelValue to undefined
  26407. if (!allowInvalid && prevValid !== allValid) {
  26408. // Note: Don't check this.$valid here, as we could have
  26409. // external validators (e.g. calculated on the server),
  26410. // that just call $setValidity and need the model value
  26411. // to calculate their validity.
  26412. that.$modelValue = allValid ? modelValue : undefined;
  26413. if (that.$modelValue !== prevModelValue) {
  26414. that.$$writeModelToScope();
  26415. }
  26416. }
  26417. });
  26418. },
  26419. $$runValidators: function(modelValue, viewValue, doneCallback) {
  26420. this.$$currentValidationRunId++;
  26421. var localValidationRunId = this.$$currentValidationRunId;
  26422. var that = this;
  26423. // check parser error
  26424. if (!processParseErrors()) {
  26425. validationDone(false);
  26426. return;
  26427. }
  26428. if (!processSyncValidators()) {
  26429. validationDone(false);
  26430. return;
  26431. }
  26432. processAsyncValidators();
  26433. function processParseErrors() {
  26434. var errorKey = that.$$parserName || 'parse';
  26435. if (isUndefined(that.$$parserValid)) {
  26436. setValidity(errorKey, null);
  26437. } else {
  26438. if (!that.$$parserValid) {
  26439. forEach(that.$validators, function(v, name) {
  26440. setValidity(name, null);
  26441. });
  26442. forEach(that.$asyncValidators, function(v, name) {
  26443. setValidity(name, null);
  26444. });
  26445. }
  26446. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  26447. setValidity(errorKey, that.$$parserValid);
  26448. return that.$$parserValid;
  26449. }
  26450. return true;
  26451. }
  26452. function processSyncValidators() {
  26453. var syncValidatorsValid = true;
  26454. forEach(that.$validators, function(validator, name) {
  26455. var result = Boolean(validator(modelValue, viewValue));
  26456. syncValidatorsValid = syncValidatorsValid && result;
  26457. setValidity(name, result);
  26458. });
  26459. if (!syncValidatorsValid) {
  26460. forEach(that.$asyncValidators, function(v, name) {
  26461. setValidity(name, null);
  26462. });
  26463. return false;
  26464. }
  26465. return true;
  26466. }
  26467. function processAsyncValidators() {
  26468. var validatorPromises = [];
  26469. var allValid = true;
  26470. forEach(that.$asyncValidators, function(validator, name) {
  26471. var promise = validator(modelValue, viewValue);
  26472. if (!isPromiseLike(promise)) {
  26473. throw ngModelMinErr('nopromise',
  26474. 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
  26475. }
  26476. setValidity(name, undefined);
  26477. validatorPromises.push(promise.then(function() {
  26478. setValidity(name, true);
  26479. }, function() {
  26480. allValid = false;
  26481. setValidity(name, false);
  26482. }));
  26483. });
  26484. if (!validatorPromises.length) {
  26485. validationDone(true);
  26486. } else {
  26487. that.$$q.all(validatorPromises).then(function() {
  26488. validationDone(allValid);
  26489. }, noop);
  26490. }
  26491. }
  26492. function setValidity(name, isValid) {
  26493. if (localValidationRunId === that.$$currentValidationRunId) {
  26494. that.$setValidity(name, isValid);
  26495. }
  26496. }
  26497. function validationDone(allValid) {
  26498. if (localValidationRunId === that.$$currentValidationRunId) {
  26499. doneCallback(allValid);
  26500. }
  26501. }
  26502. },
  26503. /**
  26504. * @ngdoc method
  26505. * @name ngModel.NgModelController#$commitViewValue
  26506. *
  26507. * @description
  26508. * Commit a pending update to the `$modelValue`.
  26509. *
  26510. * Updates may be pending by a debounced event or because the input is waiting for a some future
  26511. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  26512. * usually handles calling this in response to input events.
  26513. */
  26514. $commitViewValue: function() {
  26515. var viewValue = this.$viewValue;
  26516. this.$$timeout.cancel(this.$$pendingDebounce);
  26517. // If the view value has not changed then we should just exit, except in the case where there is
  26518. // a native validator on the element. In this case the validation state may have changed even though
  26519. // the viewValue has stayed empty.
  26520. if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {
  26521. return;
  26522. }
  26523. this.$$updateEmptyClasses(viewValue);
  26524. this.$$lastCommittedViewValue = viewValue;
  26525. // change to dirty
  26526. if (this.$pristine) {
  26527. this.$setDirty();
  26528. }
  26529. this.$$parseAndValidate();
  26530. },
  26531. $$parseAndValidate: function() {
  26532. var viewValue = this.$$lastCommittedViewValue;
  26533. var modelValue = viewValue;
  26534. var that = this;
  26535. this.$$parserValid = isUndefined(modelValue) ? undefined : true;
  26536. if (this.$$parserValid) {
  26537. for (var i = 0; i < this.$parsers.length; i++) {
  26538. modelValue = this.$parsers[i](modelValue);
  26539. if (isUndefined(modelValue)) {
  26540. this.$$parserValid = false;
  26541. break;
  26542. }
  26543. }
  26544. }
  26545. if (isNumberNaN(this.$modelValue)) {
  26546. // this.$modelValue has not been touched yet...
  26547. this.$modelValue = this.$$ngModelGet(this.$$scope);
  26548. }
  26549. var prevModelValue = this.$modelValue;
  26550. var allowInvalid = this.$options.getOption('allowInvalid');
  26551. this.$$rawModelValue = modelValue;
  26552. if (allowInvalid) {
  26553. this.$modelValue = modelValue;
  26554. writeToModelIfNeeded();
  26555. }
  26556. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  26557. // This can happen if e.g. $setViewValue is called from inside a parser
  26558. this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {
  26559. if (!allowInvalid) {
  26560. // Note: Don't check this.$valid here, as we could have
  26561. // external validators (e.g. calculated on the server),
  26562. // that just call $setValidity and need the model value
  26563. // to calculate their validity.
  26564. that.$modelValue = allValid ? modelValue : undefined;
  26565. writeToModelIfNeeded();
  26566. }
  26567. });
  26568. function writeToModelIfNeeded() {
  26569. if (that.$modelValue !== prevModelValue) {
  26570. that.$$writeModelToScope();
  26571. }
  26572. }
  26573. },
  26574. $$writeModelToScope: function() {
  26575. this.$$ngModelSet(this.$$scope, this.$modelValue);
  26576. forEach(this.$viewChangeListeners, function(listener) {
  26577. try {
  26578. listener();
  26579. } catch (e) {
  26580. // eslint-disable-next-line no-invalid-this
  26581. this.$$exceptionHandler(e);
  26582. }
  26583. }, this);
  26584. },
  26585. /**
  26586. * @ngdoc method
  26587. * @name ngModel.NgModelController#$setViewValue
  26588. *
  26589. * @description
  26590. * Update the view value.
  26591. *
  26592. * This method should be called when a control wants to change the view value; typically,
  26593. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  26594. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  26595. * calls it when an option is selected.
  26596. *
  26597. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  26598. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  26599. * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and
  26600. * `$asyncValidators` are called and the value is applied to `$modelValue`.
  26601. * Finally, the value is set to the **expression** specified in the `ng-model` attribute and
  26602. * all the registered change listeners, in the `$viewChangeListeners` list are called.
  26603. *
  26604. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  26605. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  26606. * `updateOn` events is triggered on the DOM element.
  26607. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  26608. * directive is used with a custom debounce for this particular event.
  26609. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  26610. * is specified, once the timer runs out.
  26611. *
  26612. * When used with standard inputs, the view value will always be a string (which is in some cases
  26613. * parsed into another type, such as a `Date` object for `input[date]`.)
  26614. * However, custom controls might also pass objects to this method. In this case, we should make
  26615. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  26616. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  26617. * the property of the object then ngModel will not realize that the object has changed and
  26618. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  26619. * not change properties of the copy once it has been passed to `$setViewValue`.
  26620. * Otherwise you may cause the model value on the scope to change incorrectly.
  26621. *
  26622. * <div class="alert alert-info">
  26623. * In any case, the value passed to the method should always reflect the current value
  26624. * of the control. For example, if you are calling `$setViewValue` for an input element,
  26625. * you should pass the input DOM value. Otherwise, the control and the scope model become
  26626. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  26627. * the control's DOM value in any way. If we want to change the control's DOM value
  26628. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  26629. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  26630. * to update the DOM, and finally call `$validate` on it.
  26631. * </div>
  26632. *
  26633. * @param {*} value value from the view.
  26634. * @param {string} trigger Event that triggered the update.
  26635. */
  26636. $setViewValue: function(value, trigger) {
  26637. this.$viewValue = value;
  26638. if (this.$options.getOption('updateOnDefault')) {
  26639. this.$$debounceViewValueCommit(trigger);
  26640. }
  26641. },
  26642. $$debounceViewValueCommit: function(trigger) {
  26643. var debounceDelay = this.$options.getOption('debounce');
  26644. if (isNumber(debounceDelay[trigger])) {
  26645. debounceDelay = debounceDelay[trigger];
  26646. } else if (isNumber(debounceDelay['default'])) {
  26647. debounceDelay = debounceDelay['default'];
  26648. }
  26649. this.$$timeout.cancel(this.$$pendingDebounce);
  26650. var that = this;
  26651. if (debounceDelay > 0) { // this fails if debounceDelay is an object
  26652. this.$$pendingDebounce = this.$$timeout(function() {
  26653. that.$commitViewValue();
  26654. }, debounceDelay);
  26655. } else if (this.$$scope.$root.$$phase) {
  26656. this.$commitViewValue();
  26657. } else {
  26658. this.$$scope.$apply(function() {
  26659. that.$commitViewValue();
  26660. });
  26661. }
  26662. },
  26663. /**
  26664. * @ngdoc method
  26665. *
  26666. * @name ngModel.NgModelController#$overrideModelOptions
  26667. *
  26668. * @description
  26669. *
  26670. * Override the current model options settings programmatically.
  26671. *
  26672. * The previous `ModelOptions` value will not be modified. Instead, a
  26673. * new `ModelOptions` object will inherit from the previous one overriding
  26674. * or inheriting settings that are defined in the given parameter.
  26675. *
  26676. * See {@link ngModelOptions} for information about what options can be specified
  26677. * and how model option inheritance works.
  26678. *
  26679. * @param {Object} options a hash of settings to override the previous options
  26680. *
  26681. */
  26682. $overrideModelOptions: function(options) {
  26683. this.$options = this.$options.createChild(options);
  26684. }
  26685. };
  26686. function setupModelWatcher(ctrl) {
  26687. // model -> value
  26688. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  26689. // 1. scope value is 'a'
  26690. // 2. user enters 'b'
  26691. // 3. ng-change kicks in and reverts scope value to 'a'
  26692. // -> scope value did not change since the last digest as
  26693. // ng-change executes in apply phase
  26694. // 4. view should be changed back to 'a'
  26695. ctrl.$$scope.$watch(function ngModelWatch(scope) {
  26696. var modelValue = ctrl.$$ngModelGet(scope);
  26697. // if scope model value and ngModel value are out of sync
  26698. // TODO(perf): why not move this to the action fn?
  26699. if (modelValue !== ctrl.$modelValue &&
  26700. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  26701. // eslint-disable-next-line no-self-compare
  26702. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  26703. ) {
  26704. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  26705. ctrl.$$parserValid = undefined;
  26706. var formatters = ctrl.$formatters,
  26707. idx = formatters.length;
  26708. var viewValue = modelValue;
  26709. while (idx--) {
  26710. viewValue = formatters[idx](viewValue);
  26711. }
  26712. if (ctrl.$viewValue !== viewValue) {
  26713. ctrl.$$updateEmptyClasses(viewValue);
  26714. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  26715. ctrl.$render();
  26716. // It is possible that model and view value have been updated during render
  26717. ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop);
  26718. }
  26719. }
  26720. return modelValue;
  26721. });
  26722. }
  26723. /**
  26724. * @ngdoc method
  26725. * @name ngModel.NgModelController#$setValidity
  26726. *
  26727. * @description
  26728. * Change the validity state, and notify the form.
  26729. *
  26730. * This method can be called within $parsers/$formatters or a custom validation implementation.
  26731. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  26732. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  26733. *
  26734. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  26735. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  26736. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  26737. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  26738. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  26739. * classes and can be bound to as `{{ someForm.someControl.$error.myError }}`.
  26740. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  26741. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  26742. * Skipped is used by Angular when validators do not run because of parse errors and
  26743. * when `$asyncValidators` do not run because any of the `$validators` failed.
  26744. */
  26745. addSetValidityMethod({
  26746. clazz: NgModelController,
  26747. set: function(object, property) {
  26748. object[property] = true;
  26749. },
  26750. unset: function(object, property) {
  26751. delete object[property];
  26752. }
  26753. });
  26754. /**
  26755. * @ngdoc directive
  26756. * @name ngModel
  26757. *
  26758. * @element input
  26759. * @priority 1
  26760. *
  26761. * @description
  26762. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  26763. * property on the scope using {@link ngModel.NgModelController NgModelController},
  26764. * which is created and exposed by this directive.
  26765. *
  26766. * `ngModel` is responsible for:
  26767. *
  26768. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  26769. * require.
  26770. * - Providing validation behavior (i.e. required, number, email, url).
  26771. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  26772. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  26773. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  26774. * - Registering the control with its parent {@link ng.directive:form form}.
  26775. *
  26776. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  26777. * current scope. If the property doesn't already exist on this scope, it will be created
  26778. * implicitly and added to the scope.
  26779. *
  26780. * For best practices on using `ngModel`, see:
  26781. *
  26782. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  26783. *
  26784. * For basic examples, how to use `ngModel`, see:
  26785. *
  26786. * - {@link ng.directive:input input}
  26787. * - {@link input[text] text}
  26788. * - {@link input[checkbox] checkbox}
  26789. * - {@link input[radio] radio}
  26790. * - {@link input[number] number}
  26791. * - {@link input[email] email}
  26792. * - {@link input[url] url}
  26793. * - {@link input[date] date}
  26794. * - {@link input[datetime-local] datetime-local}
  26795. * - {@link input[time] time}
  26796. * - {@link input[month] month}
  26797. * - {@link input[week] week}
  26798. * - {@link ng.directive:select select}
  26799. * - {@link ng.directive:textarea textarea}
  26800. *
  26801. * # Complex Models (objects or collections)
  26802. *
  26803. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  26804. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  26805. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  26806. *
  26807. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  26808. *
  26809. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  26810. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  26811. * if the select is given the `multiple` attribute.
  26812. *
  26813. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  26814. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  26815. * not trigger a re-rendering of the model.
  26816. *
  26817. * # CSS classes
  26818. * The following CSS classes are added and removed on the associated input/select/textarea element
  26819. * depending on the validity of the model.
  26820. *
  26821. * - `ng-valid`: the model is valid
  26822. * - `ng-invalid`: the model is invalid
  26823. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  26824. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  26825. * - `ng-pristine`: the control hasn't been interacted with yet
  26826. * - `ng-dirty`: the control has been interacted with
  26827. * - `ng-touched`: the control has been blurred
  26828. * - `ng-untouched`: the control hasn't been blurred
  26829. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  26830. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  26831. * by the {@link ngModel.NgModelController#$isEmpty} method
  26832. * - `ng-not-empty`: the view contains a non-empty value
  26833. *
  26834. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  26835. *
  26836. * ## Animation Hooks
  26837. *
  26838. * Animations within models are triggered when any of the associated CSS classes are added and removed
  26839. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  26840. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  26841. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  26842. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  26843. *
  26844. * The following example shows a simple way to utilize CSS transitions to style an input element
  26845. * that has been rendered as invalid after it has been validated:
  26846. *
  26847. * <pre>
  26848. * //be sure to include ngAnimate as a module to hook into more
  26849. * //advanced animations
  26850. * .my-input {
  26851. * transition:0.5s linear all;
  26852. * background: white;
  26853. * }
  26854. * .my-input.ng-invalid {
  26855. * background: red;
  26856. * color:white;
  26857. * }
  26858. * </pre>
  26859. *
  26860. * @example
  26861. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
  26862. <file name="index.html">
  26863. <script>
  26864. angular.module('inputExample', [])
  26865. .controller('ExampleController', ['$scope', function($scope) {
  26866. $scope.val = '1';
  26867. }]);
  26868. </script>
  26869. <style>
  26870. .my-input {
  26871. transition:all linear 0.5s;
  26872. background: transparent;
  26873. }
  26874. .my-input.ng-invalid {
  26875. color:white;
  26876. background: red;
  26877. }
  26878. </style>
  26879. <p id="inputDescription">
  26880. Update input to see transitions when valid/invalid.
  26881. Integer is a valid value.
  26882. </p>
  26883. <form name="testForm" ng-controller="ExampleController">
  26884. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  26885. aria-describedby="inputDescription" />
  26886. </form>
  26887. </file>
  26888. * </example>
  26889. *
  26890. * ## Binding to a getter/setter
  26891. *
  26892. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  26893. * function that returns a representation of the model when called with zero arguments, and sets
  26894. * the internal state of a model when called with an argument. It's sometimes useful to use this
  26895. * for models that have an internal representation that's different from what the model exposes
  26896. * to the view.
  26897. *
  26898. * <div class="alert alert-success">
  26899. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  26900. * frequently than other parts of your code.
  26901. * </div>
  26902. *
  26903. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  26904. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  26905. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  26906. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  26907. *
  26908. * The following example shows how to use `ngModel` with a getter/setter:
  26909. *
  26910. * @example
  26911. * <example name="ngModel-getter-setter" module="getterSetterExample">
  26912. <file name="index.html">
  26913. <div ng-controller="ExampleController">
  26914. <form name="userForm">
  26915. <label>Name:
  26916. <input type="text" name="userName"
  26917. ng-model="user.name"
  26918. ng-model-options="{ getterSetter: true }" />
  26919. </label>
  26920. </form>
  26921. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  26922. </div>
  26923. </file>
  26924. <file name="app.js">
  26925. angular.module('getterSetterExample', [])
  26926. .controller('ExampleController', ['$scope', function($scope) {
  26927. var _name = 'Brian';
  26928. $scope.user = {
  26929. name: function(newName) {
  26930. // Note that newName can be undefined for two reasons:
  26931. // 1. Because it is called as a getter and thus called with no arguments
  26932. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  26933. // input is invalid
  26934. return arguments.length ? (_name = newName) : _name;
  26935. }
  26936. };
  26937. }]);
  26938. </file>
  26939. * </example>
  26940. */
  26941. var ngModelDirective = ['$rootScope', function($rootScope) {
  26942. return {
  26943. restrict: 'A',
  26944. require: ['ngModel', '^?form', '^?ngModelOptions'],
  26945. controller: NgModelController,
  26946. // Prelink needs to run before any input directive
  26947. // so that we can set the NgModelOptions in NgModelController
  26948. // before anyone else uses it.
  26949. priority: 1,
  26950. compile: function ngModelCompile(element) {
  26951. // Setup initial state of the control
  26952. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  26953. return {
  26954. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  26955. var modelCtrl = ctrls[0],
  26956. formCtrl = ctrls[1] || modelCtrl.$$parentForm,
  26957. optionsCtrl = ctrls[2];
  26958. if (optionsCtrl) {
  26959. modelCtrl.$options = optionsCtrl.$options;
  26960. }
  26961. modelCtrl.$$initGetterSetters();
  26962. // notify others, especially parent forms
  26963. formCtrl.$addControl(modelCtrl);
  26964. attr.$observe('name', function(newValue) {
  26965. if (modelCtrl.$name !== newValue) {
  26966. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  26967. }
  26968. });
  26969. scope.$on('$destroy', function() {
  26970. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  26971. });
  26972. },
  26973. post: function ngModelPostLink(scope, element, attr, ctrls) {
  26974. var modelCtrl = ctrls[0];
  26975. if (modelCtrl.$options.getOption('updateOn')) {
  26976. element.on(modelCtrl.$options.getOption('updateOn'), function(ev) {
  26977. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  26978. });
  26979. }
  26980. function setTouched() {
  26981. modelCtrl.$setTouched();
  26982. }
  26983. element.on('blur', function() {
  26984. if (modelCtrl.$touched) return;
  26985. if ($rootScope.$$phase) {
  26986. scope.$evalAsync(setTouched);
  26987. } else {
  26988. scope.$apply(setTouched);
  26989. }
  26990. });
  26991. }
  26992. };
  26993. }
  26994. };
  26995. }];
  26996. /* exported defaultModelOptions */
  26997. var defaultModelOptions;
  26998. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  26999. /**
  27000. * @ngdoc type
  27001. * @name ModelOptions
  27002. * @description
  27003. * A container for the options set by the {@link ngModelOptions} directive
  27004. */
  27005. function ModelOptions(options) {
  27006. this.$$options = options;
  27007. }
  27008. ModelOptions.prototype = {
  27009. /**
  27010. * @ngdoc method
  27011. * @name ModelOptions#getOption
  27012. * @param {string} name the name of the option to retrieve
  27013. * @returns {*} the value of the option
  27014. * @description
  27015. * Returns the value of the given option
  27016. */
  27017. getOption: function(name) {
  27018. return this.$$options[name];
  27019. },
  27020. /**
  27021. * @ngdoc method
  27022. * @name ModelOptions#createChild
  27023. * @param {Object} options a hash of options for the new child that will override the parent's options
  27024. * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
  27025. */
  27026. createChild: function(options) {
  27027. var inheritAll = false;
  27028. // make a shallow copy
  27029. options = extend({}, options);
  27030. // Inherit options from the parent if specified by the value `"$inherit"`
  27031. forEach(options, /* @this */ function(option, key) {
  27032. if (option === '$inherit') {
  27033. if (key === '*') {
  27034. inheritAll = true;
  27035. } else {
  27036. options[key] = this.$$options[key];
  27037. // `updateOn` is special so we must also inherit the `updateOnDefault` option
  27038. if (key === 'updateOn') {
  27039. options.updateOnDefault = this.$$options.updateOnDefault;
  27040. }
  27041. }
  27042. } else {
  27043. if (key === 'updateOn') {
  27044. // If the `updateOn` property contains the `default` event then we have to remove
  27045. // it from the event list and set the `updateOnDefault` flag.
  27046. options.updateOnDefault = false;
  27047. options[key] = trim(option.replace(DEFAULT_REGEXP, function() {
  27048. options.updateOnDefault = true;
  27049. return ' ';
  27050. }));
  27051. }
  27052. }
  27053. }, this);
  27054. if (inheritAll) {
  27055. // We have a property of the form: `"*": "$inherit"`
  27056. delete options['*'];
  27057. defaults(options, this.$$options);
  27058. }
  27059. // Finally add in any missing defaults
  27060. defaults(options, defaultModelOptions.$$options);
  27061. return new ModelOptions(options);
  27062. }
  27063. };
  27064. defaultModelOptions = new ModelOptions({
  27065. updateOn: '',
  27066. updateOnDefault: true,
  27067. debounce: 0,
  27068. getterSetter: false,
  27069. allowInvalid: false,
  27070. timezone: null
  27071. });
  27072. /**
  27073. * @ngdoc directive
  27074. * @name ngModelOptions
  27075. *
  27076. * @description
  27077. * This directive allows you to modify the behaviour of {@link ngModel} directives within your
  27078. * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}
  27079. * directives will use the options of their nearest `ngModelOptions` ancestor.
  27080. *
  27081. * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as
  27082. * an Angular expression. This expression should evaluate to an object, whose properties contain
  27083. * the settings. For example: `<div "ng-model-options"="{ debounce: 100 }"`.
  27084. *
  27085. * ## Inheriting Options
  27086. *
  27087. * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions`
  27088. * directive by giving it the value of `"$inherit"`.
  27089. * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the
  27090. * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings
  27091. * will be used.
  27092. *
  27093. * For example given the following fragment of HTML
  27094. *
  27095. *
  27096. * ```html
  27097. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  27098. * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }">
  27099. * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" />
  27100. * </form>
  27101. * </div>
  27102. * ```
  27103. *
  27104. * the `input` element will have the following settings
  27105. *
  27106. * ```js
  27107. * { allowInvalid: true, updateOn: 'default', debounce: 0 }
  27108. * ```
  27109. *
  27110. * Notice that the `debounce` setting was not inherited and used the default value instead.
  27111. *
  27112. * You can specify that all undefined settings are automatically inherited from an ancestor by
  27113. * including a property with key of `"*"` and value of `"$inherit"`.
  27114. *
  27115. * For example given the following fragment of HTML
  27116. *
  27117. *
  27118. * ```html
  27119. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  27120. * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }">
  27121. * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" />
  27122. * </form>
  27123. * </div>
  27124. * ```
  27125. *
  27126. * the `input` element will have the following settings
  27127. *
  27128. * ```js
  27129. * { allowInvalid: true, updateOn: 'default', debounce: 200 }
  27130. * ```
  27131. *
  27132. * Notice that the `debounce` setting now inherits the value from the outer `<div>` element.
  27133. *
  27134. * If you are creating a reusable component then you should be careful when using `"*": "$inherit"`
  27135. * since you may inadvertently inherit a setting in the future that changes the behavior of your component.
  27136. *
  27137. *
  27138. * ## Triggering and debouncing model updates
  27139. *
  27140. * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
  27141. * trigger a model update and/or a debouncing delay so that the actual update only takes place when
  27142. * a timer expires; this timer will be reset after another change takes place.
  27143. *
  27144. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  27145. * be different from the value in the actual model. This means that if you update the model you
  27146. * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in
  27147. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  27148. *
  27149. * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}
  27150. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  27151. * important because `form` controllers are published to the related scope under the name in their
  27152. * `name` attribute.
  27153. *
  27154. * Any pending changes will take place immediately when an enclosing form is submitted via the
  27155. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  27156. * to have access to the updated model.
  27157. *
  27158. * The following example shows how to override immediate updates. Changes on the inputs within the
  27159. * form will update the model only when the control loses focus (blur event). If `escape` key is
  27160. * pressed while the input field is focused, the value is reset to the value in the current model.
  27161. *
  27162. * <example name="ngModelOptions-directive-blur" module="optionsExample">
  27163. * <file name="index.html">
  27164. * <div ng-controller="ExampleController">
  27165. * <form name="userForm">
  27166. * <label>
  27167. * Name:
  27168. * <input type="text" name="userName"
  27169. * ng-model="user.name"
  27170. * ng-model-options="{ updateOn: 'blur' }"
  27171. * ng-keyup="cancel($event)" />
  27172. * </label><br />
  27173. * <label>
  27174. * Other data:
  27175. * <input type="text" ng-model="user.data" />
  27176. * </label><br />
  27177. * </form>
  27178. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  27179. * </div>
  27180. * </file>
  27181. * <file name="app.js">
  27182. * angular.module('optionsExample', [])
  27183. * .controller('ExampleController', ['$scope', function($scope) {
  27184. * $scope.user = { name: 'say', data: '' };
  27185. *
  27186. * $scope.cancel = function(e) {
  27187. * if (e.keyCode === 27) {
  27188. * $scope.userForm.userName.$rollbackViewValue();
  27189. * }
  27190. * };
  27191. * }]);
  27192. * </file>
  27193. * <file name="protractor.js" type="protractor">
  27194. * var model = element(by.binding('user.name'));
  27195. * var input = element(by.model('user.name'));
  27196. * var other = element(by.model('user.data'));
  27197. *
  27198. * it('should allow custom events', function() {
  27199. * input.sendKeys(' hello');
  27200. * input.click();
  27201. * expect(model.getText()).toEqual('say');
  27202. * other.click();
  27203. * expect(model.getText()).toEqual('say hello');
  27204. * });
  27205. *
  27206. * it('should $rollbackViewValue when model changes', function() {
  27207. * input.sendKeys(' hello');
  27208. * expect(input.getAttribute('value')).toEqual('say hello');
  27209. * input.sendKeys(protractor.Key.ESCAPE);
  27210. * expect(input.getAttribute('value')).toEqual('say');
  27211. * other.click();
  27212. * expect(model.getText()).toEqual('say');
  27213. * });
  27214. * </file>
  27215. * </example>
  27216. *
  27217. * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
  27218. * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  27219. *
  27220. * <example name="ngModelOptions-directive-debounce" module="optionsExample">
  27221. * <file name="index.html">
  27222. * <div ng-controller="ExampleController">
  27223. * <form name="userForm">
  27224. * Name:
  27225. * <input type="text" name="userName"
  27226. * ng-model="user.name"
  27227. * ng-model-options="{ debounce: 1000 }" />
  27228. * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  27229. * </form>
  27230. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  27231. * </div>
  27232. * </file>
  27233. * <file name="app.js">
  27234. * angular.module('optionsExample', [])
  27235. * .controller('ExampleController', ['$scope', function($scope) {
  27236. * $scope.user = { name: 'say' };
  27237. * }]);
  27238. * </file>
  27239. * </example>
  27240. *
  27241. * ## Model updates and validation
  27242. *
  27243. * The default behaviour in `ngModel` is that the model value is set to `undefined` when the
  27244. * validation determines that the value is invalid. By setting the `allowInvalid` property to true,
  27245. * the model will still be updated even if the value is invalid.
  27246. *
  27247. *
  27248. * ## Connecting to the scope
  27249. *
  27250. * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
  27251. * on the scope refers to a "getter/setter" function rather than the value itself.
  27252. *
  27253. * The following example shows how to bind to getter/setters:
  27254. *
  27255. * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  27256. * <file name="index.html">
  27257. * <div ng-controller="ExampleController">
  27258. * <form name="userForm">
  27259. * <label>
  27260. * Name:
  27261. * <input type="text" name="userName"
  27262. * ng-model="user.name"
  27263. * ng-model-options="{ getterSetter: true }" />
  27264. * </label>
  27265. * </form>
  27266. * <pre>user.name = <span ng-bind="user.name()"></span></pre>
  27267. * </div>
  27268. * </file>
  27269. * <file name="app.js">
  27270. * angular.module('getterSetterExample', [])
  27271. * .controller('ExampleController', ['$scope', function($scope) {
  27272. * var _name = 'Brian';
  27273. * $scope.user = {
  27274. * name: function(newName) {
  27275. * return angular.isDefined(newName) ? (_name = newName) : _name;
  27276. * }
  27277. * };
  27278. * }]);
  27279. * </file>
  27280. * </example>
  27281. *
  27282. *
  27283. * ## Specifying timezones
  27284. *
  27285. * You can specify the timezone that date/time input directives expect by providing its name in the
  27286. * `timezone` property.
  27287. *
  27288. * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and
  27289. * and its descendents. Valid keys are:
  27290. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  27291. * events using an space delimited list. There is a special event called `default` that
  27292. * matches the default events belonging to the control.
  27293. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  27294. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  27295. * custom value for each event. For example:
  27296. * ```
  27297. * ng-model-options="{
  27298. * updateOn: 'default blur',
  27299. * debounce: { 'default': 500, 'blur': 0 }
  27300. * }"
  27301. * ```
  27302. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  27303. * not validate correctly instead of the default behavior of setting the model to undefined.
  27304. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  27305. * `ngModel` as getters/setters.
  27306. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  27307. * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the
  27308. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  27309. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  27310. * If not specified, the timezone of the browser will be used.
  27311. *
  27312. */
  27313. var ngModelOptionsDirective = function() {
  27314. NgModelOptionsController.$inject = ['$attrs', '$scope'];
  27315. function NgModelOptionsController($attrs, $scope) {
  27316. this.$$attrs = $attrs;
  27317. this.$$scope = $scope;
  27318. }
  27319. NgModelOptionsController.prototype = {
  27320. $onInit: function() {
  27321. var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions;
  27322. var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions);
  27323. this.$options = parentOptions.createChild(modelOptionsDefinition);
  27324. }
  27325. };
  27326. return {
  27327. restrict: 'A',
  27328. // ngModelOptions needs to run before ngModel and input directives
  27329. priority: 10,
  27330. require: {parentCtrl: '?^^ngModelOptions'},
  27331. bindToController: true,
  27332. controller: NgModelOptionsController
  27333. };
  27334. };
  27335. // shallow copy over values from `src` that are not already specified on `dst`
  27336. function defaults(dst, src) {
  27337. forEach(src, function(value, key) {
  27338. if (!isDefined(dst[key])) {
  27339. dst[key] = value;
  27340. }
  27341. });
  27342. }
  27343. /**
  27344. * @ngdoc directive
  27345. * @name ngNonBindable
  27346. * @restrict AC
  27347. * @priority 1000
  27348. *
  27349. * @description
  27350. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  27351. * DOM element. This is useful if the element contains what appears to be Angular directives and
  27352. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  27353. * displays snippets of code, for instance.
  27354. *
  27355. * @element ANY
  27356. *
  27357. * @example
  27358. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  27359. * but the one wrapped in `ngNonBindable` is left alone.
  27360. *
  27361. * @example
  27362. <example name="ng-non-bindable">
  27363. <file name="index.html">
  27364. <div>Normal: {{1 + 2}}</div>
  27365. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  27366. </file>
  27367. <file name="protractor.js" type="protractor">
  27368. it('should check ng-non-bindable', function() {
  27369. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  27370. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  27371. });
  27372. </file>
  27373. </example>
  27374. */
  27375. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  27376. /* exported ngOptionsDirective */
  27377. /* global jqLiteRemove */
  27378. var ngOptionsMinErr = minErr('ngOptions');
  27379. /**
  27380. * @ngdoc directive
  27381. * @name ngOptions
  27382. * @restrict A
  27383. *
  27384. * @description
  27385. *
  27386. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  27387. * elements for the `<select>` element using the array or object obtained by evaluating the
  27388. * `ngOptions` comprehension expression.
  27389. *
  27390. * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of
  27391. * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits:
  27392. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  27393. * comprehension expression
  27394. * - reduced memory consumption by not creating a new scope for each repeated instance
  27395. * - increased render speed by creating the options in a documentFragment instead of individually
  27396. *
  27397. * When an item in the `<select>` menu is selected, the array element or object property
  27398. * represented by the selected option will be bound to the model identified by the `ngModel`
  27399. * directive.
  27400. *
  27401. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  27402. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  27403. * option. See example below for demonstration.
  27404. *
  27405. * ## Complex Models (objects or collections)
  27406. *
  27407. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  27408. * binding the select to a model that is an object or a collection.
  27409. *
  27410. * One issue occurs if you want to preselect an option. For example, if you set
  27411. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  27412. * because the objects are not identical. So by default, you should always reference the item in your collection
  27413. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  27414. *
  27415. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  27416. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  27417. * collection items have an id property, you would `track by item.id`.
  27418. *
  27419. * A different issue with objects or collections is that ngModel won't detect if an object property or
  27420. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  27421. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  27422. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  27423. * has not changed identity, but only a property on the object or an item in the collection changes.
  27424. *
  27425. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  27426. * if the model is an array). This means that changing a property deeper than the first level inside the
  27427. * object/collection will not trigger a re-rendering.
  27428. *
  27429. * ## `select` **`as`**
  27430. *
  27431. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  27432. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  27433. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  27434. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  27435. *
  27436. *
  27437. * ### `select` **`as`** and **`track by`**
  27438. *
  27439. * <div class="alert alert-warning">
  27440. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  27441. * </div>
  27442. *
  27443. * Given this array of items on the $scope:
  27444. *
  27445. * ```js
  27446. * $scope.items = [{
  27447. * id: 1,
  27448. * label: 'aLabel',
  27449. * subItem: { name: 'aSubItem' }
  27450. * }, {
  27451. * id: 2,
  27452. * label: 'bLabel',
  27453. * subItem: { name: 'bSubItem' }
  27454. * }];
  27455. * ```
  27456. *
  27457. * This will work:
  27458. *
  27459. * ```html
  27460. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  27461. * ```
  27462. * ```js
  27463. * $scope.selected = $scope.items[0];
  27464. * ```
  27465. *
  27466. * but this will not work:
  27467. *
  27468. * ```html
  27469. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  27470. * ```
  27471. * ```js
  27472. * $scope.selected = $scope.items[0].subItem;
  27473. * ```
  27474. *
  27475. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  27476. * `items` array. Because the selected option has been set programmatically in the controller, the
  27477. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  27478. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  27479. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  27480. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  27481. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  27482. *
  27483. *
  27484. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  27485. * @param {comprehension_expression} ngOptions in one of the following forms:
  27486. *
  27487. * * for array data sources:
  27488. * * `label` **`for`** `value` **`in`** `array`
  27489. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  27490. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  27491. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  27492. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  27493. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  27494. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  27495. * (for including a filter with `track by`)
  27496. * * for object data sources:
  27497. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  27498. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  27499. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  27500. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  27501. * * `select` **`as`** `label` **`group by`** `group`
  27502. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  27503. * * `select` **`as`** `label` **`disable when`** `disable`
  27504. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  27505. *
  27506. * Where:
  27507. *
  27508. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  27509. * * `value`: local variable which will refer to each item in the `array` or each property value
  27510. * of `object` during iteration.
  27511. * * `key`: local variable which will refer to a property name in `object` during iteration.
  27512. * * `label`: The result of this expression will be the label for `<option>` element. The
  27513. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  27514. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  27515. * element. If not specified, `select` expression will default to `value`.
  27516. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  27517. * DOM element.
  27518. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  27519. * element. Return `true` to disable.
  27520. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  27521. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  27522. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  27523. * even when the options are recreated (e.g. reloaded from the server).
  27524. * @param {string=} name Property name of the form under which the control is published.
  27525. * @param {string=} required The control is considered valid only if value is entered.
  27526. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  27527. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  27528. * `required` when you want to data-bind to the `required` attribute.
  27529. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  27530. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  27531. *
  27532. * @example
  27533. <example module="selectExample" name="select">
  27534. <file name="index.html">
  27535. <script>
  27536. angular.module('selectExample', [])
  27537. .controller('ExampleController', ['$scope', function($scope) {
  27538. $scope.colors = [
  27539. {name:'black', shade:'dark'},
  27540. {name:'white', shade:'light', notAnOption: true},
  27541. {name:'red', shade:'dark'},
  27542. {name:'blue', shade:'dark', notAnOption: true},
  27543. {name:'yellow', shade:'light', notAnOption: false}
  27544. ];
  27545. $scope.myColor = $scope.colors[2]; // red
  27546. }]);
  27547. </script>
  27548. <div ng-controller="ExampleController">
  27549. <ul>
  27550. <li ng-repeat="color in colors">
  27551. <label>Name: <input ng-model="color.name"></label>
  27552. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  27553. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  27554. </li>
  27555. <li>
  27556. <button ng-click="colors.push({})">add</button>
  27557. </li>
  27558. </ul>
  27559. <hr/>
  27560. <label>Color (null not allowed):
  27561. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  27562. </label><br/>
  27563. <label>Color (null allowed):
  27564. <span class="nullable">
  27565. <select ng-model="myColor" ng-options="color.name for color in colors">
  27566. <option value="">-- choose color --</option>
  27567. </select>
  27568. </span></label><br/>
  27569. <label>Color grouped by shade:
  27570. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  27571. </select>
  27572. </label><br/>
  27573. <label>Color grouped by shade, with some disabled:
  27574. <select ng-model="myColor"
  27575. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  27576. </select>
  27577. </label><br/>
  27578. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  27579. <br/>
  27580. <hr/>
  27581. Currently selected: {{ {selected_color:myColor} }}
  27582. <div style="border:solid 1px black; height:20px"
  27583. ng-style="{'background-color':myColor.name}">
  27584. </div>
  27585. </div>
  27586. </file>
  27587. <file name="protractor.js" type="protractor">
  27588. it('should check ng-options', function() {
  27589. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  27590. element.all(by.model('myColor')).first().click();
  27591. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  27592. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  27593. element(by.css('.nullable select[ng-model="myColor"]')).click();
  27594. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  27595. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  27596. });
  27597. </file>
  27598. </example>
  27599. */
  27600. /* eslint-disable max-len */
  27601. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999
  27602. 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]+?))?$/;
  27603. // 1: value expression (valueFn)
  27604. // 2: label expression (displayFn)
  27605. // 3: group by expression (groupByFn)
  27606. // 4: disable when expression (disableWhenFn)
  27607. // 5: array item variable name
  27608. // 6: object item key variable name
  27609. // 7: object item value variable name
  27610. // 8: collection expression
  27611. // 9: track by expression
  27612. /* eslint-enable */
  27613. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  27614. function parseOptionsExpression(optionsExp, selectElement, scope) {
  27615. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  27616. if (!(match)) {
  27617. throw ngOptionsMinErr('iexp',
  27618. 'Expected expression in form of ' +
  27619. '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
  27620. ' but got \'{0}\'. Element: {1}',
  27621. optionsExp, startingTag(selectElement));
  27622. }
  27623. // Extract the parts from the ngOptions expression
  27624. // The variable name for the value of the item in the collection
  27625. var valueName = match[5] || match[7];
  27626. // The variable name for the key of the item in the collection
  27627. var keyName = match[6];
  27628. // An expression that generates the viewValue for an option if there is a label expression
  27629. var selectAs = / as /.test(match[0]) && match[1];
  27630. // An expression that is used to track the id of each object in the options collection
  27631. var trackBy = match[9];
  27632. // An expression that generates the viewValue for an option if there is no label expression
  27633. var valueFn = $parse(match[2] ? match[1] : valueName);
  27634. var selectAsFn = selectAs && $parse(selectAs);
  27635. var viewValueFn = selectAsFn || valueFn;
  27636. var trackByFn = trackBy && $parse(trackBy);
  27637. // Get the value by which we are going to track the option
  27638. // if we have a trackFn then use that (passing scope and locals)
  27639. // otherwise just hash the given viewValue
  27640. var getTrackByValueFn = trackBy ?
  27641. function(value, locals) { return trackByFn(scope, locals); } :
  27642. function getHashOfValue(value) { return hashKey(value); };
  27643. var getTrackByValue = function(value, key) {
  27644. return getTrackByValueFn(value, getLocals(value, key));
  27645. };
  27646. var displayFn = $parse(match[2] || match[1]);
  27647. var groupByFn = $parse(match[3] || '');
  27648. var disableWhenFn = $parse(match[4] || '');
  27649. var valuesFn = $parse(match[8]);
  27650. var locals = {};
  27651. var getLocals = keyName ? function(value, key) {
  27652. locals[keyName] = key;
  27653. locals[valueName] = value;
  27654. return locals;
  27655. } : function(value) {
  27656. locals[valueName] = value;
  27657. return locals;
  27658. };
  27659. function Option(selectValue, viewValue, label, group, disabled) {
  27660. this.selectValue = selectValue;
  27661. this.viewValue = viewValue;
  27662. this.label = label;
  27663. this.group = group;
  27664. this.disabled = disabled;
  27665. }
  27666. function getOptionValuesKeys(optionValues) {
  27667. var optionValuesKeys;
  27668. if (!keyName && isArrayLike(optionValues)) {
  27669. optionValuesKeys = optionValues;
  27670. } else {
  27671. // if object, extract keys, in enumeration order, unsorted
  27672. optionValuesKeys = [];
  27673. for (var itemKey in optionValues) {
  27674. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  27675. optionValuesKeys.push(itemKey);
  27676. }
  27677. }
  27678. }
  27679. return optionValuesKeys;
  27680. }
  27681. return {
  27682. trackBy: trackBy,
  27683. getTrackByValue: getTrackByValue,
  27684. getWatchables: $parse(valuesFn, function(optionValues) {
  27685. // Create a collection of things that we would like to watch (watchedArray)
  27686. // so that they can all be watched using a single $watchCollection
  27687. // that only runs the handler once if anything changes
  27688. var watchedArray = [];
  27689. optionValues = optionValues || [];
  27690. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27691. var optionValuesLength = optionValuesKeys.length;
  27692. for (var index = 0; index < optionValuesLength; index++) {
  27693. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27694. var value = optionValues[key];
  27695. var locals = getLocals(value, key);
  27696. var selectValue = getTrackByValueFn(value, locals);
  27697. watchedArray.push(selectValue);
  27698. // Only need to watch the displayFn if there is a specific label expression
  27699. if (match[2] || match[1]) {
  27700. var label = displayFn(scope, locals);
  27701. watchedArray.push(label);
  27702. }
  27703. // Only need to watch the disableWhenFn if there is a specific disable expression
  27704. if (match[4]) {
  27705. var disableWhen = disableWhenFn(scope, locals);
  27706. watchedArray.push(disableWhen);
  27707. }
  27708. }
  27709. return watchedArray;
  27710. }),
  27711. getOptions: function() {
  27712. var optionItems = [];
  27713. var selectValueMap = {};
  27714. // The option values were already computed in the `getWatchables` fn,
  27715. // which must have been called to trigger `getOptions`
  27716. var optionValues = valuesFn(scope) || [];
  27717. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27718. var optionValuesLength = optionValuesKeys.length;
  27719. for (var index = 0; index < optionValuesLength; index++) {
  27720. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27721. var value = optionValues[key];
  27722. var locals = getLocals(value, key);
  27723. var viewValue = viewValueFn(scope, locals);
  27724. var selectValue = getTrackByValueFn(viewValue, locals);
  27725. var label = displayFn(scope, locals);
  27726. var group = groupByFn(scope, locals);
  27727. var disabled = disableWhenFn(scope, locals);
  27728. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  27729. optionItems.push(optionItem);
  27730. selectValueMap[selectValue] = optionItem;
  27731. }
  27732. return {
  27733. items: optionItems,
  27734. selectValueMap: selectValueMap,
  27735. getOptionFromViewValue: function(value) {
  27736. return selectValueMap[getTrackByValue(value)];
  27737. },
  27738. getViewValueFromOption: function(option) {
  27739. // If the viewValue could be an object that may be mutated by the application,
  27740. // we need to make a copy and not return the reference to the value on the option.
  27741. return trackBy ? copy(option.viewValue) : option.viewValue;
  27742. }
  27743. };
  27744. }
  27745. };
  27746. }
  27747. // Support: IE 9 only
  27748. // We can't just jqLite('<option>') since jqLite is not smart enough
  27749. // to create it in <select> and IE barfs otherwise.
  27750. var optionTemplate = window.document.createElement('option'),
  27751. optGroupTemplate = window.document.createElement('optgroup');
  27752. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  27753. var selectCtrl = ctrls[0];
  27754. var ngModelCtrl = ctrls[1];
  27755. var multiple = attr.multiple;
  27756. // The emptyOption allows the application developer to provide their own custom "empty"
  27757. // option when the viewValue does not match any of the option values.
  27758. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  27759. if (children[i].value === '') {
  27760. selectCtrl.hasEmptyOption = true;
  27761. selectCtrl.emptyOption = children.eq(i);
  27762. break;
  27763. }
  27764. }
  27765. // The empty option will be compiled and rendered before we first generate the options
  27766. selectElement.empty();
  27767. var providedEmptyOption = !!selectCtrl.emptyOption;
  27768. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  27769. unknownOption.val('?');
  27770. var options;
  27771. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  27772. // This stores the newly created options before they are appended to the select.
  27773. // Since the contents are removed from the fragment when it is appended,
  27774. // we only need to create it once.
  27775. var listFragment = $document[0].createDocumentFragment();
  27776. // Overwrite the implementation. ngOptions doesn't use hashes
  27777. selectCtrl.generateUnknownOptionValue = function(val) {
  27778. return '?';
  27779. };
  27780. // Update the controller methods for multiple selectable options
  27781. if (!multiple) {
  27782. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  27783. // The options might not be defined yet when ngModel tries to render
  27784. if (!options) return;
  27785. var selectedOption = selectElement[0].options[selectElement[0].selectedIndex];
  27786. var option = options.getOptionFromViewValue(value);
  27787. // Make sure to remove the selected attribute from the previously selected option
  27788. // Otherwise, screen readers might get confused
  27789. if (selectedOption) selectedOption.removeAttribute('selected');
  27790. if (option) {
  27791. // Don't update the option when it is already selected.
  27792. // For example, the browser will select the first option by default. In that case,
  27793. // most properties are set automatically - except the `selected` attribute, which we
  27794. // set always
  27795. if (selectElement[0].value !== option.selectValue) {
  27796. selectCtrl.removeUnknownOption();
  27797. selectElement[0].value = option.selectValue;
  27798. option.element.selected = true;
  27799. }
  27800. option.element.setAttribute('selected', 'selected');
  27801. } else {
  27802. selectCtrl.selectUnknownOrEmptyOption(value);
  27803. }
  27804. };
  27805. selectCtrl.readValue = function readNgOptionsValue() {
  27806. var selectedOption = options.selectValueMap[selectElement.val()];
  27807. if (selectedOption && !selectedOption.disabled) {
  27808. selectCtrl.unselectEmptyOption();
  27809. selectCtrl.removeUnknownOption();
  27810. return options.getViewValueFromOption(selectedOption);
  27811. }
  27812. return null;
  27813. };
  27814. // If we are using `track by` then we must watch the tracked value on the model
  27815. // since ngModel only watches for object identity change
  27816. // FIXME: When a user selects an option, this watch will fire needlessly
  27817. if (ngOptions.trackBy) {
  27818. scope.$watch(
  27819. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  27820. function() { ngModelCtrl.$render(); }
  27821. );
  27822. }
  27823. } else {
  27824. selectCtrl.writeValue = function writeNgOptionsMultiple(values) {
  27825. // The options might not be defined yet when ngModel tries to render
  27826. if (!options) return;
  27827. // Only set `<option>.selected` if necessary, in order to prevent some browsers from
  27828. // scrolling to `<option>` elements that are outside the `<select>` element's viewport.
  27829. var selectedOptions = values && values.map(getAndUpdateSelectedOption) || [];
  27830. options.items.forEach(function(option) {
  27831. if (option.element.selected && !includes(selectedOptions, option)) {
  27832. option.element.selected = false;
  27833. }
  27834. });
  27835. };
  27836. selectCtrl.readValue = function readNgOptionsMultiple() {
  27837. var selectedValues = selectElement.val() || [],
  27838. selections = [];
  27839. forEach(selectedValues, function(value) {
  27840. var option = options.selectValueMap[value];
  27841. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  27842. });
  27843. return selections;
  27844. };
  27845. // If we are using `track by` then we must watch these tracked values on the model
  27846. // since ngModel only watches for object identity change
  27847. if (ngOptions.trackBy) {
  27848. scope.$watchCollection(function() {
  27849. if (isArray(ngModelCtrl.$viewValue)) {
  27850. return ngModelCtrl.$viewValue.map(function(value) {
  27851. return ngOptions.getTrackByValue(value);
  27852. });
  27853. }
  27854. }, function() {
  27855. ngModelCtrl.$render();
  27856. });
  27857. }
  27858. }
  27859. if (providedEmptyOption) {
  27860. // compile the element since there might be bindings in it
  27861. $compile(selectCtrl.emptyOption)(scope);
  27862. selectElement.prepend(selectCtrl.emptyOption);
  27863. if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) {
  27864. // This means the empty option has currently no actual DOM node, probably because
  27865. // it has been modified by a transclusion directive.
  27866. selectCtrl.hasEmptyOption = false;
  27867. // Redefine the registerOption function, which will catch
  27868. // options that are added by ngIf etc. (rendering of the node is async because of
  27869. // lazy transclusion)
  27870. selectCtrl.registerOption = function(optionScope, optionEl) {
  27871. if (optionEl.val() === '') {
  27872. selectCtrl.hasEmptyOption = true;
  27873. selectCtrl.emptyOption = optionEl;
  27874. selectCtrl.emptyOption.removeClass('ng-scope');
  27875. // This ensures the new empty option is selected if previously no option was selected
  27876. ngModelCtrl.$render();
  27877. optionEl.on('$destroy', function() {
  27878. var needsRerender = selectCtrl.$isEmptyOptionSelected();
  27879. selectCtrl.hasEmptyOption = false;
  27880. selectCtrl.emptyOption = undefined;
  27881. if (needsRerender) ngModelCtrl.$render();
  27882. });
  27883. }
  27884. };
  27885. } else {
  27886. // remove the class, which is added automatically because we recompile the element and it
  27887. // becomes the compilation root
  27888. selectCtrl.emptyOption.removeClass('ng-scope');
  27889. }
  27890. }
  27891. // We will re-render the option elements if the option values or labels change
  27892. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  27893. // ------------------------------------------------------------------ //
  27894. function addOptionElement(option, parent) {
  27895. var optionElement = optionTemplate.cloneNode(false);
  27896. parent.appendChild(optionElement);
  27897. updateOptionElement(option, optionElement);
  27898. }
  27899. function getAndUpdateSelectedOption(viewValue) {
  27900. var option = options.getOptionFromViewValue(viewValue);
  27901. var element = option && option.element;
  27902. if (element && !element.selected) element.selected = true;
  27903. return option;
  27904. }
  27905. function updateOptionElement(option, element) {
  27906. option.element = element;
  27907. element.disabled = option.disabled;
  27908. // Support: IE 11 only, Edge 12-13 only
  27909. // NOTE: The label must be set before the value, otherwise IE 11 & Edge create unresponsive
  27910. // selects in certain circumstances when multiple selects are next to each other and display
  27911. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  27912. // See https://github.com/angular/angular.js/issues/11314 for more info.
  27913. // This is unfortunately untestable with unit / e2e tests
  27914. if (option.label !== element.label) {
  27915. element.label = option.label;
  27916. element.textContent = option.label;
  27917. }
  27918. element.value = option.selectValue;
  27919. }
  27920. function updateOptions() {
  27921. var previousValue = options && selectCtrl.readValue();
  27922. // We must remove all current options, but cannot simply set innerHTML = null
  27923. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  27924. // must preserve.
  27925. // Instead, iterate over the current option elements and remove them or their optgroup
  27926. // parents
  27927. if (options) {
  27928. for (var i = options.items.length - 1; i >= 0; i--) {
  27929. var option = options.items[i];
  27930. if (isDefined(option.group)) {
  27931. jqLiteRemove(option.element.parentNode);
  27932. } else {
  27933. jqLiteRemove(option.element);
  27934. }
  27935. }
  27936. }
  27937. options = ngOptions.getOptions();
  27938. var groupElementMap = {};
  27939. options.items.forEach(function addOption(option) {
  27940. var groupElement;
  27941. if (isDefined(option.group)) {
  27942. // This option is to live in a group
  27943. // See if we have already created this group
  27944. groupElement = groupElementMap[option.group];
  27945. if (!groupElement) {
  27946. groupElement = optGroupTemplate.cloneNode(false);
  27947. listFragment.appendChild(groupElement);
  27948. // Update the label on the group element
  27949. // "null" is special cased because of Safari
  27950. groupElement.label = option.group === null ? 'null' : option.group;
  27951. // Store it for use later
  27952. groupElementMap[option.group] = groupElement;
  27953. }
  27954. addOptionElement(option, groupElement);
  27955. } else {
  27956. // This option is not in a group
  27957. addOptionElement(option, listFragment);
  27958. }
  27959. });
  27960. selectElement[0].appendChild(listFragment);
  27961. ngModelCtrl.$render();
  27962. // Check to see if the value has changed due to the update to the options
  27963. if (!ngModelCtrl.$isEmpty(previousValue)) {
  27964. var nextValue = selectCtrl.readValue();
  27965. var isNotPrimitive = ngOptions.trackBy || multiple;
  27966. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  27967. ngModelCtrl.$setViewValue(nextValue);
  27968. ngModelCtrl.$render();
  27969. }
  27970. }
  27971. }
  27972. }
  27973. return {
  27974. restrict: 'A',
  27975. terminal: true,
  27976. require: ['select', 'ngModel'],
  27977. link: {
  27978. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  27979. // Deactivate the SelectController.register method to prevent
  27980. // option directives from accidentally registering themselves
  27981. // (and unwanted $destroy handlers etc.)
  27982. ctrls[0].registerOption = noop;
  27983. },
  27984. post: ngOptionsPostLink
  27985. }
  27986. };
  27987. }];
  27988. /**
  27989. * @ngdoc directive
  27990. * @name ngPluralize
  27991. * @restrict EA
  27992. *
  27993. * @description
  27994. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  27995. * These rules are bundled with angular.js, but can be overridden
  27996. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  27997. * by specifying the mappings between
  27998. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  27999. * and the strings to be displayed.
  28000. *
  28001. * # Plural categories and explicit number rules
  28002. * There are two
  28003. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  28004. * in Angular's default en-US locale: "one" and "other".
  28005. *
  28006. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  28007. * any number that is not 1), an explicit number rule can only match one number. For example, the
  28008. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  28009. * and explicit number rules throughout the rest of this documentation.
  28010. *
  28011. * # Configuring ngPluralize
  28012. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  28013. * You can also provide an optional attribute, `offset`.
  28014. *
  28015. * The value of the `count` attribute can be either a string or an {@link guide/expression
  28016. * Angular expression}; these are evaluated on the current scope for its bound value.
  28017. *
  28018. * The `when` attribute specifies the mappings between plural categories and the actual
  28019. * string to be displayed. The value of the attribute should be a JSON object.
  28020. *
  28021. * The following example shows how to configure ngPluralize:
  28022. *
  28023. * ```html
  28024. * <ng-pluralize count="personCount"
  28025. when="{'0': 'Nobody is viewing.',
  28026. * 'one': '1 person is viewing.',
  28027. * 'other': '{} people are viewing.'}">
  28028. * </ng-pluralize>
  28029. *```
  28030. *
  28031. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  28032. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  28033. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  28034. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  28035. * show "a dozen people are viewing".
  28036. *
  28037. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  28038. * into pluralized strings. In the previous example, Angular will replace `{}` with
  28039. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  28040. * for <span ng-non-bindable>{{numberExpression}}</span>.
  28041. *
  28042. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  28043. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  28044. *
  28045. * # Configuring ngPluralize with offset
  28046. * The `offset` attribute allows further customization of pluralized text, which can result in
  28047. * a better user experience. For example, instead of the message "4 people are viewing this document",
  28048. * you might display "John, Kate and 2 others are viewing this document".
  28049. * The offset attribute allows you to offset a number by any desired value.
  28050. * Let's take a look at an example:
  28051. *
  28052. * ```html
  28053. * <ng-pluralize count="personCount" offset=2
  28054. * when="{'0': 'Nobody is viewing.',
  28055. * '1': '{{person1}} is viewing.',
  28056. * '2': '{{person1}} and {{person2}} are viewing.',
  28057. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  28058. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  28059. * </ng-pluralize>
  28060. * ```
  28061. *
  28062. * Notice that we are still using two plural categories(one, other), but we added
  28063. * three explicit number rules 0, 1 and 2.
  28064. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  28065. * When three people view the document, no explicit number rule is found, so
  28066. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  28067. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  28068. * is shown.
  28069. *
  28070. * Note that when you specify offsets, you must provide explicit number rules for
  28071. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  28072. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  28073. * plural categories "one" and "other".
  28074. *
  28075. * @param {string|expression} count The variable to be bound to.
  28076. * @param {string} when The mapping between plural category to its corresponding strings.
  28077. * @param {number=} offset Offset to deduct from the total number.
  28078. *
  28079. * @example
  28080. <example module="pluralizeExample" name="ng-pluralize">
  28081. <file name="index.html">
  28082. <script>
  28083. angular.module('pluralizeExample', [])
  28084. .controller('ExampleController', ['$scope', function($scope) {
  28085. $scope.person1 = 'Igor';
  28086. $scope.person2 = 'Misko';
  28087. $scope.personCount = 1;
  28088. }]);
  28089. </script>
  28090. <div ng-controller="ExampleController">
  28091. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  28092. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  28093. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  28094. <!--- Example with simple pluralization rules for en locale --->
  28095. Without Offset:
  28096. <ng-pluralize count="personCount"
  28097. when="{'0': 'Nobody is viewing.',
  28098. 'one': '1 person is viewing.',
  28099. 'other': '{} people are viewing.'}">
  28100. </ng-pluralize><br>
  28101. <!--- Example with offset --->
  28102. With Offset(2):
  28103. <ng-pluralize count="personCount" offset=2
  28104. when="{'0': 'Nobody is viewing.',
  28105. '1': '{{person1}} is viewing.',
  28106. '2': '{{person1}} and {{person2}} are viewing.',
  28107. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  28108. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  28109. </ng-pluralize>
  28110. </div>
  28111. </file>
  28112. <file name="protractor.js" type="protractor">
  28113. it('should show correct pluralized string', function() {
  28114. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  28115. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  28116. var countInput = element(by.model('personCount'));
  28117. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  28118. expect(withOffset.getText()).toEqual('Igor is viewing.');
  28119. countInput.clear();
  28120. countInput.sendKeys('0');
  28121. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  28122. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  28123. countInput.clear();
  28124. countInput.sendKeys('2');
  28125. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  28126. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  28127. countInput.clear();
  28128. countInput.sendKeys('3');
  28129. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  28130. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  28131. countInput.clear();
  28132. countInput.sendKeys('4');
  28133. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  28134. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  28135. });
  28136. it('should show data-bound names', function() {
  28137. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  28138. var personCount = element(by.model('personCount'));
  28139. var person1 = element(by.model('person1'));
  28140. var person2 = element(by.model('person2'));
  28141. personCount.clear();
  28142. personCount.sendKeys('4');
  28143. person1.clear();
  28144. person1.sendKeys('Di');
  28145. person2.clear();
  28146. person2.sendKeys('Vojta');
  28147. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  28148. });
  28149. </file>
  28150. </example>
  28151. */
  28152. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  28153. var BRACE = /{}/g,
  28154. IS_WHEN = /^when(Minus)?(.+)$/;
  28155. return {
  28156. link: function(scope, element, attr) {
  28157. var numberExp = attr.count,
  28158. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  28159. offset = attr.offset || 0,
  28160. whens = scope.$eval(whenExp) || {},
  28161. whensExpFns = {},
  28162. startSymbol = $interpolate.startSymbol(),
  28163. endSymbol = $interpolate.endSymbol(),
  28164. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  28165. watchRemover = angular.noop,
  28166. lastCount;
  28167. forEach(attr, function(expression, attributeName) {
  28168. var tmpMatch = IS_WHEN.exec(attributeName);
  28169. if (tmpMatch) {
  28170. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  28171. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  28172. }
  28173. });
  28174. forEach(whens, function(expression, key) {
  28175. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  28176. });
  28177. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  28178. var count = parseFloat(newVal);
  28179. var countIsNaN = isNumberNaN(count);
  28180. if (!countIsNaN && !(count in whens)) {
  28181. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  28182. // Otherwise, check it against pluralization rules in $locale service.
  28183. count = $locale.pluralCat(count - offset);
  28184. }
  28185. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  28186. // In JS `NaN !== NaN`, so we have to explicitly check.
  28187. if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
  28188. watchRemover();
  28189. var whenExpFn = whensExpFns[count];
  28190. if (isUndefined(whenExpFn)) {
  28191. if (newVal != null) {
  28192. $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
  28193. }
  28194. watchRemover = noop;
  28195. updateElementText();
  28196. } else {
  28197. watchRemover = scope.$watch(whenExpFn, updateElementText);
  28198. }
  28199. lastCount = count;
  28200. }
  28201. });
  28202. function updateElementText(newText) {
  28203. element.text(newText || '');
  28204. }
  28205. }
  28206. };
  28207. }];
  28208. /* exported ngRepeatDirective */
  28209. /**
  28210. * @ngdoc directive
  28211. * @name ngRepeat
  28212. * @multiElement
  28213. * @restrict A
  28214. *
  28215. * @description
  28216. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  28217. * instance gets its own scope, where the given loop variable is set to the current collection item,
  28218. * and `$index` is set to the item index or key.
  28219. *
  28220. * Special properties are exposed on the local scope of each template instance, including:
  28221. *
  28222. * | Variable | Type | Details |
  28223. * |-----------|-----------------|-----------------------------------------------------------------------------|
  28224. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  28225. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  28226. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  28227. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  28228. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  28229. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  28230. *
  28231. * <div class="alert alert-info">
  28232. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  28233. * This may be useful when, for instance, nesting ngRepeats.
  28234. * </div>
  28235. *
  28236. *
  28237. * # Iterating over object properties
  28238. *
  28239. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  28240. * syntax:
  28241. *
  28242. * ```js
  28243. * <div ng-repeat="(key, value) in myObj"> ... </div>
  28244. * ```
  28245. *
  28246. * However, there are a few limitations compared to array iteration:
  28247. *
  28248. * - The JavaScript specification does not define the order of keys
  28249. * returned for an object, so Angular relies on the order returned by the browser
  28250. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  28251. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  28252. * and reinstated. See the
  28253. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  28254. *
  28255. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  28256. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  28257. *
  28258. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  28259. * objects, and will throw an error if used with one.
  28260. *
  28261. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  28262. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  28263. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  28264. * or implement a `$watch` on the object yourself.
  28265. *
  28266. *
  28267. * # Tracking and Duplicates
  28268. *
  28269. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  28270. * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:
  28271. *
  28272. * * When an item is added, a new instance of the template is added to the DOM.
  28273. * * When an item is removed, its template instance is removed from the DOM.
  28274. * * When items are reordered, their respective templates are reordered in the DOM.
  28275. *
  28276. * To minimize creation of DOM elements, `ngRepeat` uses a function
  28277. * to "keep track" of all items in the collection and their corresponding DOM elements.
  28278. * For example, if an item is added to the collection, `ngRepeat` will know that all other items
  28279. * already have DOM elements, and will not re-render them.
  28280. *
  28281. * The default tracking function (which tracks items by their identity) does not allow
  28282. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  28283. * to maintain a one-to-one mapping between collection items and DOM elements.
  28284. *
  28285. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  28286. * with your own using the `track by` expression.
  28287. *
  28288. * For example, you may track items by the index of each item in the collection, using the
  28289. * special scope property `$index`:
  28290. * ```html
  28291. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  28292. * {{n}}
  28293. * </div>
  28294. * ```
  28295. *
  28296. * You may also use arbitrary expressions in `track by`, including references to custom functions
  28297. * on the scope:
  28298. * ```html
  28299. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  28300. * {{n}}
  28301. * </div>
  28302. * ```
  28303. *
  28304. * <div class="alert alert-success">
  28305. * If you are working with objects that have a unique identifier property, you should track
  28306. * by this identifier instead of the object instance. Should you reload your data later, `ngRepeat`
  28307. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  28308. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  28309. * this significantly improves rendering performance. If you don't have a unique identifier,
  28310. * `track by $index` can also provide a performance boost.
  28311. * </div>
  28312. *
  28313. * ```html
  28314. * <div ng-repeat="model in collection track by model.id">
  28315. * {{model.name}}
  28316. * </div>
  28317. * ```
  28318. *
  28319. * <br />
  28320. * <div class="alert alert-warning">
  28321. * Avoid using `track by $index` when the repeated template contains
  28322. * {@link guide/expression#one-time-binding one-time bindings}. In such cases, the `nth` DOM
  28323. * element will always be matched with the `nth` item of the array, so the bindings on that element
  28324. * will not be updated even when the corresponding item changes, essentially causing the view to get
  28325. * out-of-sync with the underlying data.
  28326. * </div>
  28327. *
  28328. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  28329. * `$id` function, which tracks items by their identity:
  28330. * ```html
  28331. * <div ng-repeat="obj in collection track by $id(obj)">
  28332. * {{obj.prop}}
  28333. * </div>
  28334. * ```
  28335. *
  28336. * <br />
  28337. * <div class="alert alert-warning">
  28338. * **Note:** `track by` must always be the last expression:
  28339. * </div>
  28340. * ```
  28341. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  28342. * {{model.name}}
  28343. * </div>
  28344. * ```
  28345. *
  28346. *
  28347. * # Special repeat start and end points
  28348. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  28349. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  28350. * 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)
  28351. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  28352. *
  28353. * The example below makes use of this feature:
  28354. * ```html
  28355. * <header ng-repeat-start="item in items">
  28356. * Header {{ item }}
  28357. * </header>
  28358. * <div class="body">
  28359. * Body {{ item }}
  28360. * </div>
  28361. * <footer ng-repeat-end>
  28362. * Footer {{ item }}
  28363. * </footer>
  28364. * ```
  28365. *
  28366. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  28367. * ```html
  28368. * <header>
  28369. * Header A
  28370. * </header>
  28371. * <div class="body">
  28372. * Body A
  28373. * </div>
  28374. * <footer>
  28375. * Footer A
  28376. * </footer>
  28377. * <header>
  28378. * Header B
  28379. * </header>
  28380. * <div class="body">
  28381. * Body B
  28382. * </div>
  28383. * <footer>
  28384. * Footer B
  28385. * </footer>
  28386. * ```
  28387. *
  28388. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  28389. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  28390. *
  28391. * @animations
  28392. * | Animation | Occurs |
  28393. * |----------------------------------|-------------------------------------|
  28394. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  28395. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  28396. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  28397. *
  28398. * See the example below for defining CSS animations with ngRepeat.
  28399. *
  28400. * @element ANY
  28401. * @scope
  28402. * @priority 1000
  28403. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  28404. * formats are currently supported:
  28405. *
  28406. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  28407. * is a scope expression giving the collection to enumerate.
  28408. *
  28409. * For example: `album in artist.albums`.
  28410. *
  28411. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  28412. * and `expression` is the scope expression giving the collection to enumerate.
  28413. *
  28414. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  28415. *
  28416. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  28417. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  28418. * is specified, ng-repeat associates elements by identity. It is an error to have
  28419. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  28420. * mapped to the same DOM element, which is not possible.)
  28421. *
  28422. * <div class="alert alert-warning">
  28423. * <strong>Note:</strong> the `track by` expression must come last - after any filters, and the alias expression.
  28424. * </div>
  28425. *
  28426. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  28427. * will be associated by item identity in the array.
  28428. *
  28429. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  28430. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  28431. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  28432. * element in the same way in the DOM.
  28433. *
  28434. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  28435. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  28436. * property is same.
  28437. *
  28438. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  28439. * to items in conjunction with a tracking expression.
  28440. *
  28441. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  28442. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  28443. * when a filter is active on the repeater, but the filtered result set is empty.
  28444. *
  28445. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  28446. * the items have been processed through the filter.
  28447. *
  28448. * 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
  28449. * (and not as operator, inside an expression).
  28450. *
  28451. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  28452. *
  28453. * @example
  28454. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  28455. * results by name or by age. New (entering) and removed (leaving) items are animated.
  28456. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true" name="ng-repeat">
  28457. <file name="index.html">
  28458. <div ng-controller="repeatController">
  28459. I have {{friends.length}} friends. They are:
  28460. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  28461. <ul class="example-animate-container">
  28462. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  28463. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  28464. </li>
  28465. <li class="animate-repeat" ng-if="results.length === 0">
  28466. <strong>No results found...</strong>
  28467. </li>
  28468. </ul>
  28469. </div>
  28470. </file>
  28471. <file name="script.js">
  28472. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  28473. $scope.friends = [
  28474. {name:'John', age:25, gender:'boy'},
  28475. {name:'Jessie', age:30, gender:'girl'},
  28476. {name:'Johanna', age:28, gender:'girl'},
  28477. {name:'Joy', age:15, gender:'girl'},
  28478. {name:'Mary', age:28, gender:'girl'},
  28479. {name:'Peter', age:95, gender:'boy'},
  28480. {name:'Sebastian', age:50, gender:'boy'},
  28481. {name:'Erika', age:27, gender:'girl'},
  28482. {name:'Patrick', age:40, gender:'boy'},
  28483. {name:'Samantha', age:60, gender:'girl'}
  28484. ];
  28485. });
  28486. </file>
  28487. <file name="animations.css">
  28488. .example-animate-container {
  28489. background:white;
  28490. border:1px solid black;
  28491. list-style:none;
  28492. margin:0;
  28493. padding:0 10px;
  28494. }
  28495. .animate-repeat {
  28496. line-height:30px;
  28497. list-style:none;
  28498. box-sizing:border-box;
  28499. }
  28500. .animate-repeat.ng-move,
  28501. .animate-repeat.ng-enter,
  28502. .animate-repeat.ng-leave {
  28503. transition:all linear 0.5s;
  28504. }
  28505. .animate-repeat.ng-leave.ng-leave-active,
  28506. .animate-repeat.ng-move,
  28507. .animate-repeat.ng-enter {
  28508. opacity:0;
  28509. max-height:0;
  28510. }
  28511. .animate-repeat.ng-leave,
  28512. .animate-repeat.ng-move.ng-move-active,
  28513. .animate-repeat.ng-enter.ng-enter-active {
  28514. opacity:1;
  28515. max-height:30px;
  28516. }
  28517. </file>
  28518. <file name="protractor.js" type="protractor">
  28519. var friends = element.all(by.repeater('friend in friends'));
  28520. it('should render initial data set', function() {
  28521. expect(friends.count()).toBe(10);
  28522. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  28523. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  28524. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  28525. expect(element(by.binding('friends.length')).getText())
  28526. .toMatch("I have 10 friends. They are:");
  28527. });
  28528. it('should update repeater when filter predicate changes', function() {
  28529. expect(friends.count()).toBe(10);
  28530. element(by.model('q')).sendKeys('ma');
  28531. expect(friends.count()).toBe(2);
  28532. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  28533. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  28534. });
  28535. </file>
  28536. </example>
  28537. */
  28538. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  28539. var NG_REMOVED = '$$NG_REMOVED';
  28540. var ngRepeatMinErr = minErr('ngRepeat');
  28541. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  28542. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  28543. scope[valueIdentifier] = value;
  28544. if (keyIdentifier) scope[keyIdentifier] = key;
  28545. scope.$index = index;
  28546. scope.$first = (index === 0);
  28547. scope.$last = (index === (arrayLength - 1));
  28548. scope.$middle = !(scope.$first || scope.$last);
  28549. // eslint-disable-next-line no-bitwise
  28550. scope.$odd = !(scope.$even = (index & 1) === 0);
  28551. };
  28552. var getBlockStart = function(block) {
  28553. return block.clone[0];
  28554. };
  28555. var getBlockEnd = function(block) {
  28556. return block.clone[block.clone.length - 1];
  28557. };
  28558. return {
  28559. restrict: 'A',
  28560. multiElement: true,
  28561. transclude: 'element',
  28562. priority: 1000,
  28563. terminal: true,
  28564. $$tlb: true,
  28565. compile: function ngRepeatCompile($element, $attr) {
  28566. var expression = $attr.ngRepeat;
  28567. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  28568. 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*$/);
  28569. if (!match) {
  28570. throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
  28571. expression);
  28572. }
  28573. var lhs = match[1];
  28574. var rhs = match[2];
  28575. var aliasAs = match[3];
  28576. var trackByExp = match[4];
  28577. match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
  28578. if (!match) {
  28579. throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
  28580. lhs);
  28581. }
  28582. var valueIdentifier = match[3] || match[1];
  28583. var keyIdentifier = match[2];
  28584. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  28585. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  28586. throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
  28587. aliasAs);
  28588. }
  28589. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  28590. var hashFnLocals = {$id: hashKey};
  28591. if (trackByExp) {
  28592. trackByExpGetter = $parse(trackByExp);
  28593. } else {
  28594. trackByIdArrayFn = function(key, value) {
  28595. return hashKey(value);
  28596. };
  28597. trackByIdObjFn = function(key) {
  28598. return key;
  28599. };
  28600. }
  28601. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  28602. if (trackByExpGetter) {
  28603. trackByIdExpFn = function(key, value, index) {
  28604. // assign key, value, and $index to the locals so that they can be used in hash functions
  28605. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  28606. hashFnLocals[valueIdentifier] = value;
  28607. hashFnLocals.$index = index;
  28608. return trackByExpGetter($scope, hashFnLocals);
  28609. };
  28610. }
  28611. // Store a list of elements from previous run. This is a hash where key is the item from the
  28612. // iterator, and the value is objects with following properties.
  28613. // - scope: bound scope
  28614. // - clone: previous element.
  28615. // - index: position
  28616. //
  28617. // We are using no-proto object so that we don't need to guard against inherited props via
  28618. // hasOwnProperty.
  28619. var lastBlockMap = createMap();
  28620. //watch props
  28621. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  28622. var index, length,
  28623. previousNode = $element[0], // node that cloned nodes should be inserted after
  28624. // initialized to the comment node anchor
  28625. nextNode,
  28626. // Same as lastBlockMap but it has the current state. It will become the
  28627. // lastBlockMap on the next iteration.
  28628. nextBlockMap = createMap(),
  28629. collectionLength,
  28630. key, value, // key/value of iteration
  28631. trackById,
  28632. trackByIdFn,
  28633. collectionKeys,
  28634. block, // last object information {scope, element, id}
  28635. nextBlockOrder,
  28636. elementsToRemove;
  28637. if (aliasAs) {
  28638. $scope[aliasAs] = collection;
  28639. }
  28640. if (isArrayLike(collection)) {
  28641. collectionKeys = collection;
  28642. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  28643. } else {
  28644. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  28645. // if object, extract keys, in enumeration order, unsorted
  28646. collectionKeys = [];
  28647. for (var itemKey in collection) {
  28648. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  28649. collectionKeys.push(itemKey);
  28650. }
  28651. }
  28652. }
  28653. collectionLength = collectionKeys.length;
  28654. nextBlockOrder = new Array(collectionLength);
  28655. // locate existing items
  28656. for (index = 0; index < collectionLength; index++) {
  28657. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28658. value = collection[key];
  28659. trackById = trackByIdFn(key, value, index);
  28660. if (lastBlockMap[trackById]) {
  28661. // found previously seen block
  28662. block = lastBlockMap[trackById];
  28663. delete lastBlockMap[trackById];
  28664. nextBlockMap[trackById] = block;
  28665. nextBlockOrder[index] = block;
  28666. } else if (nextBlockMap[trackById]) {
  28667. // if collision detected. restore lastBlockMap and throw an error
  28668. forEach(nextBlockOrder, function(block) {
  28669. if (block && block.scope) lastBlockMap[block.id] = block;
  28670. });
  28671. throw ngRepeatMinErr('dupes',
  28672. 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
  28673. expression, trackById, value);
  28674. } else {
  28675. // new never before seen block
  28676. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  28677. nextBlockMap[trackById] = true;
  28678. }
  28679. }
  28680. // remove leftover items
  28681. for (var blockKey in lastBlockMap) {
  28682. block = lastBlockMap[blockKey];
  28683. elementsToRemove = getBlockNodes(block.clone);
  28684. $animate.leave(elementsToRemove);
  28685. if (elementsToRemove[0].parentNode) {
  28686. // if the element was not removed yet because of pending animation, mark it as deleted
  28687. // so that we can ignore it later
  28688. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  28689. elementsToRemove[index][NG_REMOVED] = true;
  28690. }
  28691. }
  28692. block.scope.$destroy();
  28693. }
  28694. // we are not using forEach for perf reasons (trying to avoid #call)
  28695. for (index = 0; index < collectionLength; index++) {
  28696. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28697. value = collection[key];
  28698. block = nextBlockOrder[index];
  28699. if (block.scope) {
  28700. // if we have already seen this object, then we need to reuse the
  28701. // associated scope/element
  28702. nextNode = previousNode;
  28703. // skip nodes that are already pending removal via leave animation
  28704. do {
  28705. nextNode = nextNode.nextSibling;
  28706. } while (nextNode && nextNode[NG_REMOVED]);
  28707. if (getBlockStart(block) !== nextNode) {
  28708. // existing item which got moved
  28709. $animate.move(getBlockNodes(block.clone), null, previousNode);
  28710. }
  28711. previousNode = getBlockEnd(block);
  28712. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28713. } else {
  28714. // new item which we don't know about
  28715. $transclude(function ngRepeatTransclude(clone, scope) {
  28716. block.scope = scope;
  28717. // http://jsperf.com/clone-vs-createcomment
  28718. var endNode = ngRepeatEndComment.cloneNode(false);
  28719. clone[clone.length++] = endNode;
  28720. $animate.enter(clone, null, previousNode);
  28721. previousNode = endNode;
  28722. // Note: We only need the first/last node of the cloned nodes.
  28723. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  28724. // by a directive with templateUrl when its template arrives.
  28725. block.clone = clone;
  28726. nextBlockMap[block.id] = block;
  28727. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28728. });
  28729. }
  28730. }
  28731. lastBlockMap = nextBlockMap;
  28732. });
  28733. };
  28734. }
  28735. };
  28736. }];
  28737. var NG_HIDE_CLASS = 'ng-hide';
  28738. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  28739. /**
  28740. * @ngdoc directive
  28741. * @name ngShow
  28742. * @multiElement
  28743. *
  28744. * @description
  28745. * The `ngShow` directive shows or hides the given HTML element based on the expression provided to
  28746. * the `ngShow` attribute.
  28747. *
  28748. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  28749. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  28750. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  28751. * {@link ng.directive:ngCsp ngCsp}).
  28752. *
  28753. * ```html
  28754. * <!-- when $scope.myValue is truthy (element is visible) -->
  28755. * <div ng-show="myValue"></div>
  28756. *
  28757. * <!-- when $scope.myValue is falsy (element is hidden) -->
  28758. * <div ng-show="myValue" class="ng-hide"></div>
  28759. * ```
  28760. *
  28761. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added
  28762. * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide`
  28763. * CSS class is removed from the element causing the element not to appear hidden.
  28764. *
  28765. * ## Why is `!important` used?
  28766. *
  28767. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  28768. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  28769. * simple as changing the display style on a HTML list item would make hidden elements appear
  28770. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  28771. *
  28772. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  28773. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  28774. * developer chooses to override the styling to change how to hide an element then it is just a
  28775. * matter of using `!important` in their own CSS code.
  28776. *
  28777. * ### Overriding `.ng-hide`
  28778. *
  28779. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  28780. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  28781. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  28782. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  28783. *
  28784. * ```css
  28785. * .ng-hide:not(.ng-hide-animate) {
  28786. * /&#42; These are just alternative ways of hiding an element &#42;/
  28787. * display: block!important;
  28788. * position: absolute;
  28789. * top: -9999px;
  28790. * left: -9999px;
  28791. * }
  28792. * ```
  28793. *
  28794. * By default you don't need to override anything in CSS and the animations will work around the
  28795. * display style.
  28796. *
  28797. * ## A note about animations with `ngShow`
  28798. *
  28799. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  28800. * directive expression is true and false. This system works like the animation system present with
  28801. * `ngClass` except that you must also include the `!important` flag to override the display
  28802. * property so that the elements are not actually hidden during the animation.
  28803. *
  28804. * ```css
  28805. * /&#42; A working example can be found at the bottom of this page. &#42;/
  28806. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28807. * transition: all 0.5s linear;
  28808. * }
  28809. *
  28810. * .my-element.ng-hide-add { ... }
  28811. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  28812. * .my-element.ng-hide-remove { ... }
  28813. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  28814. * ```
  28815. *
  28816. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  28817. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  28818. *
  28819. * @animations
  28820. * | Animation | Occurs |
  28821. * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
  28822. * | {@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. |
  28823. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. |
  28824. *
  28825. * @element ANY
  28826. * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the
  28827. * element is shown/hidden respectively.
  28828. *
  28829. * @example
  28830. * A simple example, animating the element's opacity:
  28831. *
  28832. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-simple">
  28833. <file name="index.html">
  28834. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  28835. <div class="check-element animate-show-hide" ng-show="checked">
  28836. I show up when your checkbox is checked.
  28837. </div>
  28838. </file>
  28839. <file name="animations.css">
  28840. .animate-show-hide.ng-hide {
  28841. opacity: 0;
  28842. }
  28843. .animate-show-hide.ng-hide-add,
  28844. .animate-show-hide.ng-hide-remove {
  28845. transition: all linear 0.5s;
  28846. }
  28847. .check-element {
  28848. border: 1px solid black;
  28849. opacity: 1;
  28850. padding: 10px;
  28851. }
  28852. </file>
  28853. <file name="protractor.js" type="protractor">
  28854. it('should check ngShow', function() {
  28855. var checkbox = element(by.model('checked'));
  28856. var checkElem = element(by.css('.check-element'));
  28857. expect(checkElem.isDisplayed()).toBe(false);
  28858. checkbox.click();
  28859. expect(checkElem.isDisplayed()).toBe(true);
  28860. });
  28861. </file>
  28862. </example>
  28863. *
  28864. * <hr />
  28865. * @example
  28866. * A more complex example, featuring different show/hide animations:
  28867. *
  28868. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-complex">
  28869. <file name="index.html">
  28870. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  28871. <div class="check-element funky-show-hide" ng-show="checked">
  28872. I show up when your checkbox is checked.
  28873. </div>
  28874. </file>
  28875. <file name="animations.css">
  28876. body {
  28877. overflow: hidden;
  28878. perspective: 1000px;
  28879. }
  28880. .funky-show-hide.ng-hide-add {
  28881. transform: rotateZ(0);
  28882. transform-origin: right;
  28883. transition: all 0.5s ease-in-out;
  28884. }
  28885. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  28886. transform: rotateZ(-135deg);
  28887. }
  28888. .funky-show-hide.ng-hide-remove {
  28889. transform: rotateY(90deg);
  28890. transform-origin: left;
  28891. transition: all 0.5s ease;
  28892. }
  28893. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  28894. transform: rotateY(0);
  28895. }
  28896. .check-element {
  28897. border: 1px solid black;
  28898. opacity: 1;
  28899. padding: 10px;
  28900. }
  28901. </file>
  28902. <file name="protractor.js" type="protractor">
  28903. it('should check ngShow', function() {
  28904. var checkbox = element(by.model('checked'));
  28905. var checkElem = element(by.css('.check-element'));
  28906. expect(checkElem.isDisplayed()).toBe(false);
  28907. checkbox.click();
  28908. expect(checkElem.isDisplayed()).toBe(true);
  28909. });
  28910. </file>
  28911. </example>
  28912. */
  28913. var ngShowDirective = ['$animate', function($animate) {
  28914. return {
  28915. restrict: 'A',
  28916. multiElement: true,
  28917. link: function(scope, element, attr) {
  28918. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  28919. // we're adding a temporary, animation-specific class for ng-hide since this way
  28920. // we can control when the element is actually displayed on screen without having
  28921. // to have a global/greedy CSS selector that breaks when other animations are run.
  28922. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  28923. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  28924. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  28925. });
  28926. });
  28927. }
  28928. };
  28929. }];
  28930. /**
  28931. * @ngdoc directive
  28932. * @name ngHide
  28933. * @multiElement
  28934. *
  28935. * @description
  28936. * The `ngHide` directive shows or hides the given HTML element based on the expression provided to
  28937. * the `ngHide` attribute.
  28938. *
  28939. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  28940. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  28941. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  28942. * {@link ng.directive:ngCsp ngCsp}).
  28943. *
  28944. * ```html
  28945. * <!-- when $scope.myValue is truthy (element is hidden) -->
  28946. * <div ng-hide="myValue" class="ng-hide"></div>
  28947. *
  28948. * <!-- when $scope.myValue is falsy (element is visible) -->
  28949. * <div ng-hide="myValue"></div>
  28950. * ```
  28951. *
  28952. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added
  28953. * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide`
  28954. * CSS class is removed from the element causing the element not to appear hidden.
  28955. *
  28956. * ## Why is `!important` used?
  28957. *
  28958. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  28959. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  28960. * simple as changing the display style on a HTML list item would make hidden elements appear
  28961. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  28962. *
  28963. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  28964. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  28965. * developer chooses to override the styling to change how to hide an element then it is just a
  28966. * matter of using `!important` in their own CSS code.
  28967. *
  28968. * ### Overriding `.ng-hide`
  28969. *
  28970. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  28971. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  28972. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  28973. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  28974. *
  28975. * ```css
  28976. * .ng-hide:not(.ng-hide-animate) {
  28977. * /&#42; These are just alternative ways of hiding an element &#42;/
  28978. * display: block!important;
  28979. * position: absolute;
  28980. * top: -9999px;
  28981. * left: -9999px;
  28982. * }
  28983. * ```
  28984. *
  28985. * By default you don't need to override in CSS anything and the animations will work around the
  28986. * display style.
  28987. *
  28988. * ## A note about animations with `ngHide`
  28989. *
  28990. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  28991. * directive expression is true and false. This system works like the animation system present with
  28992. * `ngClass` except that you must also include the `!important` flag to override the display
  28993. * property so that the elements are not actually hidden during the animation.
  28994. *
  28995. * ```css
  28996. * /&#42; A working example can be found at the bottom of this page. &#42;/
  28997. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28998. * transition: all 0.5s linear;
  28999. * }
  29000. *
  29001. * .my-element.ng-hide-add { ... }
  29002. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  29003. * .my-element.ng-hide-remove { ... }
  29004. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  29005. * ```
  29006. *
  29007. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  29008. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  29009. *
  29010. * @animations
  29011. * | Animation | Occurs |
  29012. * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------|
  29013. * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. |
  29014. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. |
  29015. *
  29016. *
  29017. * @element ANY
  29018. * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the
  29019. * element is hidden/shown respectively.
  29020. *
  29021. * @example
  29022. * A simple example, animating the element's opacity:
  29023. *
  29024. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-simple">
  29025. <file name="index.html">
  29026. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  29027. <div class="check-element animate-show-hide" ng-hide="checked">
  29028. I hide when your checkbox is checked.
  29029. </div>
  29030. </file>
  29031. <file name="animations.css">
  29032. .animate-show-hide.ng-hide {
  29033. opacity: 0;
  29034. }
  29035. .animate-show-hide.ng-hide-add,
  29036. .animate-show-hide.ng-hide-remove {
  29037. transition: all linear 0.5s;
  29038. }
  29039. .check-element {
  29040. border: 1px solid black;
  29041. opacity: 1;
  29042. padding: 10px;
  29043. }
  29044. </file>
  29045. <file name="protractor.js" type="protractor">
  29046. it('should check ngHide', function() {
  29047. var checkbox = element(by.model('checked'));
  29048. var checkElem = element(by.css('.check-element'));
  29049. expect(checkElem.isDisplayed()).toBe(true);
  29050. checkbox.click();
  29051. expect(checkElem.isDisplayed()).toBe(false);
  29052. });
  29053. </file>
  29054. </example>
  29055. *
  29056. * <hr />
  29057. * @example
  29058. * A more complex example, featuring different show/hide animations:
  29059. *
  29060. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-complex">
  29061. <file name="index.html">
  29062. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  29063. <div class="check-element funky-show-hide" ng-hide="checked">
  29064. I hide when your checkbox is checked.
  29065. </div>
  29066. </file>
  29067. <file name="animations.css">
  29068. body {
  29069. overflow: hidden;
  29070. perspective: 1000px;
  29071. }
  29072. .funky-show-hide.ng-hide-add {
  29073. transform: rotateZ(0);
  29074. transform-origin: right;
  29075. transition: all 0.5s ease-in-out;
  29076. }
  29077. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  29078. transform: rotateZ(-135deg);
  29079. }
  29080. .funky-show-hide.ng-hide-remove {
  29081. transform: rotateY(90deg);
  29082. transform-origin: left;
  29083. transition: all 0.5s ease;
  29084. }
  29085. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  29086. transform: rotateY(0);
  29087. }
  29088. .check-element {
  29089. border: 1px solid black;
  29090. opacity: 1;
  29091. padding: 10px;
  29092. }
  29093. </file>
  29094. <file name="protractor.js" type="protractor">
  29095. it('should check ngHide', function() {
  29096. var checkbox = element(by.model('checked'));
  29097. var checkElem = element(by.css('.check-element'));
  29098. expect(checkElem.isDisplayed()).toBe(true);
  29099. checkbox.click();
  29100. expect(checkElem.isDisplayed()).toBe(false);
  29101. });
  29102. </file>
  29103. </example>
  29104. */
  29105. var ngHideDirective = ['$animate', function($animate) {
  29106. return {
  29107. restrict: 'A',
  29108. multiElement: true,
  29109. link: function(scope, element, attr) {
  29110. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  29111. // The comment inside of the ngShowDirective explains why we add and
  29112. // remove a temporary class for the show/hide animation
  29113. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  29114. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  29115. });
  29116. });
  29117. }
  29118. };
  29119. }];
  29120. /**
  29121. * @ngdoc directive
  29122. * @name ngStyle
  29123. * @restrict AC
  29124. *
  29125. * @description
  29126. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  29127. *
  29128. * @knownIssue
  29129. * You should not use {@link guide/interpolation interpolation} in the value of the `style`
  29130. * attribute, when using the `ngStyle` directive on the same element.
  29131. * See {@link guide/interpolation#known-issues here} for more info.
  29132. *
  29133. * @element ANY
  29134. * @param {expression} ngStyle
  29135. *
  29136. * {@link guide/expression Expression} which evals to an
  29137. * object whose keys are CSS style names and values are corresponding values for those CSS
  29138. * keys.
  29139. *
  29140. * Since some CSS style names are not valid keys for an object, they must be quoted.
  29141. * See the 'background-color' style in the example below.
  29142. *
  29143. * @example
  29144. <example name="ng-style">
  29145. <file name="index.html">
  29146. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  29147. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  29148. <input type="button" value="clear" ng-click="myStyle={}">
  29149. <br/>
  29150. <span ng-style="myStyle">Sample Text</span>
  29151. <pre>myStyle={{myStyle}}</pre>
  29152. </file>
  29153. <file name="style.css">
  29154. span {
  29155. color: black;
  29156. }
  29157. </file>
  29158. <file name="protractor.js" type="protractor">
  29159. var colorSpan = element(by.css('span'));
  29160. it('should check ng-style', function() {
  29161. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  29162. element(by.css('input[value=\'set color\']')).click();
  29163. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  29164. element(by.css('input[value=clear]')).click();
  29165. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  29166. });
  29167. </file>
  29168. </example>
  29169. */
  29170. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  29171. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  29172. if (oldStyles && (newStyles !== oldStyles)) {
  29173. forEach(oldStyles, function(val, style) { element.css(style, '');});
  29174. }
  29175. if (newStyles) element.css(newStyles);
  29176. }, true);
  29177. });
  29178. /**
  29179. * @ngdoc directive
  29180. * @name ngSwitch
  29181. * @restrict EA
  29182. *
  29183. * @description
  29184. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  29185. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  29186. * as specified in the template.
  29187. *
  29188. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  29189. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  29190. * matches the value obtained from the evaluated expression. In other words, you define a container element
  29191. * (where you place the directive), place an expression on the **`on="..."` attribute**
  29192. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  29193. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  29194. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  29195. * attribute is displayed.
  29196. *
  29197. * <div class="alert alert-info">
  29198. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  29199. * as literal string values to match against.
  29200. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  29201. * value of the expression `$scope.someVal`.
  29202. * </div>
  29203. * @animations
  29204. * | Animation | Occurs |
  29205. * |----------------------------------|-------------------------------------|
  29206. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  29207. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  29208. *
  29209. * @usage
  29210. *
  29211. * ```
  29212. * <ANY ng-switch="expression">
  29213. * <ANY ng-switch-when="matchValue1">...</ANY>
  29214. * <ANY ng-switch-when="matchValue2">...</ANY>
  29215. * <ANY ng-switch-default>...</ANY>
  29216. * </ANY>
  29217. * ```
  29218. *
  29219. *
  29220. * @scope
  29221. * @priority 1200
  29222. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  29223. * On child elements add:
  29224. *
  29225. * * `ngSwitchWhen`: the case statement to match against. If match then this
  29226. * case will be displayed. If the same match appears multiple times, all the
  29227. * elements will be displayed. It is possible to associate multiple values to
  29228. * the same `ngSwitchWhen` by defining the optional attribute
  29229. * `ngSwitchWhenSeparator`. The separator will be used to split the value of
  29230. * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
  29231. * if any of the `ngSwitch` evaluates to any of these tokens.
  29232. * * `ngSwitchDefault`: the default case when no other case match. If there
  29233. * are multiple default cases, all of them will be displayed when no other
  29234. * case match.
  29235. *
  29236. *
  29237. * @example
  29238. <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
  29239. <file name="index.html">
  29240. <div ng-controller="ExampleController">
  29241. <select ng-model="selection" ng-options="item for item in items">
  29242. </select>
  29243. <code>selection={{selection}}</code>
  29244. <hr/>
  29245. <div class="animate-switch-container"
  29246. ng-switch on="selection">
  29247. <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
  29248. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  29249. <div class="animate-switch" ng-switch-default>default</div>
  29250. </div>
  29251. </div>
  29252. </file>
  29253. <file name="script.js">
  29254. angular.module('switchExample', ['ngAnimate'])
  29255. .controller('ExampleController', ['$scope', function($scope) {
  29256. $scope.items = ['settings', 'home', 'options', 'other'];
  29257. $scope.selection = $scope.items[0];
  29258. }]);
  29259. </file>
  29260. <file name="animations.css">
  29261. .animate-switch-container {
  29262. position:relative;
  29263. background:white;
  29264. border:1px solid black;
  29265. height:40px;
  29266. overflow:hidden;
  29267. }
  29268. .animate-switch {
  29269. padding:10px;
  29270. }
  29271. .animate-switch.ng-animate {
  29272. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  29273. position:absolute;
  29274. top:0;
  29275. left:0;
  29276. right:0;
  29277. bottom:0;
  29278. }
  29279. .animate-switch.ng-leave.ng-leave-active,
  29280. .animate-switch.ng-enter {
  29281. top:-50px;
  29282. }
  29283. .animate-switch.ng-leave,
  29284. .animate-switch.ng-enter.ng-enter-active {
  29285. top:0;
  29286. }
  29287. </file>
  29288. <file name="protractor.js" type="protractor">
  29289. var switchElem = element(by.css('[ng-switch]'));
  29290. var select = element(by.model('selection'));
  29291. it('should start in settings', function() {
  29292. expect(switchElem.getText()).toMatch(/Settings Div/);
  29293. });
  29294. it('should change to home', function() {
  29295. select.all(by.css('option')).get(1).click();
  29296. expect(switchElem.getText()).toMatch(/Home Span/);
  29297. });
  29298. it('should change to settings via "options"', function() {
  29299. select.all(by.css('option')).get(2).click();
  29300. expect(switchElem.getText()).toMatch(/Settings Div/);
  29301. });
  29302. it('should select default', function() {
  29303. select.all(by.css('option')).get(3).click();
  29304. expect(switchElem.getText()).toMatch(/default/);
  29305. });
  29306. </file>
  29307. </example>
  29308. */
  29309. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  29310. return {
  29311. require: 'ngSwitch',
  29312. // asks for $scope to fool the BC controller module
  29313. controller: ['$scope', function NgSwitchController() {
  29314. this.cases = {};
  29315. }],
  29316. link: function(scope, element, attr, ngSwitchController) {
  29317. var watchExpr = attr.ngSwitch || attr.on,
  29318. selectedTranscludes = [],
  29319. selectedElements = [],
  29320. previousLeaveAnimations = [],
  29321. selectedScopes = [];
  29322. var spliceFactory = function(array, index) {
  29323. return function(response) {
  29324. if (response !== false) array.splice(index, 1);
  29325. };
  29326. };
  29327. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  29328. var i, ii;
  29329. // Start with the last, in case the array is modified during the loop
  29330. while (previousLeaveAnimations.length) {
  29331. $animate.cancel(previousLeaveAnimations.pop());
  29332. }
  29333. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  29334. var selected = getBlockNodes(selectedElements[i].clone);
  29335. selectedScopes[i].$destroy();
  29336. var runner = previousLeaveAnimations[i] = $animate.leave(selected);
  29337. runner.done(spliceFactory(previousLeaveAnimations, i));
  29338. }
  29339. selectedElements.length = 0;
  29340. selectedScopes.length = 0;
  29341. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  29342. forEach(selectedTranscludes, function(selectedTransclude) {
  29343. selectedTransclude.transclude(function(caseElement, selectedScope) {
  29344. selectedScopes.push(selectedScope);
  29345. var anchor = selectedTransclude.element;
  29346. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  29347. var block = { clone: caseElement };
  29348. selectedElements.push(block);
  29349. $animate.enter(caseElement, anchor.parent(), anchor);
  29350. });
  29351. });
  29352. }
  29353. });
  29354. }
  29355. };
  29356. }];
  29357. var ngSwitchWhenDirective = ngDirective({
  29358. transclude: 'element',
  29359. priority: 1200,
  29360. require: '^ngSwitch',
  29361. multiElement: true,
  29362. link: function(scope, element, attrs, ctrl, $transclude) {
  29363. var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
  29364. // Filter duplicate cases
  29365. function(element, index, array) { return array[index - 1] !== element; }
  29366. );
  29367. forEach(cases, function(whenCase) {
  29368. ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
  29369. ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
  29370. });
  29371. }
  29372. });
  29373. var ngSwitchDefaultDirective = ngDirective({
  29374. transclude: 'element',
  29375. priority: 1200,
  29376. require: '^ngSwitch',
  29377. multiElement: true,
  29378. link: function(scope, element, attr, ctrl, $transclude) {
  29379. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  29380. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  29381. }
  29382. });
  29383. /**
  29384. * @ngdoc directive
  29385. * @name ngTransclude
  29386. * @restrict EAC
  29387. *
  29388. * @description
  29389. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  29390. *
  29391. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  29392. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  29393. *
  29394. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  29395. * content of this element will be removed before the transcluded content is inserted.
  29396. * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback
  29397. * content in the case that no transcluded content is provided.
  29398. *
  29399. * @element ANY
  29400. *
  29401. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  29402. * or its value is the same as the name of the attribute then the default slot is used.
  29403. *
  29404. * @example
  29405. * ### Basic transclusion
  29406. * This example demonstrates basic transclusion of content into a component directive.
  29407. * <example name="simpleTranscludeExample" module="transcludeExample">
  29408. * <file name="index.html">
  29409. * <script>
  29410. * angular.module('transcludeExample', [])
  29411. * .directive('pane', function(){
  29412. * return {
  29413. * restrict: 'E',
  29414. * transclude: true,
  29415. * scope: { title:'@' },
  29416. * template: '<div style="border: 1px solid black;">' +
  29417. * '<div style="background-color: gray">{{title}}</div>' +
  29418. * '<ng-transclude></ng-transclude>' +
  29419. * '</div>'
  29420. * };
  29421. * })
  29422. * .controller('ExampleController', ['$scope', function($scope) {
  29423. * $scope.title = 'Lorem Ipsum';
  29424. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  29425. * }]);
  29426. * </script>
  29427. * <div ng-controller="ExampleController">
  29428. * <input ng-model="title" aria-label="title"> <br/>
  29429. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  29430. * <pane title="{{title}}"><span>{{text}}</span></pane>
  29431. * </div>
  29432. * </file>
  29433. * <file name="protractor.js" type="protractor">
  29434. * it('should have transcluded', function() {
  29435. * var titleElement = element(by.model('title'));
  29436. * titleElement.clear();
  29437. * titleElement.sendKeys('TITLE');
  29438. * var textElement = element(by.model('text'));
  29439. * textElement.clear();
  29440. * textElement.sendKeys('TEXT');
  29441. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  29442. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  29443. * });
  29444. * </file>
  29445. * </example>
  29446. *
  29447. * @example
  29448. * ### Transclude fallback content
  29449. * This example shows how to use `NgTransclude` with fallback content, that
  29450. * is displayed if no transcluded content is provided.
  29451. *
  29452. * <example module="transcludeFallbackContentExample" name="ng-transclude">
  29453. * <file name="index.html">
  29454. * <script>
  29455. * angular.module('transcludeFallbackContentExample', [])
  29456. * .directive('myButton', function(){
  29457. * return {
  29458. * restrict: 'E',
  29459. * transclude: true,
  29460. * scope: true,
  29461. * template: '<button style="cursor: pointer;">' +
  29462. * '<ng-transclude>' +
  29463. * '<b style="color: red;">Button1</b>' +
  29464. * '</ng-transclude>' +
  29465. * '</button>'
  29466. * };
  29467. * });
  29468. * </script>
  29469. * <!-- fallback button content -->
  29470. * <my-button id="fallback"></my-button>
  29471. * <!-- modified button content -->
  29472. * <my-button id="modified">
  29473. * <i style="color: green;">Button2</i>
  29474. * </my-button>
  29475. * </file>
  29476. * <file name="protractor.js" type="protractor">
  29477. * it('should have different transclude element content', function() {
  29478. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  29479. * expect(element(by.id('modified')).getText()).toBe('Button2');
  29480. * });
  29481. * </file>
  29482. * </example>
  29483. *
  29484. * @example
  29485. * ### Multi-slot transclusion
  29486. * This example demonstrates using multi-slot transclusion in a component directive.
  29487. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  29488. * <file name="index.html">
  29489. * <style>
  29490. * .title, .footer {
  29491. * background-color: gray
  29492. * }
  29493. * </style>
  29494. * <div ng-controller="ExampleController">
  29495. * <input ng-model="title" aria-label="title"> <br/>
  29496. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  29497. * <pane>
  29498. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  29499. * <pane-body><p>{{text}}</p></pane-body>
  29500. * </pane>
  29501. * </div>
  29502. * </file>
  29503. * <file name="app.js">
  29504. * angular.module('multiSlotTranscludeExample', [])
  29505. * .directive('pane', function() {
  29506. * return {
  29507. * restrict: 'E',
  29508. * transclude: {
  29509. * 'title': '?paneTitle',
  29510. * 'body': 'paneBody',
  29511. * 'footer': '?paneFooter'
  29512. * },
  29513. * template: '<div style="border: 1px solid black;">' +
  29514. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  29515. * '<div ng-transclude="body"></div>' +
  29516. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  29517. * '</div>'
  29518. * };
  29519. * })
  29520. * .controller('ExampleController', ['$scope', function($scope) {
  29521. * $scope.title = 'Lorem Ipsum';
  29522. * $scope.link = 'https://google.com';
  29523. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  29524. * }]);
  29525. * </file>
  29526. * <file name="protractor.js" type="protractor">
  29527. * it('should have transcluded the title and the body', function() {
  29528. * var titleElement = element(by.model('title'));
  29529. * titleElement.clear();
  29530. * titleElement.sendKeys('TITLE');
  29531. * var textElement = element(by.model('text'));
  29532. * textElement.clear();
  29533. * textElement.sendKeys('TEXT');
  29534. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  29535. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  29536. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  29537. * });
  29538. * </file>
  29539. * </example>
  29540. */
  29541. var ngTranscludeMinErr = minErr('ngTransclude');
  29542. var ngTranscludeDirective = ['$compile', function($compile) {
  29543. return {
  29544. restrict: 'EAC',
  29545. terminal: true,
  29546. compile: function ngTranscludeCompile(tElement) {
  29547. // Remove and cache any original content to act as a fallback
  29548. var fallbackLinkFn = $compile(tElement.contents());
  29549. tElement.empty();
  29550. return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
  29551. if (!$transclude) {
  29552. throw ngTranscludeMinErr('orphan',
  29553. 'Illegal use of ngTransclude directive in the template! ' +
  29554. 'No parent directive that requires a transclusion found. ' +
  29555. 'Element: {0}',
  29556. startingTag($element));
  29557. }
  29558. // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
  29559. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  29560. $attrs.ngTransclude = '';
  29561. }
  29562. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  29563. // If the slot is required and no transclusion content is provided then this call will throw an error
  29564. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  29565. // If the slot is optional and no transclusion content is provided then use the fallback content
  29566. if (slotName && !$transclude.isSlotFilled(slotName)) {
  29567. useFallbackContent();
  29568. }
  29569. function ngTranscludeCloneAttachFn(clone, transcludedScope) {
  29570. if (clone.length && notWhitespace(clone)) {
  29571. $element.append(clone);
  29572. } else {
  29573. useFallbackContent();
  29574. // There is nothing linked against the transcluded scope since no content was available,
  29575. // so it should be safe to clean up the generated scope.
  29576. transcludedScope.$destroy();
  29577. }
  29578. }
  29579. function useFallbackContent() {
  29580. // Since this is the fallback content rather than the transcluded content,
  29581. // we link against the scope of this directive rather than the transcluded scope
  29582. fallbackLinkFn($scope, function(clone) {
  29583. $element.append(clone);
  29584. });
  29585. }
  29586. function notWhitespace(nodes) {
  29587. for (var i = 0, ii = nodes.length; i < ii; i++) {
  29588. var node = nodes[i];
  29589. if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) {
  29590. return true;
  29591. }
  29592. }
  29593. }
  29594. };
  29595. }
  29596. };
  29597. }];
  29598. /**
  29599. * @ngdoc directive
  29600. * @name script
  29601. * @restrict E
  29602. *
  29603. * @description
  29604. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  29605. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  29606. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  29607. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  29608. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  29609. *
  29610. * @param {string} type Must be set to `'text/ng-template'`.
  29611. * @param {string} id Cache name of the template.
  29612. *
  29613. * @example
  29614. <example name="script-tag">
  29615. <file name="index.html">
  29616. <script type="text/ng-template" id="/tpl.html">
  29617. Content of the template.
  29618. </script>
  29619. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  29620. <div id="tpl-content" ng-include src="currentTpl"></div>
  29621. </file>
  29622. <file name="protractor.js" type="protractor">
  29623. it('should load template defined inside script tag', function() {
  29624. element(by.css('#tpl-link')).click();
  29625. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  29626. });
  29627. </file>
  29628. </example>
  29629. */
  29630. var scriptDirective = ['$templateCache', function($templateCache) {
  29631. return {
  29632. restrict: 'E',
  29633. terminal: true,
  29634. compile: function(element, attr) {
  29635. if (attr.type === 'text/ng-template') {
  29636. var templateUrl = attr.id,
  29637. text = element[0].text;
  29638. $templateCache.put(templateUrl, text);
  29639. }
  29640. }
  29641. };
  29642. }];
  29643. /* exported selectDirective, optionDirective */
  29644. var noopNgModelController = { $setViewValue: noop, $render: noop };
  29645. function setOptionSelectedStatus(optionEl, value) {
  29646. optionEl.prop('selected', value);
  29647. /**
  29648. * When unselecting an option, setting the property to null / false should be enough
  29649. * However, screenreaders might react to the selected attribute instead, see
  29650. * https://github.com/angular/angular.js/issues/14419
  29651. * Note: "selected" is a boolean attr and will be removed when the "value" arg in attr() is false
  29652. * or null
  29653. */
  29654. optionEl.attr('selected', value);
  29655. }
  29656. /**
  29657. * @ngdoc type
  29658. * @name select.SelectController
  29659. *
  29660. * @description
  29661. * The controller for the {@link ng.select select} directive. The controller exposes
  29662. * a few utility methods that can be used to augment the behavior of a regular or an
  29663. * {@link ng.ngOptions ngOptions} select element.
  29664. *
  29665. * @example
  29666. * ### Set a custom error when the unknown option is selected
  29667. *
  29668. * This example sets a custom error "unknownValue" on the ngModelController
  29669. * when the select element's unknown option is selected, i.e. when the model is set to a value
  29670. * that is not matched by any option.
  29671. *
  29672. * <example name="select-unknown-value-error" module="staticSelect">
  29673. * <file name="index.html">
  29674. * <div ng-controller="ExampleController">
  29675. * <form name="myForm">
  29676. * <label for="testSelect"> Single select: </label><br>
  29677. * <select name="testSelect" ng-model="selected" unknown-value-error>
  29678. * <option value="option-1">Option 1</option>
  29679. * <option value="option-2">Option 2</option>
  29680. * </select><br>
  29681. * <span ng-if="myForm.testSelect.$error.unknownValue">Error: The current model doesn't match any option</span>
  29682. *
  29683. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  29684. * </form>
  29685. * </div>
  29686. * </file>
  29687. * <file name="app.js">
  29688. * angular.module('staticSelect', [])
  29689. * .controller('ExampleController', ['$scope', function($scope) {
  29690. * $scope.selected = null;
  29691. *
  29692. * $scope.forceUnknownOption = function() {
  29693. * $scope.selected = 'nonsense';
  29694. * };
  29695. * }])
  29696. * .directive('unknownValueError', function() {
  29697. * return {
  29698. * require: ['ngModel', 'select'],
  29699. * link: function(scope, element, attrs, ctrls) {
  29700. * var ngModelCtrl = ctrls[0];
  29701. * var selectCtrl = ctrls[1];
  29702. *
  29703. * ngModelCtrl.$validators.unknownValue = function(modelValue, viewValue) {
  29704. * if (selectCtrl.$isUnknownOptionSelected()) {
  29705. * return false;
  29706. * }
  29707. *
  29708. * return true;
  29709. * };
  29710. * }
  29711. *
  29712. * };
  29713. * });
  29714. * </file>
  29715. *</example>
  29716. *
  29717. *
  29718. * @example
  29719. * ### Set the "required" error when the unknown option is selected.
  29720. *
  29721. * By default, the "required" error on the ngModelController is only set on a required select
  29722. * when the empty option is selected. This example adds a custom directive that also sets the
  29723. * error when the unknown option is selected.
  29724. *
  29725. * <example name="select-unknown-value-required" module="staticSelect">
  29726. * <file name="index.html">
  29727. * <div ng-controller="ExampleController">
  29728. * <form name="myForm">
  29729. * <label for="testSelect"> Select: </label><br>
  29730. * <select name="testSelect" ng-model="selected" unknown-value-required>
  29731. * <option value="option-1">Option 1</option>
  29732. * <option value="option-2">Option 2</option>
  29733. * </select><br>
  29734. * <span ng-if="myForm.testSelect.$error.required">Error: Please select a value</span><br>
  29735. *
  29736. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  29737. * </form>
  29738. * </div>
  29739. * </file>
  29740. * <file name="app.js">
  29741. * angular.module('staticSelect', [])
  29742. * .controller('ExampleController', ['$scope', function($scope) {
  29743. * $scope.selected = null;
  29744. *
  29745. * $scope.forceUnknownOption = function() {
  29746. * $scope.selected = 'nonsense';
  29747. * };
  29748. * }])
  29749. * .directive('unknownValueRequired', function() {
  29750. * return {
  29751. * priority: 1, // This directive must run after the required directive has added its validator
  29752. * require: ['ngModel', 'select'],
  29753. * link: function(scope, element, attrs, ctrls) {
  29754. * var ngModelCtrl = ctrls[0];
  29755. * var selectCtrl = ctrls[1];
  29756. *
  29757. * var originalRequiredValidator = ngModelCtrl.$validators.required;
  29758. *
  29759. * ngModelCtrl.$validators.required = function() {
  29760. * if (attrs.required && selectCtrl.$isUnknownOptionSelected()) {
  29761. * return false;
  29762. * }
  29763. *
  29764. * return originalRequiredValidator.apply(this, arguments);
  29765. * };
  29766. * }
  29767. * };
  29768. * });
  29769. * </file>
  29770. *</example>
  29771. *
  29772. *
  29773. */
  29774. var SelectController =
  29775. ['$element', '$scope', /** @this */ function($element, $scope) {
  29776. var self = this,
  29777. optionsMap = new NgMap();
  29778. self.selectValueMap = {}; // Keys are the hashed values, values the original values
  29779. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  29780. self.ngModelCtrl = noopNgModelController;
  29781. self.multiple = false;
  29782. // The "unknown" option is one that is prepended to the list if the viewValue
  29783. // does not match any of the options. When it is rendered the value of the unknown
  29784. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  29785. //
  29786. // Support: IE 9 only
  29787. // We can't just jqLite('<option>') since jqLite is not smart enough
  29788. // to create it in <select> and IE barfs otherwise.
  29789. self.unknownOption = jqLite(window.document.createElement('option'));
  29790. // The empty option is an option with the value '' that the application developer can
  29791. // provide inside the select. It is always selectable and indicates that a "null" selection has
  29792. // been made by the user.
  29793. // If the select has an empty option, and the model of the select is set to "undefined" or "null",
  29794. // the empty option is selected.
  29795. // If the model is set to a different unmatched value, the unknown option is rendered and
  29796. // selected, i.e both are present, because a "null" selection and an unknown value are different.
  29797. self.hasEmptyOption = false;
  29798. self.emptyOption = undefined;
  29799. self.renderUnknownOption = function(val) {
  29800. var unknownVal = self.generateUnknownOptionValue(val);
  29801. self.unknownOption.val(unknownVal);
  29802. $element.prepend(self.unknownOption);
  29803. setOptionSelectedStatus(self.unknownOption, true);
  29804. $element.val(unknownVal);
  29805. };
  29806. self.updateUnknownOption = function(val) {
  29807. var unknownVal = self.generateUnknownOptionValue(val);
  29808. self.unknownOption.val(unknownVal);
  29809. setOptionSelectedStatus(self.unknownOption, true);
  29810. $element.val(unknownVal);
  29811. };
  29812. self.generateUnknownOptionValue = function(val) {
  29813. return '? ' + hashKey(val) + ' ?';
  29814. };
  29815. self.removeUnknownOption = function() {
  29816. if (self.unknownOption.parent()) self.unknownOption.remove();
  29817. };
  29818. self.selectEmptyOption = function() {
  29819. if (self.emptyOption) {
  29820. $element.val('');
  29821. setOptionSelectedStatus(self.emptyOption, true);
  29822. }
  29823. };
  29824. self.unselectEmptyOption = function() {
  29825. if (self.hasEmptyOption) {
  29826. setOptionSelectedStatus(self.emptyOption, false);
  29827. }
  29828. };
  29829. $scope.$on('$destroy', function() {
  29830. // disable unknown option so that we don't do work when the whole select is being destroyed
  29831. self.renderUnknownOption = noop;
  29832. });
  29833. // Read the value of the select control, the implementation of this changes depending
  29834. // upon whether the select can have multiple values and whether ngOptions is at work.
  29835. self.readValue = function readSingleValue() {
  29836. var val = $element.val();
  29837. // ngValue added option values are stored in the selectValueMap, normal interpolations are not
  29838. var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;
  29839. if (self.hasOption(realVal)) {
  29840. return realVal;
  29841. }
  29842. return null;
  29843. };
  29844. // Write the value to the select control, the implementation of this changes depending
  29845. // upon whether the select can have multiple values and whether ngOptions is at work.
  29846. self.writeValue = function writeSingleValue(value) {
  29847. // Make sure to remove the selected attribute from the previously selected option
  29848. // Otherwise, screen readers might get confused
  29849. var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];
  29850. if (currentlySelectedOption) setOptionSelectedStatus(jqLite(currentlySelectedOption), false);
  29851. if (self.hasOption(value)) {
  29852. self.removeUnknownOption();
  29853. var hashedVal = hashKey(value);
  29854. $element.val(hashedVal in self.selectValueMap ? hashedVal : value);
  29855. // Set selected attribute and property on selected option for screen readers
  29856. var selectedOption = $element[0].options[$element[0].selectedIndex];
  29857. setOptionSelectedStatus(jqLite(selectedOption), true);
  29858. } else {
  29859. self.selectUnknownOrEmptyOption(value);
  29860. }
  29861. };
  29862. // Tell the select control that an option, with the given value, has been added
  29863. self.addOption = function(value, element) {
  29864. // Skip comment nodes, as they only pollute the `optionsMap`
  29865. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  29866. assertNotHasOwnProperty(value, '"option value"');
  29867. if (value === '') {
  29868. self.hasEmptyOption = true;
  29869. self.emptyOption = element;
  29870. }
  29871. var count = optionsMap.get(value) || 0;
  29872. optionsMap.set(value, count + 1);
  29873. // Only render at the end of a digest. This improves render performance when many options
  29874. // are added during a digest and ensures all relevant options are correctly marked as selected
  29875. scheduleRender();
  29876. };
  29877. // Tell the select control that an option, with the given value, has been removed
  29878. self.removeOption = function(value) {
  29879. var count = optionsMap.get(value);
  29880. if (count) {
  29881. if (count === 1) {
  29882. optionsMap.delete(value);
  29883. if (value === '') {
  29884. self.hasEmptyOption = false;
  29885. self.emptyOption = undefined;
  29886. }
  29887. } else {
  29888. optionsMap.set(value, count - 1);
  29889. }
  29890. }
  29891. };
  29892. // Check whether the select control has an option matching the given value
  29893. self.hasOption = function(value) {
  29894. return !!optionsMap.get(value);
  29895. };
  29896. /**
  29897. * @ngdoc method
  29898. * @name select.SelectController#$hasEmptyOption
  29899. *
  29900. * @description
  29901. *
  29902. * Returns `true` if the select element currently has an empty option
  29903. * element, i.e. an option that signifies that the select is empty / the selection is null.
  29904. *
  29905. */
  29906. self.$hasEmptyOption = function() {
  29907. return self.hasEmptyOption;
  29908. };
  29909. /**
  29910. * @ngdoc method
  29911. * @name select.SelectController#$isUnknownOptionSelected
  29912. *
  29913. * @description
  29914. *
  29915. * Returns `true` if the select element's unknown option is selected. The unknown option is added
  29916. * and automatically selected whenever the select model doesn't match any option.
  29917. *
  29918. */
  29919. self.$isUnknownOptionSelected = function() {
  29920. // Presence of the unknown option means it is selected
  29921. return $element[0].options[0] === self.unknownOption[0];
  29922. };
  29923. /**
  29924. * @ngdoc method
  29925. * @name select.SelectController#$isEmptyOptionSelected
  29926. *
  29927. * @description
  29928. *
  29929. * Returns `true` if the select element has an empty option and this empty option is currently
  29930. * selected. Returns `false` if the select element has no empty option or it is not selected.
  29931. *
  29932. */
  29933. self.$isEmptyOptionSelected = function() {
  29934. return self.hasEmptyOption && $element[0].options[$element[0].selectedIndex] === self.emptyOption[0];
  29935. };
  29936. self.selectUnknownOrEmptyOption = function(value) {
  29937. if (value == null && self.emptyOption) {
  29938. self.removeUnknownOption();
  29939. self.selectEmptyOption();
  29940. } else if (self.unknownOption.parent().length) {
  29941. self.updateUnknownOption(value);
  29942. } else {
  29943. self.renderUnknownOption(value);
  29944. }
  29945. };
  29946. var renderScheduled = false;
  29947. function scheduleRender() {
  29948. if (renderScheduled) return;
  29949. renderScheduled = true;
  29950. $scope.$$postDigest(function() {
  29951. renderScheduled = false;
  29952. self.ngModelCtrl.$render();
  29953. });
  29954. }
  29955. var updateScheduled = false;
  29956. function scheduleViewValueUpdate(renderAfter) {
  29957. if (updateScheduled) return;
  29958. updateScheduled = true;
  29959. $scope.$$postDigest(function() {
  29960. if ($scope.$$destroyed) return;
  29961. updateScheduled = false;
  29962. self.ngModelCtrl.$setViewValue(self.readValue());
  29963. if (renderAfter) self.ngModelCtrl.$render();
  29964. });
  29965. }
  29966. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  29967. if (optionAttrs.$attr.ngValue) {
  29968. // The value attribute is set by ngValue
  29969. var oldVal, hashedVal = NaN;
  29970. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29971. var removal;
  29972. var previouslySelected = optionElement.prop('selected');
  29973. if (isDefined(hashedVal)) {
  29974. self.removeOption(oldVal);
  29975. delete self.selectValueMap[hashedVal];
  29976. removal = true;
  29977. }
  29978. hashedVal = hashKey(newVal);
  29979. oldVal = newVal;
  29980. self.selectValueMap[hashedVal] = newVal;
  29981. self.addOption(newVal, optionElement);
  29982. // Set the attribute directly instead of using optionAttrs.$set - this stops the observer
  29983. // from firing a second time. Other $observers on value will also get the result of the
  29984. // ngValue expression, not the hashed value
  29985. optionElement.attr('value', hashedVal);
  29986. if (removal && previouslySelected) {
  29987. scheduleViewValueUpdate();
  29988. }
  29989. });
  29990. } else if (interpolateValueFn) {
  29991. // The value attribute is interpolated
  29992. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29993. // This method is overwritten in ngOptions and has side-effects!
  29994. self.readValue();
  29995. var removal;
  29996. var previouslySelected = optionElement.prop('selected');
  29997. if (isDefined(oldVal)) {
  29998. self.removeOption(oldVal);
  29999. removal = true;
  30000. }
  30001. oldVal = newVal;
  30002. self.addOption(newVal, optionElement);
  30003. if (removal && previouslySelected) {
  30004. scheduleViewValueUpdate();
  30005. }
  30006. });
  30007. } else if (interpolateTextFn) {
  30008. // The text content is interpolated
  30009. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  30010. optionAttrs.$set('value', newVal);
  30011. var previouslySelected = optionElement.prop('selected');
  30012. if (oldVal !== newVal) {
  30013. self.removeOption(oldVal);
  30014. }
  30015. self.addOption(newVal, optionElement);
  30016. if (oldVal && previouslySelected) {
  30017. scheduleViewValueUpdate();
  30018. }
  30019. });
  30020. } else {
  30021. // The value attribute is static
  30022. self.addOption(optionAttrs.value, optionElement);
  30023. }
  30024. optionAttrs.$observe('disabled', function(newVal) {
  30025. // Since model updates will also select disabled options (like ngOptions),
  30026. // we only have to handle options becoming disabled, not enabled
  30027. if (newVal === 'true' || newVal && optionElement.prop('selected')) {
  30028. if (self.multiple) {
  30029. scheduleViewValueUpdate(true);
  30030. } else {
  30031. self.ngModelCtrl.$setViewValue(null);
  30032. self.ngModelCtrl.$render();
  30033. }
  30034. }
  30035. });
  30036. optionElement.on('$destroy', function() {
  30037. var currentValue = self.readValue();
  30038. var removeValue = optionAttrs.value;
  30039. self.removeOption(removeValue);
  30040. scheduleRender();
  30041. if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
  30042. currentValue === removeValue
  30043. ) {
  30044. // When multiple (selected) options are destroyed at the same time, we don't want
  30045. // to run a model update for each of them. Instead, run a single update in the $$postDigest
  30046. scheduleViewValueUpdate(true);
  30047. }
  30048. });
  30049. };
  30050. }];
  30051. /**
  30052. * @ngdoc directive
  30053. * @name select
  30054. * @restrict E
  30055. *
  30056. * @description
  30057. * HTML `select` element with angular data-binding.
  30058. *
  30059. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  30060. * between the scope and the `<select>` control (including setting default values).
  30061. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  30062. * {@link ngOptions `ngOptions`} directives.
  30063. *
  30064. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  30065. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  30066. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  30067. * Value and textContent can be interpolated.
  30068. *
  30069. * The {@link select.SelectController select controller} exposes utility functions that can be used
  30070. * to manipulate the select's behavior.
  30071. *
  30072. * ## Matching model and option values
  30073. *
  30074. * In general, the match between the model and an option is evaluated by strictly comparing the model
  30075. * value against the value of the available options.
  30076. *
  30077. * If you are setting the option value with the option's `value` attribute, or textContent, the
  30078. * value will always be a `string` which means that the model value must also be a string.
  30079. * Otherwise the `select` directive cannot match them correctly.
  30080. *
  30081. * To bind the model to a non-string value, you can use one of the following strategies:
  30082. * - the {@link ng.ngOptions `ngOptions`} directive
  30083. * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value})
  30084. * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be
  30085. * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example})
  30086. * - model $parsers / $formatters to convert the string value
  30087. * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example})
  30088. *
  30089. * If the viewValue of `ngModel` does not match any of the options, then the control
  30090. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  30091. *
  30092. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  30093. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  30094. * option. See example below for demonstration.
  30095. *
  30096. * ## Choosing between `ngRepeat` and `ngOptions`
  30097. *
  30098. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  30099. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits:
  30100. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  30101. * comprehension expression
  30102. * - reduced memory consumption by not creating a new scope for each repeated instance
  30103. * - increased render speed by creating the options in a documentFragment instead of individually
  30104. *
  30105. * Specifically, select with repeated options slows down significantly starting at 2000 options in
  30106. * Chrome and Internet Explorer / Edge.
  30107. *
  30108. *
  30109. * @param {string} ngModel Assignable angular expression to data-bind to.
  30110. * @param {string=} name Property name of the form under which the control is published.
  30111. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  30112. * bound to the model as an array.
  30113. * @param {string=} required Sets `required` validation error key if the value is not entered.
  30114. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  30115. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  30116. * when you want to data-bind to the required attribute.
  30117. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  30118. * interaction with the select element.
  30119. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  30120. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  30121. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  30122. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  30123. *
  30124. *
  30125. * @knownIssue
  30126. *
  30127. * In Firefox, the select model is only updated when the select element is blurred. For example,
  30128. * when switching between options with the keyboard, the select model is only set to the
  30129. * currently selected option when the select is blurred, e.g via tab key or clicking the mouse
  30130. * outside the select.
  30131. *
  30132. * This is due to an ambiguity in the select element specification. See the
  30133. * [issue on the Firefox bug tracker](https://bugzilla.mozilla.org/show_bug.cgi?id=126379)
  30134. * for more information, and this
  30135. * [Github comment for a workaround](https://github.com/angular/angular.js/issues/9134#issuecomment-130800488)
  30136. *
  30137. * @example
  30138. * ### Simple `select` elements with static options
  30139. *
  30140. * <example name="static-select" module="staticSelect">
  30141. * <file name="index.html">
  30142. * <div ng-controller="ExampleController">
  30143. * <form name="myForm">
  30144. * <label for="singleSelect"> Single select: </label><br>
  30145. * <select name="singleSelect" ng-model="data.singleSelect">
  30146. * <option value="option-1">Option 1</option>
  30147. * <option value="option-2">Option 2</option>
  30148. * </select><br>
  30149. *
  30150. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  30151. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  30152. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  30153. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  30154. * <option value="option-2">Option 2</option>
  30155. * </select><br>
  30156. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  30157. * <tt>singleSelect = {{data.singleSelect}}</tt>
  30158. *
  30159. * <hr>
  30160. * <label for="multipleSelect"> Multiple select: </label><br>
  30161. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  30162. * <option value="option-1">Option 1</option>
  30163. * <option value="option-2">Option 2</option>
  30164. * <option value="option-3">Option 3</option>
  30165. * </select><br>
  30166. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  30167. * </form>
  30168. * </div>
  30169. * </file>
  30170. * <file name="app.js">
  30171. * angular.module('staticSelect', [])
  30172. * .controller('ExampleController', ['$scope', function($scope) {
  30173. * $scope.data = {
  30174. * singleSelect: null,
  30175. * multipleSelect: [],
  30176. * option1: 'option-1'
  30177. * };
  30178. *
  30179. * $scope.forceUnknownOption = function() {
  30180. * $scope.data.singleSelect = 'nonsense';
  30181. * };
  30182. * }]);
  30183. * </file>
  30184. *</example>
  30185. *
  30186. * ### Using `ngRepeat` to generate `select` options
  30187. * <example name="select-ngrepeat" module="ngrepeatSelect">
  30188. * <file name="index.html">
  30189. * <div ng-controller="ExampleController">
  30190. * <form name="myForm">
  30191. * <label for="repeatSelect"> Repeat select: </label>
  30192. * <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  30193. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  30194. * </select>
  30195. * </form>
  30196. * <hr>
  30197. * <tt>model = {{data.model}}</tt><br/>
  30198. * </div>
  30199. * </file>
  30200. * <file name="app.js">
  30201. * angular.module('ngrepeatSelect', [])
  30202. * .controller('ExampleController', ['$scope', function($scope) {
  30203. * $scope.data = {
  30204. * model: null,
  30205. * availableOptions: [
  30206. * {id: '1', name: 'Option A'},
  30207. * {id: '2', name: 'Option B'},
  30208. * {id: '3', name: 'Option C'}
  30209. * ]
  30210. * };
  30211. * }]);
  30212. * </file>
  30213. *</example>
  30214. *
  30215. * ### Using `ngValue` to bind the model to an array of objects
  30216. * <example name="select-ngvalue" module="ngvalueSelect">
  30217. * <file name="index.html">
  30218. * <div ng-controller="ExampleController">
  30219. * <form name="myForm">
  30220. * <label for="ngvalueselect"> ngvalue select: </label>
  30221. * <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
  30222. * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
  30223. * </select>
  30224. * </form>
  30225. * <hr>
  30226. * <pre>model = {{data.model | json}}</pre><br/>
  30227. * </div>
  30228. * </file>
  30229. * <file name="app.js">
  30230. * angular.module('ngvalueSelect', [])
  30231. * .controller('ExampleController', ['$scope', function($scope) {
  30232. * $scope.data = {
  30233. * model: null,
  30234. * availableOptions: [
  30235. {value: 'myString', name: 'string'},
  30236. {value: 1, name: 'integer'},
  30237. {value: true, name: 'boolean'},
  30238. {value: null, name: 'null'},
  30239. {value: {prop: 'value'}, name: 'object'},
  30240. {value: ['a'], name: 'array'}
  30241. * ]
  30242. * };
  30243. * }]);
  30244. * </file>
  30245. *</example>
  30246. *
  30247. * ### Using `select` with `ngOptions` and setting a default value
  30248. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  30249. *
  30250. * <example name="select-with-default-values" module="defaultValueSelect">
  30251. * <file name="index.html">
  30252. * <div ng-controller="ExampleController">
  30253. * <form name="myForm">
  30254. * <label for="mySelect">Make a choice:</label>
  30255. * <select name="mySelect" id="mySelect"
  30256. * ng-options="option.name for option in data.availableOptions track by option.id"
  30257. * ng-model="data.selectedOption"></select>
  30258. * </form>
  30259. * <hr>
  30260. * <tt>option = {{data.selectedOption}}</tt><br/>
  30261. * </div>
  30262. * </file>
  30263. * <file name="app.js">
  30264. * angular.module('defaultValueSelect', [])
  30265. * .controller('ExampleController', ['$scope', function($scope) {
  30266. * $scope.data = {
  30267. * availableOptions: [
  30268. * {id: '1', name: 'Option A'},
  30269. * {id: '2', name: 'Option B'},
  30270. * {id: '3', name: 'Option C'}
  30271. * ],
  30272. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  30273. * };
  30274. * }]);
  30275. * </file>
  30276. *</example>
  30277. *
  30278. *
  30279. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  30280. *
  30281. * <example name="select-with-non-string-options" module="nonStringSelect">
  30282. * <file name="index.html">
  30283. * <select ng-model="model.id" convert-to-number>
  30284. * <option value="0">Zero</option>
  30285. * <option value="1">One</option>
  30286. * <option value="2">Two</option>
  30287. * </select>
  30288. * {{ model }}
  30289. * </file>
  30290. * <file name="app.js">
  30291. * angular.module('nonStringSelect', [])
  30292. * .run(function($rootScope) {
  30293. * $rootScope.model = { id: 2 };
  30294. * })
  30295. * .directive('convertToNumber', function() {
  30296. * return {
  30297. * require: 'ngModel',
  30298. * link: function(scope, element, attrs, ngModel) {
  30299. * ngModel.$parsers.push(function(val) {
  30300. * return parseInt(val, 10);
  30301. * });
  30302. * ngModel.$formatters.push(function(val) {
  30303. * return '' + val;
  30304. * });
  30305. * }
  30306. * };
  30307. * });
  30308. * </file>
  30309. * <file name="protractor.js" type="protractor">
  30310. * it('should initialize to model', function() {
  30311. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  30312. * });
  30313. * </file>
  30314. * </example>
  30315. *
  30316. */
  30317. var selectDirective = function() {
  30318. return {
  30319. restrict: 'E',
  30320. require: ['select', '?ngModel'],
  30321. controller: SelectController,
  30322. priority: 1,
  30323. link: {
  30324. pre: selectPreLink,
  30325. post: selectPostLink
  30326. }
  30327. };
  30328. function selectPreLink(scope, element, attr, ctrls) {
  30329. var selectCtrl = ctrls[0];
  30330. var ngModelCtrl = ctrls[1];
  30331. // if ngModel is not defined, we don't need to do anything but set the registerOption
  30332. // function to noop, so options don't get added internally
  30333. if (!ngModelCtrl) {
  30334. selectCtrl.registerOption = noop;
  30335. return;
  30336. }
  30337. selectCtrl.ngModelCtrl = ngModelCtrl;
  30338. // When the selected item(s) changes we delegate getting the value of the select control
  30339. // to the `readValue` method, which can be changed if the select can have multiple
  30340. // selected values or if the options are being generated by `ngOptions`
  30341. element.on('change', function() {
  30342. selectCtrl.removeUnknownOption();
  30343. scope.$apply(function() {
  30344. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  30345. });
  30346. });
  30347. // If the select allows multiple values then we need to modify how we read and write
  30348. // values from and to the control; also what it means for the value to be empty and
  30349. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  30350. // doesn't trigger rendering if only an item in the array changes.
  30351. if (attr.multiple) {
  30352. selectCtrl.multiple = true;
  30353. // Read value now needs to check each option to see if it is selected
  30354. selectCtrl.readValue = function readMultipleValue() {
  30355. var array = [];
  30356. forEach(element.find('option'), function(option) {
  30357. if (option.selected && !option.disabled) {
  30358. var val = option.value;
  30359. array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
  30360. }
  30361. });
  30362. return array;
  30363. };
  30364. // Write value now needs to set the selected property of each matching option
  30365. selectCtrl.writeValue = function writeMultipleValue(value) {
  30366. forEach(element.find('option'), function(option) {
  30367. var shouldBeSelected = !!value && (includes(value, option.value) ||
  30368. includes(value, selectCtrl.selectValueMap[option.value]));
  30369. var currentlySelected = option.selected;
  30370. // Support: IE 9-11 only, Edge 12-15+
  30371. // In IE and Edge adding options to the selection via shift+click/UP/DOWN
  30372. // will de-select already selected options if "selected" on those options was set
  30373. // more than once (i.e. when the options were already selected)
  30374. // So we only modify the selected property if necessary.
  30375. // Note: this behavior cannot be replicated via unit tests because it only shows in the
  30376. // actual user interface.
  30377. if (shouldBeSelected !== currentlySelected) {
  30378. setOptionSelectedStatus(jqLite(option), shouldBeSelected);
  30379. }
  30380. });
  30381. };
  30382. // we have to do it on each watch since ngModel watches reference, but
  30383. // we need to work of an array, so we need to see if anything was inserted/removed
  30384. var lastView, lastViewRef = NaN;
  30385. scope.$watch(function selectMultipleWatch() {
  30386. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  30387. lastView = shallowCopy(ngModelCtrl.$viewValue);
  30388. ngModelCtrl.$render();
  30389. }
  30390. lastViewRef = ngModelCtrl.$viewValue;
  30391. });
  30392. // If we are a multiple select then value is now a collection
  30393. // so the meaning of $isEmpty changes
  30394. ngModelCtrl.$isEmpty = function(value) {
  30395. return !value || value.length === 0;
  30396. };
  30397. }
  30398. }
  30399. function selectPostLink(scope, element, attrs, ctrls) {
  30400. // if ngModel is not defined, we don't need to do anything
  30401. var ngModelCtrl = ctrls[1];
  30402. if (!ngModelCtrl) return;
  30403. var selectCtrl = ctrls[0];
  30404. // We delegate rendering to the `writeValue` method, which can be changed
  30405. // if the select can have multiple selected values or if the options are being
  30406. // generated by `ngOptions`.
  30407. // This must be done in the postLink fn to prevent $render to be called before
  30408. // all nodes have been linked correctly.
  30409. ngModelCtrl.$render = function() {
  30410. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  30411. };
  30412. }
  30413. };
  30414. // The option directive is purely designed to communicate the existence (or lack of)
  30415. // of dynamically created (and destroyed) option elements to their containing select
  30416. // directive via its controller.
  30417. var optionDirective = ['$interpolate', function($interpolate) {
  30418. return {
  30419. restrict: 'E',
  30420. priority: 100,
  30421. compile: function(element, attr) {
  30422. var interpolateValueFn, interpolateTextFn;
  30423. if (isDefined(attr.ngValue)) {
  30424. // Will be handled by registerOption
  30425. } else if (isDefined(attr.value)) {
  30426. // If the value attribute is defined, check if it contains an interpolation
  30427. interpolateValueFn = $interpolate(attr.value, true);
  30428. } else {
  30429. // If the value attribute is not defined then we fall back to the
  30430. // text content of the option element, which may be interpolated
  30431. interpolateTextFn = $interpolate(element.text(), true);
  30432. if (!interpolateTextFn) {
  30433. attr.$set('value', element.text());
  30434. }
  30435. }
  30436. return function(scope, element, attr) {
  30437. // This is an optimization over using ^^ since we don't want to have to search
  30438. // all the way to the root of the DOM for every single option element
  30439. var selectCtrlName = '$selectController',
  30440. parent = element.parent(),
  30441. selectCtrl = parent.data(selectCtrlName) ||
  30442. parent.parent().data(selectCtrlName); // in case we are in optgroup
  30443. if (selectCtrl) {
  30444. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  30445. }
  30446. };
  30447. }
  30448. };
  30449. }];
  30450. /**
  30451. * @ngdoc directive
  30452. * @name ngRequired
  30453. * @restrict A
  30454. *
  30455. * @description
  30456. *
  30457. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30458. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  30459. * applied to custom controls.
  30460. *
  30461. * The directive sets the `required` attribute on the element if the Angular expression inside
  30462. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  30463. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  30464. * for more info.
  30465. *
  30466. * The validator will set the `required` error key to true if the `required` attribute is set and
  30467. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  30468. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  30469. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  30470. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  30471. *
  30472. * @example
  30473. * <example name="ngRequiredDirective" module="ngRequiredExample">
  30474. * <file name="index.html">
  30475. * <script>
  30476. * angular.module('ngRequiredExample', [])
  30477. * .controller('ExampleController', ['$scope', function($scope) {
  30478. * $scope.required = true;
  30479. * }]);
  30480. * </script>
  30481. * <div ng-controller="ExampleController">
  30482. * <form name="form">
  30483. * <label for="required">Toggle required: </label>
  30484. * <input type="checkbox" ng-model="required" id="required" />
  30485. * <br>
  30486. * <label for="input">This input must be filled if `required` is true: </label>
  30487. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  30488. * <hr>
  30489. * required error set? = <code>{{form.input.$error.required}}</code><br>
  30490. * model = <code>{{model}}</code>
  30491. * </form>
  30492. * </div>
  30493. * </file>
  30494. * <file name="protractor.js" type="protractor">
  30495. var required = element(by.binding('form.input.$error.required'));
  30496. var model = element(by.binding('model'));
  30497. var input = element(by.id('input'));
  30498. it('should set the required error', function() {
  30499. expect(required.getText()).toContain('true');
  30500. input.sendKeys('123');
  30501. expect(required.getText()).not.toContain('true');
  30502. expect(model.getText()).toContain('123');
  30503. });
  30504. * </file>
  30505. * </example>
  30506. */
  30507. var requiredDirective = function() {
  30508. return {
  30509. restrict: 'A',
  30510. require: '?ngModel',
  30511. link: function(scope, elm, attr, ctrl) {
  30512. if (!ctrl) return;
  30513. attr.required = true; // force truthy in case we are on non input element
  30514. ctrl.$validators.required = function(modelValue, viewValue) {
  30515. return !attr.required || !ctrl.$isEmpty(viewValue);
  30516. };
  30517. attr.$observe('required', function() {
  30518. ctrl.$validate();
  30519. });
  30520. }
  30521. };
  30522. };
  30523. /**
  30524. * @ngdoc directive
  30525. * @name ngPattern
  30526. *
  30527. * @description
  30528. *
  30529. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30530. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30531. *
  30532. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30533. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  30534. * `ngPattern` attribute value:
  30535. * * If the expression evaluates to a RegExp object, then this is used directly.
  30536. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  30537. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  30538. *
  30539. * <div class="alert alert-info">
  30540. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  30541. * start at the index of the last search's match, thus not taking the whole input value into
  30542. * account.
  30543. * </div>
  30544. *
  30545. * <div class="alert alert-info">
  30546. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  30547. * differences:
  30548. * <ol>
  30549. * <li>
  30550. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  30551. * not available.
  30552. * </li>
  30553. * <li>
  30554. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  30555. * interpolated.
  30556. * </li>
  30557. * </ol>
  30558. * </div>
  30559. *
  30560. * @example
  30561. * <example name="ngPatternDirective" module="ngPatternExample">
  30562. * <file name="index.html">
  30563. * <script>
  30564. * angular.module('ngPatternExample', [])
  30565. * .controller('ExampleController', ['$scope', function($scope) {
  30566. * $scope.regex = '\\d+';
  30567. * }]);
  30568. * </script>
  30569. * <div ng-controller="ExampleController">
  30570. * <form name="form">
  30571. * <label for="regex">Set a pattern (regex string): </label>
  30572. * <input type="text" ng-model="regex" id="regex" />
  30573. * <br>
  30574. * <label for="input">This input is restricted by the current pattern: </label>
  30575. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  30576. * <hr>
  30577. * input valid? = <code>{{form.input.$valid}}</code><br>
  30578. * model = <code>{{model}}</code>
  30579. * </form>
  30580. * </div>
  30581. * </file>
  30582. * <file name="protractor.js" type="protractor">
  30583. var model = element(by.binding('model'));
  30584. var input = element(by.id('input'));
  30585. it('should validate the input with the default pattern', function() {
  30586. input.sendKeys('aaa');
  30587. expect(model.getText()).not.toContain('aaa');
  30588. input.clear().then(function() {
  30589. input.sendKeys('123');
  30590. expect(model.getText()).toContain('123');
  30591. });
  30592. });
  30593. * </file>
  30594. * </example>
  30595. */
  30596. var patternDirective = function() {
  30597. return {
  30598. restrict: 'A',
  30599. require: '?ngModel',
  30600. link: function(scope, elm, attr, ctrl) {
  30601. if (!ctrl) return;
  30602. var regexp, patternExp = attr.ngPattern || attr.pattern;
  30603. attr.$observe('pattern', function(regex) {
  30604. if (isString(regex) && regex.length > 0) {
  30605. regex = new RegExp('^' + regex + '$');
  30606. }
  30607. if (regex && !regex.test) {
  30608. throw minErr('ngPattern')('noregexp',
  30609. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  30610. regex, startingTag(elm));
  30611. }
  30612. regexp = regex || undefined;
  30613. ctrl.$validate();
  30614. });
  30615. ctrl.$validators.pattern = function(modelValue, viewValue) {
  30616. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  30617. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  30618. };
  30619. }
  30620. };
  30621. };
  30622. /**
  30623. * @ngdoc directive
  30624. * @name ngMaxlength
  30625. *
  30626. * @description
  30627. *
  30628. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30629. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30630. *
  30631. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30632. * is longer than the integer obtained by evaluating the Angular expression given in the
  30633. * `ngMaxlength` attribute value.
  30634. *
  30635. * <div class="alert alert-info">
  30636. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  30637. * differences:
  30638. * <ol>
  30639. * <li>
  30640. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  30641. * validation is not available.
  30642. * </li>
  30643. * <li>
  30644. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  30645. * interpolated.
  30646. * </li>
  30647. * </ol>
  30648. * </div>
  30649. *
  30650. * @example
  30651. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  30652. * <file name="index.html">
  30653. * <script>
  30654. * angular.module('ngMaxlengthExample', [])
  30655. * .controller('ExampleController', ['$scope', function($scope) {
  30656. * $scope.maxlength = 5;
  30657. * }]);
  30658. * </script>
  30659. * <div ng-controller="ExampleController">
  30660. * <form name="form">
  30661. * <label for="maxlength">Set a maxlength: </label>
  30662. * <input type="number" ng-model="maxlength" id="maxlength" />
  30663. * <br>
  30664. * <label for="input">This input is restricted by the current maxlength: </label>
  30665. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  30666. * <hr>
  30667. * input valid? = <code>{{form.input.$valid}}</code><br>
  30668. * model = <code>{{model}}</code>
  30669. * </form>
  30670. * </div>
  30671. * </file>
  30672. * <file name="protractor.js" type="protractor">
  30673. var model = element(by.binding('model'));
  30674. var input = element(by.id('input'));
  30675. it('should validate the input with the default maxlength', function() {
  30676. input.sendKeys('abcdef');
  30677. expect(model.getText()).not.toContain('abcdef');
  30678. input.clear().then(function() {
  30679. input.sendKeys('abcde');
  30680. expect(model.getText()).toContain('abcde');
  30681. });
  30682. });
  30683. * </file>
  30684. * </example>
  30685. */
  30686. var maxlengthDirective = function() {
  30687. return {
  30688. restrict: 'A',
  30689. require: '?ngModel',
  30690. link: function(scope, elm, attr, ctrl) {
  30691. if (!ctrl) return;
  30692. var maxlength = -1;
  30693. attr.$observe('maxlength', function(value) {
  30694. var intVal = toInt(value);
  30695. maxlength = isNumberNaN(intVal) ? -1 : intVal;
  30696. ctrl.$validate();
  30697. });
  30698. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  30699. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  30700. };
  30701. }
  30702. };
  30703. };
  30704. /**
  30705. * @ngdoc directive
  30706. * @name ngMinlength
  30707. *
  30708. * @description
  30709. *
  30710. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30711. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30712. *
  30713. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30714. * is shorter than the integer obtained by evaluating the Angular expression given in the
  30715. * `ngMinlength` attribute value.
  30716. *
  30717. * <div class="alert alert-info">
  30718. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  30719. * differences:
  30720. * <ol>
  30721. * <li>
  30722. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  30723. * validation is not available.
  30724. * </li>
  30725. * <li>
  30726. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  30727. * interpolated.
  30728. * </li>
  30729. * </ol>
  30730. * </div>
  30731. *
  30732. * @example
  30733. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  30734. * <file name="index.html">
  30735. * <script>
  30736. * angular.module('ngMinlengthExample', [])
  30737. * .controller('ExampleController', ['$scope', function($scope) {
  30738. * $scope.minlength = 3;
  30739. * }]);
  30740. * </script>
  30741. * <div ng-controller="ExampleController">
  30742. * <form name="form">
  30743. * <label for="minlength">Set a minlength: </label>
  30744. * <input type="number" ng-model="minlength" id="minlength" />
  30745. * <br>
  30746. * <label for="input">This input is restricted by the current minlength: </label>
  30747. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  30748. * <hr>
  30749. * input valid? = <code>{{form.input.$valid}}</code><br>
  30750. * model = <code>{{model}}</code>
  30751. * </form>
  30752. * </div>
  30753. * </file>
  30754. * <file name="protractor.js" type="protractor">
  30755. var model = element(by.binding('model'));
  30756. var input = element(by.id('input'));
  30757. it('should validate the input with the default minlength', function() {
  30758. input.sendKeys('ab');
  30759. expect(model.getText()).not.toContain('ab');
  30760. input.sendKeys('abc');
  30761. expect(model.getText()).toContain('abc');
  30762. });
  30763. * </file>
  30764. * </example>
  30765. */
  30766. var minlengthDirective = function() {
  30767. return {
  30768. restrict: 'A',
  30769. require: '?ngModel',
  30770. link: function(scope, elm, attr, ctrl) {
  30771. if (!ctrl) return;
  30772. var minlength = 0;
  30773. attr.$observe('minlength', function(value) {
  30774. minlength = toInt(value) || 0;
  30775. ctrl.$validate();
  30776. });
  30777. ctrl.$validators.minlength = function(modelValue, viewValue) {
  30778. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  30779. };
  30780. }
  30781. };
  30782. };
  30783. if (window.angular.bootstrap) {
  30784. // AngularJS is already loaded, so we can return here...
  30785. if (window.console) {
  30786. console.log('WARNING: Tried to load angular more than once.');
  30787. }
  30788. return;
  30789. }
  30790. // try to bind to jquery now so that one can write jqLite(fn)
  30791. // but we will rebind on bootstrap again.
  30792. bindJQuery();
  30793. publishExternalAPI(angular);
  30794. angular.module("ngLocale", [], ["$provide", function($provide) {
  30795. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  30796. function getDecimals(n) {
  30797. n = n + '';
  30798. var i = n.indexOf('.');
  30799. return (i == -1) ? 0 : n.length - i - 1;
  30800. }
  30801. function getVF(n, opt_precision) {
  30802. var v = opt_precision;
  30803. if (undefined === v) {
  30804. v = Math.min(getDecimals(n), 3);
  30805. }
  30806. var base = Math.pow(10, v);
  30807. var f = ((n * base) | 0) % base;
  30808. return {v: v, f: f};
  30809. }
  30810. $provide.value("$locale", {
  30811. "DATETIME_FORMATS": {
  30812. "AMPMS": [
  30813. "AM",
  30814. "PM"
  30815. ],
  30816. "DAY": [
  30817. "Sunday",
  30818. "Monday",
  30819. "Tuesday",
  30820. "Wednesday",
  30821. "Thursday",
  30822. "Friday",
  30823. "Saturday"
  30824. ],
  30825. "ERANAMES": [
  30826. "Before Christ",
  30827. "Anno Domini"
  30828. ],
  30829. "ERAS": [
  30830. "BC",
  30831. "AD"
  30832. ],
  30833. "FIRSTDAYOFWEEK": 6,
  30834. "MONTH": [
  30835. "January",
  30836. "February",
  30837. "March",
  30838. "April",
  30839. "May",
  30840. "June",
  30841. "July",
  30842. "August",
  30843. "September",
  30844. "October",
  30845. "November",
  30846. "December"
  30847. ],
  30848. "SHORTDAY": [
  30849. "Sun",
  30850. "Mon",
  30851. "Tue",
  30852. "Wed",
  30853. "Thu",
  30854. "Fri",
  30855. "Sat"
  30856. ],
  30857. "SHORTMONTH": [
  30858. "Jan",
  30859. "Feb",
  30860. "Mar",
  30861. "Apr",
  30862. "May",
  30863. "Jun",
  30864. "Jul",
  30865. "Aug",
  30866. "Sep",
  30867. "Oct",
  30868. "Nov",
  30869. "Dec"
  30870. ],
  30871. "STANDALONEMONTH": [
  30872. "January",
  30873. "February",
  30874. "March",
  30875. "April",
  30876. "May",
  30877. "June",
  30878. "July",
  30879. "August",
  30880. "September",
  30881. "October",
  30882. "November",
  30883. "December"
  30884. ],
  30885. "WEEKENDRANGE": [
  30886. 5,
  30887. 6
  30888. ],
  30889. "fullDate": "EEEE, MMMM d, y",
  30890. "longDate": "MMMM d, y",
  30891. "medium": "MMM d, y h:mm:ss a",
  30892. "mediumDate": "MMM d, y",
  30893. "mediumTime": "h:mm:ss a",
  30894. "short": "M/d/yy h:mm a",
  30895. "shortDate": "M/d/yy",
  30896. "shortTime": "h:mm a"
  30897. },
  30898. "NUMBER_FORMATS": {
  30899. "CURRENCY_SYM": "$",
  30900. "DECIMAL_SEP": ".",
  30901. "GROUP_SEP": ",",
  30902. "PATTERNS": [
  30903. {
  30904. "gSize": 3,
  30905. "lgSize": 3,
  30906. "maxFrac": 3,
  30907. "minFrac": 0,
  30908. "minInt": 1,
  30909. "negPre": "-",
  30910. "negSuf": "",
  30911. "posPre": "",
  30912. "posSuf": ""
  30913. },
  30914. {
  30915. "gSize": 3,
  30916. "lgSize": 3,
  30917. "maxFrac": 2,
  30918. "minFrac": 2,
  30919. "minInt": 1,
  30920. "negPre": "-\u00a4",
  30921. "negSuf": "",
  30922. "posPre": "\u00a4",
  30923. "posSuf": ""
  30924. }
  30925. ]
  30926. },
  30927. "id": "en-us",
  30928. "localeID": "en_US",
  30929. "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;}
  30930. });
  30931. }]);
  30932. jqLite(function() {
  30933. angularInit(window.document, bootstrap);
  30934. });
  30935. })(window);
  30936. !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>');